From f856d36e17afbfd0b7c2964296ece583321fb6f2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:13:09 +0400 Subject: [PATCH 01/26] Test publishing UK release builds into build folders through the emitter Failing tests first for hand-over step H2c. UK national, dense and local-area release manifests name `release` and `build` as strings, record `built_at` and the built-with packages at the top level, and give each artifact a `role` without a `revision`; the build module hands a build to the emitter's `publish_release` and treats it as current only when a published receipt names it; the loader reads `releases.json`; the tagged publisher refuses UK releases and offers no line promotion. The fake emitter client applies release changes with the interface's shared checks. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_gate_battery_contract_pins.py | 7 +- .../uk/test_uk_dense_release_assembler.py | 42 +- .../uk/test_uk_release_assembler.py | 85 +-- .../uk/test_uk_release_publication.py | 470 +++++++++++++++++ .../tests/engine_free/shared/test_contract.py | 258 +++++++-- .../tests/engine_free/shared/test_loader.py | 490 ++++++++++++------ .../shared/test_local_area_contract.py | 69 ++- .../engine_free/shared/test_publish_guard.py | 80 --- .../tests/engine_free/shared/test_registry.py | 26 +- .../tests/engine_free/shared/test_release.py | 392 +++++++------- .../uk/test_uk_dense_release_contract.py | 138 ++++- test_support/microcosm_build/emitter.py | 176 ++++++- test_support/microcosm_data/build_folders.py | 90 ++++ test_support/microcosm_data/release.py | 33 +- 14 files changed, 1757 insertions(+), 599 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py create mode 100644 test_support/microcosm_data/build_folders.py diff --git a/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py b/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py index e2661ef8ff..90e0711609 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py @@ -385,10 +385,9 @@ def test_release_id_mirrors_the_build_shard(self) -> None: from microcosm.build.uk_runtime.release_identity import UK_DENSE_RELEASE_ID assert data_contract._UK_DENSE_RELEASE_ID == UK_DENSE_RELEASE_ID - assert data_contract._UK_DENSE_CUT_TAG_RE.fullmatch( - f"{UK_DENSE_RELEASE_ID}-20260903T105422Z-ca611e43" - ) - assert data_contract._UK_DENSE_CUT_TAG_RE.fullmatch(UK_DENSE_RELEASE_ID) is None + # Its builds publish into their own folders, with no tag to match. + assert data_contract.publishes_to_build_folder(UK_DENSE_RELEASE_ID) + assert not hasattr(data_contract, "_UK_DENSE_CUT_TAG_RE") def test_dataset_filename_mirrors_the_assembler(self) -> None: import importlib.util diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py index 5d1d911f01..c30f1aa1e9 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py @@ -7,6 +7,7 @@ import hmac import importlib.util import json +import shlex from pathlib import Path import pytest @@ -568,7 +569,8 @@ def test_assembler_stages_a_contract_valid_dense_release( summary = json.loads(capsys.readouterr().out) release_dir = out / UK_DENSE_RELEASE_ID assert summary["release_id"] == UK_DENSE_RELEASE_ID - assert summary["cut_tag"] == f"{UK_DENSE_RELEASE_ID}-20260903T105422Z-ca611e43" + assert (summary["release"], summary["build"]) == (UK_DENSE_RELEASE_ID, ATTEMPT) + assert "cut_tag" not in summary assert release_dir.is_dir() for name in dc._UK_DENSE_REQUIRED_RELEASE_FILES: assert (release_dir / name).is_file(), name @@ -614,7 +616,18 @@ def test_assembler_stages_a_contract_valid_dense_release( shipped["reviewed_exclusions_stood_on"] == coverage["signed_deferrals"]["reviewed_exclusions"] ) - assert "--tag-only" in summary["publish_command"] + # Each new dense build becomes current when it is published. + assert shlex.split(summary["publish_command"]) == [ + "uv", + "run", + "microcosm-publish-release-build", + str(release_dir), + "--repo-id", + "policyengine/populace-uk-private", + "--artifact-root", + str(candidate), + "--make-current", + ] published = candidate / "microcosm_uk_2024_25_dense.h5" assert ( published.read_bytes() @@ -637,10 +650,24 @@ def test_assembler_stages_a_contract_valid_dense_release( ] is False ) - assert ( - manifest["artifacts"]["microcosm_uk_2024_25_dense"]["revision"] - == summary["cut_tag"] + # The build publishes into its own folder: both manifests name the release + # and the build (the calibration attempt), and nothing names a tag. + build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) + for document in (build_manifest, manifest): + assert (document["release"], document["build"]) == ( + UK_DENSE_RELEASE_ID, + ATTEMPT, + ) + assert not {"build_id", "attempt_id", "cut_tag"} & set(document) + assert manifest["built_at"] == build_manifest["created_at"] + assert manifest["built_with_model_package"]["name"] == "policyengine-uk" + assert manifest["built_with_core_package"]["name"] == "policyengine-core" + assert not any("revision" in entry for entry in manifest["artifacts"].values()) + assert manifest["artifacts"]["microcosm_uk_2024_25_dense"]["role"] == "dataset" + assert manifest["artifacts"]["calibration_diagnostics"]["role"] == ( + "calibration_diagnostics" ) + assert manifest["artifacts"]["uk_local_gates"]["role"] == "uk_local_gates" assert ( manifest["artifacts"]["microcosm_uk_2024_25_dense"]["repo_id"] == "policyengine/populace-uk-private" @@ -664,13 +691,8 @@ def test_assembler_stages_a_contract_valid_dense_release( assert set(gate_summary["diagnostic_gates"]) == set(UK_LOCAL_GATE_SCOPE) - set( dc._UK_DENSE_RELEASE_BLOCKING_IDS ) - assert ( - "--no-latest" in summary["publish_command"] - and "populace-uk-private" in summary["publish_command"] - ) # The national assembler's rule: the run's staging receipt rides into the # build manifest unchanged, where publication reads it. - build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) assert build_manifest["staging"] == _staging_delivery() # The contract re-validates the finished directory, and so does the pre-flight. dc.validate_release_dir(release_dir) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py index 68f4fc644a..a0c2925c67 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py @@ -58,7 +58,6 @@ def _load_fixture_module(): #: assembler rederives the SPI Public Use Tape marker from them. _SPINE_STAGES = tuple(stage.stage for stage in load_country_spec("uk").sources.stages) _ATTEMPT_ID = "uk-frs-calibration-attempt-20260828T101112Z-1a2b3c4d" -_CUT_TAG = f"{UK_NATIONAL_RELEASE_ID}-20260828T101112Z-1a2b3c4d" def _load_driver_module(): @@ -404,8 +403,17 @@ def test_assemble_green_release_dir(assembler_inputs, capsys) -> None: "last_error_code": None, "opt_out_reason": "test fixture deliberately disables staging", } - assert build_manifest["attempt_id"] == _ATTEMPT_ID - assert build_manifest["cut_tag"] == _CUT_TAG + # The build publishes into its own folder: both manifests name the release + # and the build (the calibration attempt), and nothing names a tag. + for manifest in (build_manifest, release_manifest): + assert (manifest["release"], manifest["build"]) == ( + UK_NATIONAL_RELEASE_ID, + _ATTEMPT_ID, + ) + assert not {"build_id", "attempt_id", "cut_tag"} & set(manifest) + assert release_manifest["built_at"] == build_manifest["created_at"] + assert release_manifest["built_with_core_package"]["name"] == "policyengine-core" + assert release_manifest["built_with_model_package"]["name"] == "policyengine-uk" assert release_manifest["default_datasets"] == {"national": driver._DATASET_KEY} assert release_manifest["artifacts"][driver._DATASET_KEY]["path"] == ( driver._DATASET_FILENAME @@ -414,8 +422,20 @@ def test_assemble_green_release_dir(assembler_inputs, capsys) -> None: release_manifest["artifacts"][f"{driver._DATASET_KEY}_calibration"]["path"] == f"{driver._DATASET_KEY}_calibration.npz" ) - assert {entry["revision"] for entry in release_manifest["artifacts"].values()} == { - _CUT_TAG + assert not any( + "revision" in entry for entry in release_manifest["artifacts"].values() + ) + assert { + key: entry["role"] for key, entry in release_manifest["artifacts"].items() + } == { + driver._DATASET_KEY: "dataset", + f"{driver._DATASET_KEY}_calibration": "calibration_weights", + "calibration_diagnostics": "calibration_diagnostics", + "release_certification": "release_certification", + "terminal_gates": "terminal_gates", + "release_cut_gates": "release_cut_gates", + "spine_gates": "spine_gates", + "score_vs_enhanced_frs": "score_vs_enhanced_frs", } assert "dataset_role" not in release_manifest # The spine ran the SPI stages, so the release says it rests on the tape, @@ -434,43 +454,34 @@ def test_assemble_green_release_dir(assembler_inputs, capsys) -> None: assert ( release_dir / "release_certification.json" ).read_bytes() == assembler_inputs["certification"].read_bytes() - assert summary["cut_tag"] == _CUT_TAG + assert (summary["release"], summary["build"]) == ( + UK_NATIONAL_RELEASE_ID, + _ATTEMPT_ID, + ) + assert "cut_tag" not in summary assert summary["release_dir"] == str(release_dir) - # The command is rendered shell-safe; parse it back rather than comparing - # one quoting of it. + # The commands are rendered shell-safe; parse them back rather than + # comparing one quoting. The publication lists the build without making + # it current; the reviewed promotion is the separate second command. assert shlex.split(summary["publish_command"]) == [ "uv", "run", - "python", - "-m", - "microcosm.data.publish_cli", + "microcosm-publish-release-build", str(release_dir), "--repo-id", "policyengine/populace-uk-private", "--artifact-root", str(assembler_inputs["candidate"].parent), - "--no-latest", - "--tag-name", - _CUT_TAG, ] - promote_command = shlex.split(summary["promote_command"]) - assert promote_command == [ + assert shlex.split(summary["promote_command"]) == [ "uv", "run", - "python", - "-m", - "microcosm.data.publish_cli", + "microcosm-publish-release-build", str(release_dir), "--repo-id", "policyengine/populace-uk-private", - "--artifact-root", - str(assembler_inputs["candidate"].parent), - "--promote-line", - "national", - "--tag-name", - _CUT_TAG, + "--promote", ] - assert "--no-latest" not in promote_command def test_assemble_preserves_successful_version_2_delivery( @@ -597,10 +608,15 @@ def test_assemble_refuses_missing_score_receipt(assembler_inputs) -> None: _load_driver_module().main(assembler_inputs["argv"]) -def test_assemble_refuses_unprefixed_cut_tag(assembler_inputs) -> None: - with pytest.raises(SystemExit, match="--cut-tag must be"): +def test_assemble_takes_no_cut_tag(assembler_inputs) -> None: + """A build in its own folder has no tag to name.""" + with pytest.raises(SystemExit): _load_driver_module().main( - [*assembler_inputs["argv"], "--cut-tag", "not-a-national-cut"] + [ + *assembler_inputs["argv"], + "--cut-tag", + f"{UK_NATIONAL_RELEASE_ID}-20260828T101112Z-1a2b3c4d", + ] ) @@ -797,17 +813,6 @@ def _explode(_release_dir): assert not list(assembler_inputs["candidate"].parent.glob(".*.tmp.npz")) -def test_assemble_refuses_cut_tag_outside_the_grammar(assembler_inputs) -> None: - with pytest.raises(SystemExit, match="YYYYMMDDTHHMMSSZ"): - _load_driver_module().main( - [ - *assembler_inputs["argv"], - "--cut-tag", - f"{UK_NATIONAL_RELEASE_ID}-hotfix", - ] - ) - - def test_assemble_refuses_reserialized_diagnostics(assembler_inputs) -> None: diagnostics = json.loads(assembler_inputs["diagnostics"].read_text()) assembler_inputs["diagnostics"].write_text( diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py new file mode 100644 index 0000000000..a428f027e8 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py @@ -0,0 +1,470 @@ +"""Publishing a UK release build through the emitter (hand-over step H2c). + +The emitter's release writer puts each build in its own folder and records +it in ``releases.json``; Microcosm hands the build over with +``publish_release`` and treats it as current only when the receipt says so. +These tests use the in-memory client in ``test_support.microcosm_build``; the +emitter's own tests cover the writer, its queue and the Hub. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from microcosm_emitter_interface.releases import ReleaseRecordError, ReleasesRecord + +from microcosm.build import release_publication +from microcosm.data import release as release_module +from microcosm.data.releases_record import parse_releases_record +from test_support.microcosm_build.emitter import FakeEmitterClient +from test_support.microcosm_data.build_folders import UK_NATIONAL_BUILD +from test_support.microcosm_data.release import ( + _as_uk_national_build_folder_release, + artifact_root, # noqa: F401 (a fixture) + release_dir, # noqa: F401 (a fixture) +) + +UK_REPO_ID = "policyengine/populace-uk-private" +UK_NATIONAL_RELEASE_ID = "microcosm-uk-2024-25-national" +UK_EARLIER_BUILD = "uk-frs-calibration-attempt-20260901T000000Z-0badcafe" + + +@pytest.fixture +def national(release_dir: Path, monkeypatch) -> Path: # noqa: F811 + """A UK national build; the release contract's own tests cover its checks.""" + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) + return _as_uk_national_build_folder_release(release_dir) + + +def _record(client: FakeEmitterClient) -> dict: + return json.loads(client.hub_files[(UK_REPO_ID, "releases.json")]) + + +def test_publishing_hands_every_file_over_with_its_role( + national: Path, + artifact_root: Path, # noqa: F811 +) -> None: + client = FakeEmitterClient() + + outcome = release_publication.publish_release_build( + national, artifact_root=artifact_root, client=client + ) + + (request,) = client.release_requests + assert (request.repository, request.release, request.build) == ( + UK_REPO_ID, + UK_NATIONAL_RELEASE_ID, + UK_NATIONAL_BUILD, + ) + assert (request.release_role, request.make_current) == ("national", False) + files = {item.name: item for item in request.files} + assert files["release_manifest.json"].role == "release_manifest" + assert files["build_manifest.json"].role == "build_manifest" + assert files["populace_us_2024.h5"].role == "dataset" + assert files["populace_us_2024.h5"].local_path == ( + artifact_root / "populace_us_2024.h5" + ) + assert files["calibration_diagnostics.json"].role == "calibration_diagnostics" + folder = f"releases/{UK_NATIONAL_RELEASE_ID}/{UK_NATIONAL_BUILD}" + assert client.hub_files[(UK_REPO_ID, f"{folder}/populace_us_2024.h5")] == ( + b"h5 payload" + ) + release = _record(client)["releases"][UK_NATIONAL_RELEASE_ID] + assert release["role"] == "national" + assert release["current"] is None + assert list(release["builds"]) == [UK_NATIONAL_BUILD] + assert outcome.published and not outcome.current and outcome.succeeded + assert client.closed is False, "a client the caller passed stays open" + + +def test_a_build_published_as_current_is_current( + national: Path, + artifact_root: Path, # noqa: F811 +) -> None: + client = FakeEmitterClient() + + outcome = release_publication.publish_release_build( + national, artifact_root=artifact_root, make_current=True, client=client + ) + + assert client.release_requests[0].make_current is True + assert _record(client)["releases"][UK_NATIONAL_RELEASE_ID]["current"] == ( + UK_NATIONAL_BUILD + ) + assert outcome.current and outcome.succeeded + + +@pytest.mark.parametrize( + ("receipt", "current"), + [ + ({"status": "published", "current": UK_NATIONAL_BUILD}, True), + # A promotion requested after this publication landed first. + ({"status": "published", "current": UK_EARLIER_BUILD}, False), + ({"status": "published", "current": None}, False), + ({"status": "pending", "current": UK_NATIONAL_BUILD}, False), + ({"status": "refused", "current": UK_NATIONAL_BUILD}, False), + ({"status": "unavailable", "current": UK_NATIONAL_BUILD}, False), + ], +) +def test_a_build_is_current_only_when_a_published_receipt_names_it( + national: Path, + artifact_root: Path, # noqa: F811 + receipt: dict, + current: bool, +) -> None: + client = FakeEmitterClient(release_receipts=[receipt]) + + outcome = release_publication.publish_release_build( + national, artifact_root=artifact_root, make_current=True, client=client + ) + + assert outcome.current is current + assert outcome.succeeded is current + + +def test_pointer_files_refuse_a_build_made_current( + national: Path, + artifact_root: Path, # noqa: F811 +) -> None: + """While latest*.json files exist, the writer changes no current build.""" + client = FakeEmitterClient() + client.hub_files[(UK_REPO_ID, "latest-national.json")] = b"{}" + + outcome = release_publication.publish_release_build( + national, artifact_root=artifact_root, make_current=True, client=client + ) + + assert outcome.receipt["status"] == "refused" + assert outcome.receipt["error_code"] == "POINTER_FILES_PRESENT" + assert "without --make-current" in outcome.explanation() + assert (UK_REPO_ID, "releases.json") not in client.hub_files + + +def test_promoting_makes_a_published_build_current( + national: Path, + artifact_root: Path, # noqa: F811 +) -> None: + client = FakeEmitterClient() + release_publication.publish_release_build( + national, artifact_root=artifact_root, client=client + ) + + outcome = release_publication.promote_release_build(national, client=client) + + assert client.calls.count("promote_build") == 1 + (_, promotion) = client.release_requests + assert (promotion.release, promotion.build) == ( + UK_NATIONAL_RELEASE_ID, + UK_NATIONAL_BUILD, + ) + assert _record(client)["releases"][UK_NATIONAL_RELEASE_ID]["current"] == ( + UK_NATIONAL_BUILD + ) + assert outcome.current and outcome.succeeded + + +def test_a_repeated_publication_is_published_not_refused( + national: Path, + artifact_root: Path, # noqa: F811 +) -> None: + """Running the same command again after a lost receipt is safe.""" + client = FakeEmitterClient() + for _ in range(2): + outcome = release_publication.publish_release_build( + national, artifact_root=artifact_root, client=client + ) + assert outcome.published + + +def test_an_emitter_without_its_hugging_face_module_publishes_nothing( + national: Path, + artifact_root: Path, # noqa: F811 +) -> None: + client = FakeEmitterClient(modules=()) + + outcome = release_publication.publish_release_build( + national, artifact_root=artifact_root, client=client + ) + + assert outcome.receipt["status"] == "unavailable" + assert outcome.problem is not None and not outcome.succeeded + assert client.release_requests == [] + + +def test_a_started_emitter_is_closed_after_the_publication( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, +) -> None: + client = FakeEmitterClient() + monkeypatch.setattr(release_publication, "_start_release_emitter", lambda: client) + + release_publication.publish_release_build(national, artifact_root=artifact_root) + + assert client.closed is True + + +def _run(argv: list[str], capsys) -> tuple[int, dict | None, str]: + code = release_publication.main(argv) + captured = capsys.readouterr() + output = json.loads(captured.out) if captured.out.strip() else None + return code, output, captured.err + + +def test_the_command_publishes_and_prints_the_receipt( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, +) -> None: + client = FakeEmitterClient() + monkeypatch.setattr(release_publication, "_start_release_emitter", lambda: client) + + code, output, _ = _run( + [ + str(national), + "--repo-id", + UK_REPO_ID, + "--artifact-root", + str(artifact_root), + "--make-current", + ], + capsys, + ) + + assert code == 0 + assert output["status"] == "published" + assert (output["release"], output["build"]) == ( + UK_NATIONAL_RELEASE_ID, + UK_NATIONAL_BUILD, + ) + assert output["current"] is True + assert client.closed is True + + +def test_the_command_fails_when_the_build_did_not_become_current( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, +) -> None: + client = FakeEmitterClient( + release_receipts=[ + {"status": "published", "current": UK_EARLIER_BUILD, "message": "later"} + ] + ) + monkeypatch.setattr(release_publication, "_start_release_emitter", lambda: client) + + code, output, error = _run( + [str(national), "--artifact-root", str(artifact_root), "--make-current"], + capsys, + ) + + assert code == 1 + assert output["current"] is False + assert output["current_build"] == UK_EARLIER_BUILD + assert "is not current" in error + + +def test_the_command_promotes_with_promote( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, +) -> None: + client = FakeEmitterClient() + monkeypatch.setattr(release_publication, "_start_release_emitter", lambda: client) + assert _run([str(national), "--artifact-root", str(artifact_root)], capsys)[0] == 0 + + code, output, _ = _run([str(national), "--promote"], capsys) + + assert code == 0 + assert output["current"] is True + assert client.calls.count("promote_build") == 1 + + +def test_preflight_checks_the_build_without_an_emitter( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, +) -> None: + monkeypatch.setattr( + release_publication, + "_start_release_emitter", + lambda: pytest.fail("preflight starts no emitter"), + ) + + code, output, _ = _run( + [str(national), "--artifact-root", str(artifact_root), "--preflight-only"], + capsys, + ) + + assert code == 0 + assert output == { + "valid": True, + "published": False, + "release": UK_NATIONAL_RELEASE_ID, + "build": UK_NATIONAL_BUILD, + "repository": UK_REPO_ID, + "release_role": "national", + } + + +@pytest.mark.parametrize( + "arguments", + [ + ["--repo-id", "policyengine/populace-uk-staging"], + ["--promote", "--make-current"], + ], +) +def test_the_command_refuses_conflicting_arguments( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, + arguments: list[str], +) -> None: + monkeypatch.setattr( + release_publication, + "_start_release_emitter", + lambda: pytest.fail("a refused command starts no emitter"), + ) + + with pytest.raises((SystemExit, ValueError)): + release_publication.main( + [str(national), "--artifact-root", str(artifact_root), *arguments] + ) + + +def test_the_command_refuses_a_release_that_still_publishes_with_tags( + release_dir: Path, # noqa: F811 + artifact_root: Path, # noqa: F811 + capsys, +) -> None: + with pytest.raises(SystemExit): + release_publication.main( + [str(release_dir), "--artifact-root", str(artifact_root)] + ) + assert "tools/publish_release.sh" in capsys.readouterr().err + + +def test_the_command_refuses_a_build_whose_staging_never_arrived( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, +) -> None: + path = national / "build_manifest.json" + manifest = json.loads(path.read_text()) + manifest["staging"] = {"enabled": True, "uploads_succeeded": 0} + path.write_text(json.dumps(manifest)) + client = FakeEmitterClient() + monkeypatch.setattr(release_publication, "_start_release_emitter", lambda: client) + + code, _, error = _run( + [str(national), "--artifact-root", str(artifact_root)], capsys + ) + assert code == 1 + assert "refusing to publish" in error + assert client.release_requests == [] + + code, _, _ = _run( + [ + str(national), + "--artifact-root", + str(artifact_root), + "--allow-missing-staging", + ], + capsys, + ) + assert code == 0 + + +_RECORD = { + "schema_version": 1, + "default": UK_NATIONAL_RELEASE_ID, + "releases": { + UK_NATIONAL_RELEASE_ID: { + "role": "national", + "current": UK_NATIONAL_BUILD, + "builds": { + UK_NATIONAL_BUILD: {"published_at": "2026-11-04", "withdrawn": False}, + UK_EARLIER_BUILD: {"published_at": "2026-11-01", "withdrawn": True}, + }, + } + }, +} + + +def _variant(**changes) -> dict: + record = json.loads(json.dumps(_RECORD)) + release = record["releases"][UK_NATIONAL_RELEASE_ID] + for key, value in changes.items(): + if key in {"schema_version", "default"}: + record[key] = value + elif key == "extra": + record["extra"] = value + else: + release[key] = value + return record + + +@pytest.mark.parametrize( + "document", + [ + _RECORD, + _variant(current=None), + _variant(default=None), + _variant(current=UK_EARLIER_BUILD), + _variant(current="not-listed"), + _variant(default="microcosm-uk-2024-25-dense"), + _variant(schema_version=2), + _variant(schema_version=True), + _variant(schema_version=1.0), + _variant(role="National"), + _variant(extra={}), + _variant(builds={"bad/name": {"published_at": "x", "withdrawn": False}}), + _variant(builds={UK_NATIONAL_BUILD: {"published_at": "", "withdrawn": False}}), + _variant(builds={UK_NATIONAL_BUILD: {"published_at": "x", "withdrawn": 0}}), + [], + ], +) +def test_the_loader_reads_releases_json_as_the_release_writer_does( + document: object, +) -> None: + """microcosm-data cannot depend on the interface package (it supports + Python 3.11), so it repeats the writer's rules; both accept or refuse + each record alike.""" + content = json.dumps(document).encode() + try: + ReleasesRecord.parse(content) + except ReleaseRecordError: + writer_accepts = False + else: + writer_accepts = True + try: + parse_releases_record(content) + except ValueError: + reader_accepts = False + else: + reader_accepts = True + assert reader_accepts is writer_accepts + + +def test_the_roles_microcosm_names_are_the_interfaces() -> None: + from microcosm_emitter_interface import bundles, publication + + from microcosm.data import contract + + assert contract.RELEASE_MANIFEST_FILE_ROLE == publication.RELEASE_MANIFEST_ROLE + assert contract.BUILD_MANIFEST_FILE_ROLE == bundles.BUILD_MANIFEST_ROLE + assert contract.CHECKSUMS_FILE_ROLE == bundles.CHECKSUMS_ROLE + assert contract.DATASET_FILE_ROLE == bundles.DATASET_ROLE + assert contract.CALIBRATION_DIAGNOSTICS_FILE_ROLE == ( + bundles.CALIBRATION_DIAGNOSTICS_ROLE + ) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_contract.py index f7b3e8601b..652a74135f 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_contract.py @@ -42,6 +42,10 @@ CalibrationDiagnosticsV8, catalog_calibration_diagnostics, ) +from test_support.microcosm_data.build_folders import ( + UK_NATIONAL_BUILD, + to_build_folder_layout, +) from test_support.paths import paths_for _TEST_PATHS = paths_for("microcosm-data") @@ -50,7 +54,6 @@ UK_RELEASE_ID = "populace-uk-2023-dd68c73-4aa4b14-20260619T023711Z" UK_EXACT_K_RELEASE_ID = "populace-uk-2023-frs-k535080" UK_NATIONAL_RELEASE_ID = "microcosm-uk-2024-25-national" -UK_NATIONAL_CUT_TAG = f"{UK_NATIONAL_RELEASE_ID}-20260828T101112Z-1a2b3c4d" UK_RECORD_COUNT = 535_080 UK_TERMINAL_GATE_REPORT_FILE = "terminal_gates.json" UK_TERMINAL_GATE_PRODUCER = ( @@ -1768,22 +1771,18 @@ def _copy_real_uk_june_release(tmp_path: Path) -> Path: def _write_uk_national_release_dir(tmp_path: Path) -> Path: - """Build the constant-id national fixture from the green exact-k shape.""" + """Build the national fixture from the green exact-k shape. + + The national release publishes each build into its own folder, so the + fixture's manifests name the release and the build in that layout. + """ directory = _write_uk_release_dir(tmp_path, UK_EXACT_K_RELEASE_ID, tier="frs") national = directory.with_name(UK_NATIONAL_RELEASE_ID) directory.replace(national) - build_path = national / "build_manifest.json" - build = json.loads(build_path.read_text()) - build["build_id"] = UK_NATIONAL_RELEASE_ID - build_path.write_text(json.dumps(build)) - release_path = national / "release_manifest.json" release = json.loads(release_path.read_text()) - release["build"]["build_id"] = UK_NATIONAL_RELEASE_ID - for artifact in release["artifacts"].values(): - artifact["revision"] = UK_NATIONAL_CUT_TAG # The certification signs the evidence copies' actual bytes: the seam # report already sits in the directory (terminal_gates.json from the @@ -1813,11 +1812,11 @@ def _write_uk_national_release_dir(tmp_path: Path) -> Path: "kind": "diagnostics", "path": "release_certification.json", "repo_id": "policyengine/populace-uk-private", - "revision": UK_NATIONAL_CUT_TAG, + "revision": UK_EXACT_K_RELEASE_ID, "sha256": _sha256(certification_path), } release_path.write_text(json.dumps(release)) - return national + return to_build_folder_layout(national, build=UK_NATIONAL_BUILD) def _rewrite_exact_k_fixture_to_two_records(directory: Path) -> None: @@ -2487,7 +2486,7 @@ def test_uk_national_release_requires_policyengine_uk_model_pin( directory = _write_uk_national_release_dir(tmp_path) release_path = directory / "release_manifest.json" release = json.loads(release_path.read_text()) - release["build"]["built_with_model_package"]["name"] = "policyengine-us" + release["built_with_model_package"]["name"] = "policyengine-us" release_path.write_text(json.dumps(release)) with pytest.raises( @@ -2498,50 +2497,219 @@ def test_uk_national_release_requires_policyengine_uk_model_pin( @pytest.mark.parametrize( - "revision", + ("release_id", "publishes"), + [ + (UK_NATIONAL_RELEASE_ID, True), + ("microcosm-uk-2024-25-dense", True), + ("microcosm-uk-2024-25-local-k55000", True), + # Which stable releases US builds publish under is not agreed with + # the US data builder yet, so every US release keeps tags and + # latest.json. + (RELEASE_ID, False), + ("populace-us-2024-buildo-acs-local-abc1234-20260723T000000Z", False), + (UK_RELEASE_ID, False), + (UK_EXACT_K_RELEASE_ID, False), + ("microcosm-uk-2024-25-local-k0", False), + ], +) +def test_publishes_to_build_folder_names_only_the_uk_releases( + release_id: str, publishes: bool +) -> None: + assert contract.publishes_to_build_folder(release_id) is publishes + + +def test_release_roles_record_national_and_local_area() -> None: + assert contract.RELEASE_ROLES == { + "national_default": "national", + "non_default_local_area": "local_area", + } + + +@pytest.mark.parametrize( + ("key", "kind", "role"), [ - "main", - UK_NATIONAL_RELEASE_ID + "-", - # Prefixed but outside the attempt-derived cut-tag grammar: the - # contract validates the same - shape the - # assembler mints, so a hand-edited suffix cannot claim a cut. - UK_NATIONAL_RELEASE_ID + "-hotfix", - UK_NATIONAL_RELEASE_ID + "-20260828t101112Z-1a2b3c4d", - UK_NATIONAL_RELEASE_ID + "-20260828T101112Z-1A2B3C4D", - # Present but non-string: must fail loudly rather than vanish from - # the publish layer's string-only revision collection. - 123, + ("microcosm_uk_2024_25", "microdata", "dataset"), + ("microcosm_uk_2024_25_calibration", "calibration", "calibration_weights"), + ("calibration_diagnostics", "diagnostics", "calibration_diagnostics"), + ("release_certification", "diagnostics", "release_certification"), ], ) -def test_uk_national_release_rejects_invalid_artifact_revisions( +def test_release_artifact_role_keeps_the_general_roles( + key: str, kind: str, role: str +) -> None: + assert contract.release_artifact_role(key, kind) == role + + +def _rewrite_json(path: Path, mutate) -> None: + document = json.loads(path.read_text()) + mutate(document) + path.write_text(json.dumps(document)) + + +def _uk_national_failures(directory: Path) -> str: + with pytest.raises(ReleaseContractError) as caught: + validate_release_dir(directory) + return "\n".join(caught.value.failures) + + +def test_uk_national_build_folder_manifests_name_the_release_and_the_build( tmp_path: Path, - revision: str, ) -> None: directory = _write_uk_national_release_dir(tmp_path) - release_path = directory / "release_manifest.json" - release = json.loads(release_path.read_text()) - for artifact in release["artifacts"].values(): - artifact["revision"] = revision - release_path.write_text(json.dumps(release)) + release = json.loads((directory / "release_manifest.json").read_text()) + build = json.loads((directory / "build_manifest.json").read_text()) - with pytest.raises(ReleaseContractError, match="revision"): - validate_release_dir(directory) + assert (release["release"], release["build"]) == ( + UK_NATIONAL_RELEASE_ID, + UK_NATIONAL_BUILD, + ) + assert (build["release"], build["build"]) == ( + UK_NATIONAL_RELEASE_ID, + UK_NATIONAL_BUILD, + ) + validate_release_dir(directory) -def test_uk_national_release_rejects_mixed_cut_revisions(tmp_path: Path) -> None: - # Two individually grammar-valid cut tags are still two cuts: the - # contract refuses the mixture, not just publish. +def test_uk_national_build_folder_refuses_the_tagged_manifest_shape( + tmp_path: Path, +) -> None: directory = _write_uk_national_release_dir(tmp_path) - release_path = directory / "release_manifest.json" - release = json.loads(release_path.read_text()) - first_key = next(iter(release["artifacts"])) - release["artifacts"][first_key]["revision"] = ( - UK_NATIONAL_RELEASE_ID + "-20260901T000000Z-deadbeef" + + def tagged(release: dict) -> None: + release["build"] = { + "build_id": UK_NATIONAL_RELEASE_ID, + "cut_tag": f"{UK_NATIONAL_RELEASE_ID}-20260920T120000Z-deadbeef", + } + + _rewrite_json(directory / "release_manifest.json", tagged) + + assert "'build' must be the build's name" in _uk_national_failures(directory) + + +@pytest.mark.parametrize("field", ["build_id", "attempt_id", "cut_tag"]) +def test_uk_national_build_folder_refuses_the_retired_build_fields( + tmp_path: Path, field: str +) -> None: + directory = _write_uk_national_release_dir(tmp_path) + _rewrite_json( + directory / "build_manifest.json", + lambda build: build.update({field: UK_NATIONAL_RELEASE_ID}), ) - release_path.write_text(json.dumps(release)) - with pytest.raises(ReleaseContractError, match="more than one revision"): - validate_release_dir(directory) + assert f"build_manifest.json carries {field!r}" in _uk_national_failures(directory) + + +@pytest.mark.parametrize("manifest", ["build_manifest.json", "release_manifest.json"]) +def test_uk_national_build_folder_release_must_be_the_directory( + tmp_path: Path, manifest: str +) -> None: + directory = _write_uk_national_release_dir(tmp_path) + _rewrite_json( + directory / manifest, + lambda document: document.update(release="microcosm-uk-2024-25-dense"), + ) + + assert f"{manifest} 'release' is 'microcosm-uk-2024-25-dense'" in ( + _uk_national_failures(directory) + ) + + +@pytest.mark.parametrize("build", ["", "uk/attempt", "-attempt", 7, None]) +def test_uk_national_build_folder_build_must_be_a_safe_name( + tmp_path: Path, build: object +) -> None: + directory = _write_uk_national_release_dir(tmp_path) + for manifest in ("build_manifest.json", "release_manifest.json"): + _rewrite_json( + directory / manifest, lambda document: document.update(build=build) + ) + + assert "'build' must be the build's name" in _uk_national_failures(directory) + + +def test_uk_national_build_folder_manifests_must_name_the_same_build( + tmp_path: Path, +) -> None: + directory = _write_uk_national_release_dir(tmp_path) + _rewrite_json( + directory / "build_manifest.json", + lambda build: build.update( + build="uk-frs-calibration-attempt-20260101T000000Z-00000000" + ), + ) + + assert "build_manifest.json and release_manifest.json name different builds" in ( + _uk_national_failures(directory) + ) + + +@pytest.mark.parametrize( + "field", ["built_at", "built_with_core_package", "built_with_model_package"] +) +def test_uk_national_build_folder_records_build_details_at_the_top_level( + tmp_path: Path, field: str +) -> None: + directory = _write_uk_national_release_dir(tmp_path) + _rewrite_json( + directory / "release_manifest.json", lambda release: release.pop(field) + ) + + assert field in _uk_national_failures(directory) + + +def test_uk_national_build_folder_refuses_an_artifact_revision( + tmp_path: Path, +) -> None: + directory = _write_uk_national_release_dir(tmp_path) + + def pin(release: dict) -> None: + release["artifacts"]["calibration_diagnostics"]["revision"] = "main" + + _rewrite_json(directory / "release_manifest.json", pin) + + assert "artifact 'calibration_diagnostics' pins revision 'main'" in ( + _uk_national_failures(directory) + ) + + +@pytest.mark.parametrize( + ("role", "message"), + [ + (None, "artifact 'calibration_diagnostics' is missing 'role'"), + ("diagnostics", "artifact 'calibration_diagnostics' role is 'diagnostics'"), + ], +) +def test_uk_national_build_folder_names_each_artifact_role( + tmp_path: Path, role: str | None, message: str +) -> None: + directory = _write_uk_national_release_dir(tmp_path) + + def set_role(release: dict) -> None: + artifact = release["artifacts"]["calibration_diagnostics"] + if role is None: + artifact.pop("role") + else: + artifact["role"] = role + + _rewrite_json(directory / "release_manifest.json", set_role) + + assert message in _uk_national_failures(directory) + + +@pytest.mark.parametrize( + "path", ["releases/microcosm-uk-2024-25-national/x.json", "../x.json", "a\\b.json"] +) +def test_uk_national_build_folder_artifact_paths_are_bare_file_names( + tmp_path: Path, path: str +) -> None: + directory = _write_uk_national_release_dir(tmp_path) + + def move(release: dict) -> None: + release["artifacts"]["release_certification"]["path"] = path + + _rewrite_json(directory / "release_manifest.json", move) + + assert "artifact 'release_certification' path" in _uk_national_failures(directory) def test_uk_national_release_binds_signed_evidence_bytes(tmp_path: Path) -> None: diff --git a/packages/microcosm-data/tests/engine_free/shared/test_loader.py b/packages/microcosm-data/tests/engine_free/shared/test_loader.py index decabfd3d3..a002689b49 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_loader.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_loader.py @@ -25,8 +25,11 @@ from microcosm.data.release import ( LATEST_POINTER_PATH, latest_pointer_payload, - line_pointer_path, - line_pointer_payload, +) +from test_support.microcosm_data.build_folders import ( + UK_LOCAL_BUILD, + UK_NATIONAL_BUILD, + build_folder_release_manifest, ) #: Release id served by the hub fixture. Any well-formed id works: nothing in @@ -38,11 +41,10 @@ UK_REPO_ID = "policyengine/populace-uk-private" UK_2023_RELEASE_ID = "populace-uk-2023-dd68c73-4aa4b14-20260619T023711Z" UK_NATIONAL_RELEASE_ID = "microcosm-uk-2024-25-national" -UK_NATIONAL_CUT_TAG = f"{UK_NATIONAL_RELEASE_ID}-20260920T120000Z-deadbeef" -UK_LOCAL_LINE = "local-k15" UK_LOCAL_RELEASE_ID = "microcosm-uk-2024-25-local-k15" -UK_LOCAL_CUT_TAG = f"{UK_LOCAL_RELEASE_ID}-20260920T120000Z-cafebabe" UK_TAGGED_ARTIFACT = b"certified UK line artifact" +#: An earlier national build, still listed in releases.json. +UK_EARLIER_BUILD = "uk-frs-calibration-attempt-20260901T000000Z-0badcafe" def test_resolve_defaults_to_the_latest_year() -> None: @@ -124,8 +126,8 @@ def _release_manifest( def _uk_release_manifest( *, - release_id: str = UK_NATIONAL_RELEASE_ID, - revision: str = UK_NATIONAL_CUT_TAG, + release_id: str = UK_2023_RELEASE_ID, + revision: str = UK_2023_RELEASE_ID, filename: str = "microcosm_uk_2024_25.h5", artifact_key: str = "microcosm_uk_2024_25", dataset_role: str | None = NATIONAL_DEFAULT_DATASET_ROLE, @@ -170,7 +172,7 @@ def _uk_release_manifest( return manifest -def _uk_local_spec(*, pointer_path: str | None = None) -> DatasetSpec: +def _uk_local_spec() -> DatasetSpec: return DatasetSpec( country="uk", year=2025, @@ -180,14 +182,28 @@ def _uk_local_spec(*, pointer_path: str | None = None) -> DatasetSpec: engine_module="policyengine_uk.data", engine_class="UKSingleYearDataset", engine_package="policyengine-uk", - pointer_path=pointer_path or line_pointer_path(UK_LOCAL_LINE), + release=UK_LOCAL_RELEASE_ID, + ) + + +def _uk_build_folder_manifest( + *, + release: str = UK_NATIONAL_RELEASE_ID, + build: str = UK_NATIONAL_BUILD, + **options, +) -> dict: + """A release manifest as a build in its own folder carries it.""" + return build_folder_release_manifest( + _uk_release_manifest(release_id=release, **options), + release=release, + build=build, ) def _uk_local_manifest() -> dict: - return _uk_release_manifest( - release_id=UK_LOCAL_RELEASE_ID, - revision=UK_LOCAL_CUT_TAG, + return _uk_build_folder_manifest( + release=UK_LOCAL_RELEASE_ID, + build=UK_LOCAL_BUILD, filename="microcosm_uk_2024_25_local_k15.h5", artifact_key="microcosm_uk_2024_25_local_k15", dataset_role=NON_DEFAULT_LOCAL_AREA_DATASET_ROLE, @@ -195,6 +211,73 @@ def _uk_local_manifest() -> dict: ) +def _releases_record( + release: str = UK_NATIONAL_RELEASE_ID, + *, + role: str = "national", + current: str | None = UK_NATIONAL_BUILD, + builds: dict[str, bool] | None = None, +) -> dict: + """A releases.json document: ``builds`` maps each build to ``withdrawn``.""" + if builds is None: + builds = {UK_EARLIER_BUILD: False, UK_NATIONAL_BUILD: False} + return { + "schema_version": 1, + "default": release, + "releases": { + release: { + "role": role, + "current": current, + "builds": { + build: { + "published_at": "2026-09-20T12:00:00+00:00", + "withdrawn": withdrawn, + } + for build, withdrawn in builds.items() + }, + } + }, + } + + +def _build_folder_hub( + tmp_path: Path, + *, + manifest: dict, + record: dict | bytes | None = None, + artifact_content: bytes = UK_TAGGED_ARTIFACT, +) -> FakeHubDownload: + """Serve releases.json and one build folder, all read at ``main``.""" + hub = FakeHubDownload(tmp_path) + hub.calls.clear() + hub.files.clear() + record = _releases_record() if record is None else record + hub._add( + tmp_path, + UK_REPO_ID, + "releases.json", + None, + record if isinstance(record, bytes) else json.dumps(record).encode(), + ) + folder = f"releases/{manifest['release']}/{manifest['build']}" + hub._add( + tmp_path, + UK_REPO_ID, + f"{folder}/release_manifest.json", + None, + json.dumps(manifest).encode(), + ) + artifact = next( + entry + for entry in manifest["artifacts"].values() + if entry.get("kind") == "microdata" + ) + hub._add( + tmp_path, UK_REPO_ID, f"{folder}/{artifact['path']}", None, artifact_content + ) + return hub + + class FakeHubDownload: """Serve mutable and release-tagged files while recording every request.""" @@ -296,29 +379,6 @@ def _hub_with_pointer( return hub -def _line_pointer_hub( - tmp_path: Path, - *, - line: str, - release_id: str, - revision: str, - manifest: dict, -) -> FakeHubDownload: - pointer = line_pointer_payload( - release_id, - line=line, - revision=revision, - updated_at="2026-09-20T12:00:00+00:00", - ) - return _hub_with_pointer( - tmp_path, - repo_id=UK_REPO_ID, - pointer_path=line_pointer_path(line), - pointer=pointer, - manifest=manifest, - ) - - def _patch_engine( monkeypatch: pytest.MonkeyPatch, *, @@ -345,44 +405,193 @@ def __init__(self, *, file_path: str) -> None: return constructed -def test_resolve_uk_default_is_the_promoted_national_line(): - """microcosm#823: once the national line's first certified cut was - promoted, the line became the default UK load; the June 2023 line stays - addressable at its year and its own pointer (Max's #823 ruling).""" +def test_resolve_uk_default_is_the_national_release(): + """The national release is the default UK load, read through + releases.json; the June 2023 release stays at its year and latest.json.""" assert latest_year("uk") == 2025 assert resolve("uk").key == ("uk", 2025, DEFAULT_VARIANT) - assert resolve("uk").pointer_path == "latest-national.json" + assert resolve("uk").release == UK_NATIONAL_RELEASE_ID + assert resolve("uk", 2023).release is None assert resolve("uk", 2023).pointer_path == "latest.json" with pytest.raises(ValueError, match="variant 'national'"): resolve("uk", 2025, variant="national") -def test_resolve_uk_national_variant_follows_the_line_pointer( +def test_uk_national_load_follows_the_current_build_in_releases_json( tmp_path: Path, ) -> None: spec = resolve("uk", 2025) - manifest = _uk_release_manifest() - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=manifest, - ) + hub = _build_folder_hub(tmp_path, manifest=_uk_build_folder_manifest()) certified = loader._resolve_certified_release(spec, hub_download=hub) - manifest_path = f"releases/{UK_NATIONAL_RELEASE_ID}/release_manifest.json" - assert spec.key == ("uk", 2025, DEFAULT_VARIANT) - assert spec.pointer_path == "latest-national.json" + folder = f"releases/{UK_NATIONAL_RELEASE_ID}/{UK_NATIONAL_BUILD}" assert certified.release_id == UK_NATIONAL_RELEASE_ID - assert certified.artifact_revision == UK_NATIONAL_CUT_TAG + assert certified.build == UK_NATIONAL_BUILD + assert certified.artifact_path == f"{folder}/microcosm_uk_2024_25.h5" + assert certified.artifact_revision is None + assert certified.model.built_version == "2.89.2" + assert certified.core.built_version == "3.27.1" assert hub.calls == [ - (UK_REPO_ID, "latest-national.json", None), - (UK_REPO_ID, manifest_path, UK_NATIONAL_CUT_TAG), + (UK_REPO_ID, "releases.json", None), + (UK_REPO_ID, f"{folder}/release_manifest.json", None), ] +def test_a_pinned_build_loads_that_build(tmp_path: Path) -> None: + hub = _build_folder_hub( + tmp_path, manifest=_uk_build_folder_manifest(build=UK_EARLIER_BUILD) + ) + + certified = loader._resolve_certified_release( + resolve("uk", 2025), hub_download=hub, build=UK_EARLIER_BUILD + ) + + assert certified.build == UK_EARLIER_BUILD + + +def test_a_pinned_withdrawn_build_loads_with_a_warning(tmp_path: Path) -> None: + record = _releases_record(builds={UK_EARLIER_BUILD: True, UK_NATIONAL_BUILD: False}) + hub = _build_folder_hub( + tmp_path, + manifest=_uk_build_folder_manifest(build=UK_EARLIER_BUILD), + record=record, + ) + + with pytest.warns(UserWarning, match="has been withdrawn"): + certified = loader._resolve_certified_release( + resolve("uk", 2025), hub_download=hub, build=UK_EARLIER_BUILD + ) + assert certified.build == UK_EARLIER_BUILD + + +@pytest.mark.parametrize( + ("record", "build", "message"), + [ + ( + _releases_record(builds={UK_NATIONAL_BUILD: False}), + UK_EARLIER_BUILD, + "is not listed in releases.json", + ), + (_releases_record(current=None), None, "has no current build"), + ( + _releases_record("microcosm-uk-2024-25-dense", role="local_area"), + None, + "does not list release 'microcosm-uk-2024-25-national'", + ), + (b"not json", None, "is not a valid release record"), + ({"schema_version": 2, "default": None, "releases": {}}, None, "valid"), + ( + _releases_record(current=UK_EARLIER_BUILD, builds={UK_EARLIER_BUILD: True}), + None, + "is not a valid release record", + ), + ], +) +def test_releases_json_must_list_the_build_to_load( + tmp_path: Path, record: dict | bytes, build: str | None, message: str +) -> None: + hub = _build_folder_hub( + tmp_path, manifest=_uk_build_folder_manifest(), record=record + ) + + with pytest.raises(ValueError, match=message): + loader._resolve_certified_release( + resolve("uk", 2025), hub_download=hub, build=build + ) + + +@pytest.mark.parametrize("field", ["release", "build"]) +def test_a_manifest_naming_another_build_is_refused(tmp_path: Path, field) -> None: + manifest = _uk_build_folder_manifest() + hub = _build_folder_hub(tmp_path, manifest=manifest) + manifest[field] = "uk-frs-calibration-attempt-20260101T000000Z-00000000" + hub._add( + tmp_path, + UK_REPO_ID, + f"releases/{UK_NATIONAL_RELEASE_ID}/{UK_NATIONAL_BUILD}/release_manifest.json", + None, + json.dumps(manifest).encode(), + ) + + with pytest.raises(ValueError, match="names release"): + loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) + + +def test_a_build_folder_artifact_with_a_revision_is_refused(tmp_path: Path) -> None: + manifest = _uk_build_folder_manifest() + manifest["artifacts"]["microcosm_uk_2024_25"]["revision"] = "main" + hub = _build_folder_hub(tmp_path, manifest=manifest) + + with pytest.raises(ValueError, match="pins a revision"): + loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) + + +def test_the_dataset_artifact_must_have_the_dataset_role(tmp_path: Path) -> None: + manifest = _uk_build_folder_manifest() + manifest["artifacts"]["microcosm_uk_2024_25"]["role"] = "calibration_weights" + hub = _build_folder_hub(tmp_path, manifest=manifest) + + with pytest.raises(ValueError, match="not 'dataset'"): + loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) + + +def test_releases_json_role_must_match_the_manifest(tmp_path: Path) -> None: + hub = _build_folder_hub( + tmp_path, + manifest=_uk_build_folder_manifest(), + record=_releases_record(role="local_area"), + ) + + with pytest.raises(ValueError, match="listed with role 'local_area'"): + loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) + + +def test_a_build_pin_needs_a_build_folder_release() -> None: + def unexpected_download(**_kwargs) -> str: + pytest.fail("a refused pin must fail before a Hub request") + + with pytest.raises(ValueError, match="pins a build only for releases"): + loader._resolve_certified_release( + resolve("us", 2024), hub_download=unexpected_download, build="x" + ) + + +def test_unverified_root_loading_is_refused_for_a_build_folder_release( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr( + loader, + "_dataset_class", + lambda _spec: pytest.fail("refused before the engine is imported"), + ) + with pytest.raises(ValueError, match="no root file"): + load("uk", 2025, unverified_root=True) + + +def test_download_verifies_the_build_folder_dataset( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + hub = _build_folder_hub(tmp_path, manifest=_uk_build_folder_manifest()) + monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) + + path = download("uk", 2025) + + folder = f"releases/{UK_NATIONAL_RELEASE_ID}/{UK_NATIONAL_BUILD}" + assert path.read_bytes() == UK_TAGGED_ARTIFACT + assert hub.calls[-1] == (UK_REPO_ID, f"{folder}/microcosm_uk_2024_25.h5", None) + + hub._add( + tmp_path, + UK_REPO_ID, + f"{folder}/microcosm_uk_2024_25.h5", + None, + b"other bytes", + ) + with pytest.raises(ValueError, match="sha256 verification failed"): + download("uk", 2025) + + def test_resolve_uk_2023_still_uses_latest_json(tmp_path: Path) -> None: spec = resolve("uk", 2023) manifest = _uk_release_manifest( @@ -416,7 +625,7 @@ def test_resolve_uk_2023_still_uses_latest_json(tmp_path: Path) -> None: ] -@pytest.mark.parametrize("pointer_path", ["current.json", "latest-local-k0.json"]) +@pytest.mark.parametrize("pointer_path", ["current.json", "latest-national.json"]) def test_resolve_refuses_an_unsupported_pointer_path(pointer_path: str) -> None: spec = replace(resolve("us", 2024), pointer_path=pointer_path) @@ -427,68 +636,48 @@ def unexpected_download(**_kwargs) -> str: loader._resolve_certified_release(spec, hub_download=unexpected_download) -def test_line_pointer_refuses_any_artifact_revision_mismatch(tmp_path: Path) -> None: - manifest = _uk_release_manifest() - manifest["artifacts"]["calibration_report"] = { - "kind": "diagnostics", - "path": "calibration_diagnostics.json", - "repo_id": UK_REPO_ID, - "revision": UK_NATIONAL_RELEASE_ID, - "sha256": "0" * 64, - } - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=manifest, - ) - - with pytest.raises( - ValueError, - match=r"artifacts not pinned to expected revision.*calibration_report", - ): - loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) - - -def test_local_area_line_selects_its_only_microdata_artifact(tmp_path: Path) -> None: +def test_local_area_release_selects_its_only_microdata_artifact( + tmp_path: Path, +) -> None: manifest = _uk_local_manifest() manifest["artifacts"]["calibration_report"] = { "kind": "diagnostics", "path": "calibration_diagnostics.json", "repo_id": UK_REPO_ID, - "revision": UK_LOCAL_CUT_TAG, "sha256": "0" * 64, + "role": "calibration_diagnostics", } - hub = _line_pointer_hub( + hub = _build_folder_hub( tmp_path, - line=UK_LOCAL_LINE, - release_id=UK_LOCAL_RELEASE_ID, - revision=UK_LOCAL_CUT_TAG, manifest=manifest, + record=_releases_record( + UK_LOCAL_RELEASE_ID, + role="local_area", + current=UK_LOCAL_BUILD, + builds={UK_LOCAL_BUILD: False}, + ), ) - certified = loader._resolve_certified_release( - _uk_local_spec(), - hub_download=hub, - ) + certified = loader._resolve_certified_release(_uk_local_spec(), hub_download=hub) - manifest_path = f"releases/{UK_LOCAL_RELEASE_ID}/release_manifest.json" + folder = f"releases/{UK_LOCAL_RELEASE_ID}/{UK_LOCAL_BUILD}" assert certified.release_id == UK_LOCAL_RELEASE_ID - assert certified.artifact_path == "microcosm_uk_2024_25_local_k15.h5" - assert certified.artifact_revision == UK_LOCAL_CUT_TAG + assert certified.artifact_path == f"{folder}/microcosm_uk_2024_25_local_k15.h5" assert hub.calls == [ - (UK_REPO_ID, "latest-local-k15.json", None), - (UK_REPO_ID, manifest_path, UK_LOCAL_CUT_TAG), + (UK_REPO_ID, "releases.json", None), + (UK_REPO_ID, f"{folder}/release_manifest.json", None), ] def test_latest_json_refuses_a_local_area_manifest(tmp_path: Path) -> None: - manifest = _uk_local_manifest() - local_artifact = manifest["artifacts"]["microcosm_uk_2024_25_local_k15"] - local_artifact["revision"] = UK_LOCAL_RELEASE_ID + manifest = _uk_release_manifest( + filename="microcosm_uk_2024_25_local_k15.h5", + artifact_key="microcosm_uk_2024_25_local_k15", + dataset_role=NON_DEFAULT_LOCAL_AREA_DATASET_ROLE, + default_datasets={}, + ) pointer = latest_pointer_payload( - UK_LOCAL_RELEASE_ID, + UK_2023_RELEASE_ID, updated_at="2026-09-20T12:00:00+00:00", ) hub = _hub_with_pointer( @@ -498,36 +687,44 @@ def test_latest_json_refuses_a_local_area_manifest(tmp_path: Path) -> None: pointer=pointer, manifest=manifest, ) - spec = replace(_uk_local_spec(), pointer_path=LATEST_POINTER_PATH) + spec = replace(_uk_local_spec(), release=None, pointer_path=LATEST_POINTER_PATH) with pytest.raises( ValueError, - match=r"non_default_local_area.*line pointer.*latest\.json", + match=r"non_default_local_area.*build folder.*latest\.json", ): loader._resolve_certified_release(spec, hub_download=hub) -def test_local_area_line_refuses_nonempty_default_datasets(tmp_path: Path) -> None: - manifest = _uk_local_manifest() - manifest["default_datasets"] = {"national": "microcosm_uk_2024_25_local_k15"} - hub = _line_pointer_hub( +def _local_area_hub(tmp_path: Path, manifest: dict) -> FakeHubDownload: + return _build_folder_hub( tmp_path, - line=UK_LOCAL_LINE, - release_id=UK_LOCAL_RELEASE_ID, - revision=UK_LOCAL_CUT_TAG, manifest=manifest, + record=_releases_record( + UK_LOCAL_RELEASE_ID, + role="local_area", + current=UK_LOCAL_BUILD, + builds={UK_LOCAL_BUILD: False}, + ), ) + +def test_local_area_release_refuses_nonempty_default_datasets(tmp_path: Path) -> None: + manifest = _uk_local_manifest() + manifest["default_datasets"] = {"national": "microcosm_uk_2024_25_local_k15"} + hub = _local_area_hub(tmp_path, manifest) + with pytest.raises(ValueError, match=r"default_datasets is not empty"): loader._resolve_certified_release(_uk_local_spec(), hub_download=hub) @pytest.mark.parametrize("microdata_count", [0, 2]) -def test_local_area_line_requires_exactly_one_microdata_artifact( +def test_local_area_release_requires_exactly_one_microdata_artifact( tmp_path: Path, microdata_count: int, ) -> None: manifest = _uk_local_manifest() + hub = _local_area_hub(tmp_path, manifest) artifact = manifest["artifacts"]["microcosm_uk_2024_25_local_k15"] if microdata_count == 0: artifact["kind"] = "diagnostics" @@ -536,15 +733,15 @@ def test_local_area_line_requires_exactly_one_microdata_artifact( "kind": "microdata", "path": "second.h5", "repo_id": UK_REPO_ID, - "revision": UK_LOCAL_CUT_TAG, "sha256": "1" * 64, + "role": "dataset", } - hub = _line_pointer_hub( + hub._add( tmp_path, - line=UK_LOCAL_LINE, - release_id=UK_LOCAL_RELEASE_ID, - revision=UK_LOCAL_CUT_TAG, - manifest=manifest, + UK_REPO_ID, + f"releases/{UK_LOCAL_RELEASE_ID}/{UK_LOCAL_BUILD}/release_manifest.json", + None, + json.dumps(manifest).encode(), ) with pytest.raises( @@ -555,14 +752,8 @@ def test_local_area_line_requires_exactly_one_microdata_artifact( def test_loader_refuses_an_unknown_dataset_role(tmp_path: Path) -> None: - manifest = _uk_release_manifest(dataset_role="research_preview") - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=manifest, - ) + manifest = _uk_build_folder_manifest(dataset_role="research_preview") + hub = _build_folder_hub(tmp_path, manifest=manifest) with pytest.raises(ValueError, match="unknown dataset_role 'research_preview'"): loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) @@ -818,9 +1009,9 @@ def test_live_latest_pointer_resolves_to_a_coherent_certified_release( which are updated atomically with each certification PR. """ spec = resolve(country, year, variant=variant) - # The UK 2025 default follows its line's pointer since microcosm#823, so - # the pointer, not the variant, says how the release is named. - line = loader._line_from_pointer_path(spec.pointer_path) + # The UK 2025 default is a release whose builds publish into their own + # folders, so releases.json, not a pointer, says which build is current. + build_folder = spec.release is not None try: certified = loader._resolve_certified_release(spec) except Exception as exc: @@ -832,16 +1023,22 @@ def test_live_latest_pointer_resolves_to_a_coherent_certified_release( pytest.skip( f"repo requires credentials this environment lacks (private): {exc}" ) - if line is not None and _is_missing_pointer_error(exc, spec.pointer_path): - # A line pointer exists only once its first cut is promoted; - # until then the line is registered but not yet live. Anything - # else on a promoted line (a manifest 404, a bad pin) fails. - pytest.skip(f"line pointer {spec.pointer_path} not yet promoted: {exc}") + if build_folder and _is_missing_pointer_error(exc, "releases.json"): + # The one-time migration writes the repository's releases.json; + # until then the release has no record to read. Anything else + # once it exists (a manifest 404, a bad digest) fails. + pytest.skip(f"releases.json not yet written in {spec.hf_repo}: {exc}") raise assert certified.artifact_repo_id == spec.hf_repo - assert certified.artifact_path == spec.filename - if line is None: + if build_folder: + assert certified.release_id == spec.release + assert certified.artifact_path == ( + f"releases/{spec.release}/{certified.build}/{spec.filename}" + ) + assert certified.artifact_revision is None + else: + assert certified.artifact_path == spec.filename assert certified.release_id.startswith( # Live certified releases still carry the pre-rename id prefix; new # builds may adopt the microcosm- prefix at the next versioned @@ -849,30 +1046,19 @@ def test_live_latest_pointer_resolves_to_a_coherent_certified_release( (f"microcosm-{country}-{spec.year}-", f"populace-{country}-{spec.year}-") ) assert certified.artifact_revision == certified.release_id - else: - # A line pointer names the immutable cut tag of its constant id. - assert certified.release_id.startswith(f"microcosm-{country}-") - assert certified.artifact_revision.startswith(f"{certified.release_id}-") assert re.fullmatch(r"[0-9a-f]{64}", certified.artifact_sha256) assert certified.model.name == spec.engine_package -def test_line_pointer_refuses_a_manifest_with_another_lines_role(tmp_path: Path): - """A line pointer carries one role: the national pointer cannot select a - local-area manifest, nor a local-area pointer a national one.""" - spec = resolve("uk", 2025) - manifest = _uk_release_manifest() - manifest["dataset_role"] = "non_default_local_area" - manifest["default_datasets"] = {} - hub = _line_pointer_hub( - tmp_path, - line="national", - release_id=UK_NATIONAL_RELEASE_ID, - revision=UK_NATIONAL_CUT_TAG, - manifest=manifest, +def test_the_national_release_refuses_a_local_area_manifest(tmp_path: Path): + """releases.json gives each release one role: the national release + cannot load a local-area manifest on the strength of its name.""" + manifest = _uk_build_folder_manifest( + dataset_role="non_default_local_area", default_datasets={} ) - with pytest.raises(ValueError, match="publishes only 'national_default'"): - loader._resolve_certified_release(spec, hub_download=hub) + hub = _build_folder_hub(tmp_path, manifest=manifest) + with pytest.raises(ValueError, match="listed with role 'national'"): + loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) def test_latest_pointer_refuses_any_artifact_revision_mismatch(tmp_path: Path): diff --git a/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py index 425e703fd2..5ebae9d563 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py @@ -29,6 +29,11 @@ ) from microcosm.data.release import prepare_release, publish_release from microcosm.data.stored_inputs import register_sha256 +from test_support.microcosm_data.build_folders import ( + UK_LOCAL_BUILD, + build_folder_build_manifest, + build_folder_release_manifest, +) from test_support.paths import REPOSITORY_ROOT RELEASE_ID = "populace-us-2024-buildo-acs-local-abc1234-20260723T000000Z" @@ -110,7 +115,10 @@ def _write_local_bundle( A US id gets the package stage's stored-input and SPM measurement gates in ``gate_summary.json`` and ``build_manifest.json`` and the built-with engine they name; a UK id gets none of them, as the UK lanes write none. - ``None`` omits a piece, and a value replaces it. + ``None`` omits a piece, and a value replaces it. A UK local-area release + publishes each build into its own folder, so its manifests name the + release and the build (``UK_LOCAL_BUILD``) and record its UK built-with + packages at the top level. """ release_dir = root / "releases" / release_id release_dir.mkdir(parents=True) @@ -244,6 +252,17 @@ def _write_local_bundle( }, "reviewed_limitations": [{"id": "cd_population_marginal_vintage_2020"}], } + if release_id.startswith("microcosm-uk-2024-25-"): + manifest = _as_uk_build_folder(manifest, release_id=release_id) + payloads["build_manifest.json"] = json.dumps( + build_folder_build_manifest( + build_manifest, release=release_id, build=UK_LOCAL_BUILD + ), + indent=1, + ).encode() + (release_dir / "build_manifest.json").write_bytes( + payloads["build_manifest.json"] + ) manifest_text = json.dumps(manifest, indent=1) (release_dir / "release_manifest.json").write_text(manifest_text) ledger = {name: _sha256_bytes(payload) for name, payload in payloads.items()} @@ -255,6 +274,54 @@ def _write_local_bundle( return release_dir +def _as_uk_build_folder(manifest: dict, *, release_id: str) -> dict: + """The local-area manifest as a UK local-area build publishes it.""" + for artifact in manifest["artifacts"].values(): + artifact["repo_id"] = "policyengine/populace-uk-private" + manifest["build"] = { + "built_with_core_package": {"name": "policyengine-core", "version": "3.33.3"}, + "built_with_model_package": {"name": "policyengine-uk", "version": "2.165.1"}, + } + manifest["compatible_core_packages"] = [ + {"name": "policyengine-core", "specifier": "==3.33.3"} + ] + manifest["compatible_model_packages"] = [ + {"name": "policyengine-uk", "specifier": "==2.165.1"} + ] + return build_folder_release_manifest( + manifest, release=release_id, build=UK_LOCAL_BUILD + ) + + +def test_uk_local_area_bundle_publishes_in_the_build_folder_layout( + tmp_path: Path, +) -> None: + release_dir = _write_local_bundle(tmp_path, release_id=UK_LOCAL_RELEASE_ID) + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) + + assert (manifest["release"], manifest["build"]) == ( + UK_LOCAL_RELEASE_ID, + UK_LOCAL_BUILD, + ) + assert (build_manifest["release"], build_manifest["build"]) == ( + UK_LOCAL_RELEASE_ID, + UK_LOCAL_BUILD, + ) + validate_release_dir(release_dir) + + +def test_uk_local_area_bundle_refuses_the_tagged_layout(tmp_path: Path) -> None: + release_dir = _write_local_bundle(tmp_path, release_id=UK_LOCAL_RELEASE_ID) + build_manifest_path = release_dir / "build_manifest.json" + build_manifest = json.loads(build_manifest_path.read_text()) + build_manifest["build_id"] = UK_LOCAL_RELEASE_ID + build_manifest_path.write_text(json.dumps(build_manifest)) + + failures = _failures(release_dir) + assert any("build_manifest.json carries 'build_id'" in line for line in failures) + + def test_valid_local_area_bundle_passes(tmp_path: Path) -> None: release_dir = _write_local_bundle(tmp_path) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py b/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py index a61890267d..4540f4c1db 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py @@ -428,83 +428,3 @@ def test_publish_cli_defaults_to_the_certified_tier(tmp_path, monkeypatch): rc = main([str(tmp_path)]) assert rc == 0 assert calls[0][2]["evidence"] is False - - -def test_publish_cli_forwards_line_promotion_and_cut_tag(tmp_path, monkeypatch): - cut_tag = "microcosm-uk-2024-25-national-20260920T120000Z-deadbeef" - calls = _capture_publish(monkeypatch) - - rc = main( - [ - str(tmp_path), - "--promote-line", - "national", - "--tag-name", - cut_tag, - ] - ) - - assert rc == 0 - assert len(calls) == 1 - assert calls[0][2]["line"] == "national" - assert calls[0][2]["tag_name"] == cut_tag - assert calls[0][2]["update_latest"] is True - - -@pytest.mark.parametrize( - ("arguments", "message"), - [ - ( - [ - "--promote-line", - "national", - "--tag-name", - "cut-tag", - "--no-latest", - ], - "--promote-line cannot be combined with --no-latest", - ), - ( - [ - "--promote-line", - "national", - "--tag-name", - "cut-tag", - "--tag-only", - ], - "--promote-line cannot be combined with --tag-only", - ), - ( - [ - "--promote-line", - "national", - "--tag-name", - "cut-tag", - "--evidence", - ], - "--promote-line cannot be combined with --evidence", - ), - ( - ["--promote-line", "national"], - "--promote-line requires --tag-name", - ), - ], -) -def test_publish_cli_refuses_incompatible_line_promotion_modes( - tmp_path, capsys, monkeypatch, arguments, message -): - import microcosm.data.publish_cli as cli - - called = False - - def unexpected_publish(*args, **kwargs): - nonlocal called - called = True - - monkeypatch.setattr(cli, "publish_release", unexpected_publish) - - with pytest.raises(SystemExit, match="2"): - cli.main([str(tmp_path), *arguments]) - - assert message in capsys.readouterr().err - assert called is False diff --git a/packages/microcosm-data/tests/engine_free/shared/test_registry.py b/packages/microcosm-data/tests/engine_free/shared/test_registry.py index 066a1933ff..2831e6f3f7 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_registry.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_registry.py @@ -146,16 +146,28 @@ def test_uk_2025_dense_is_registered_off_the_default_variant() -> None: assert spec.filename == "microcosm_uk_2024_25_dense.h5" assert spec.engine_class == "UKSingleYearDataset" assert spec.engine_package == "policyengine-uk" + # Each new dense build becomes current when it is published. + assert spec.release == "microcosm-uk-2024-25-dense" assert ("uk", 2025, DEFAULT_VARIANT) in REGISTRY -def test_uk_2025_national_line_is_the_default_variant_after_promotion(): - """microcosm#823: the line's first certified cut was promoted on - 2026-10-26, so the line moved to the default variant (Max's #823 - ruling) and its own variant key retired; the June 2023 line stays - addressable at its year.""" +def test_uk_2025_national_release_is_the_default_variant(): + """The national release is the default UK 2025 load: its current build in + releases.json, not a pointer file; the June 2023 release stays + addressable at its year through latest.json.""" spec = REGISTRY[("uk", 2025, DEFAULT_VARIANT)] - assert spec.pointer_path == "latest-national.json" + assert spec.release == "microcosm-uk-2024-25-national" assert spec.filename == "microcosm_uk_2024_25.h5" assert ("uk", 2025, "national") not in REGISTRY - assert REGISTRY[("uk", 2023, DEFAULT_VARIANT)].filename == "populace_uk_2023.h5" + june = REGISTRY[("uk", 2023, DEFAULT_VARIANT)] + assert june.filename == "populace_uk_2023.h5" + assert (june.release, june.pointer_path) == (None, LATEST_POINTER_PATH) + + +def test_only_the_uk_registry_entries_name_a_release(): + """Every US entry keeps latest.json until the US stable releases are + agreed with the US data builder.""" + assert {spec.key: spec.release for spec in REGISTRY.values() if spec.release} == { + ("uk", 2025, DEFAULT_VARIANT): "microcosm-uk-2024-25-national", + ("uk", 2025, "dense"): "microcosm-uk-2024-25-dense", + } diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release.py b/packages/microcosm-data/tests/engine_free/shared/test_release.py index efc73d6a39..be1f036d8b 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release.py @@ -158,129 +158,170 @@ def test_line_pointer_payload_refuses_a_line_id_mismatch() -> None: ) +def _write_uk_build_folder_release( + release_id: str, release_dir: Path, tmp_path: Path +) -> Path: + """One build-folder release of each kind: national, dense or local-area.""" + if release_id == UK_NATIONAL_RELEASE_ID: + return _as_uk_national_build_folder_release(release_dir) + from .test_local_area_contract import _write_local_bundle + + if release_id == UK_LOCAL_RELEASE_ID: + return _write_local_bundle(tmp_path / "local", release_id=release_id) + from test_support.microcosm_data.build_folders import UK_DENSE_BUILD + + dense = _write_local_bundle(tmp_path / "dense", release_id=UK_LOCAL_RELEASE_ID) + dense = dense.rename(dense.with_name(release_id)) + for name in ("build_manifest.json", "release_manifest.json"): + manifest = json.loads((dense / name).read_text()) + manifest.update(release=release_id, build=UK_DENSE_BUILD) + (dense / name).write_text(json.dumps(manifest)) + return dense + + @pytest.mark.parametrize( - ("options", "message"), - [ - ({"update_latest": False}, "requires update_latest=True"), - ({"tag_only": True}, "cannot use tag_only=True"), - ({"evidence": True}, "cannot publish at the evidence tier"), - ], + "release_id", + [UK_NATIONAL_RELEASE_ID, "microcosm-uk-2024-25-dense", UK_LOCAL_RELEASE_ID], ) -def test_prepare_release_refuses_incompatible_line_modes( - release_dir: Path, monkeypatch, options: dict, message: str +def test_the_tagged_publisher_refuses_every_build_folder_release( + release_dir: Path, artifact_root: Path, tmp_path: Path, release_id: str ) -> None: - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - monkeypatch.setattr( - release_module, - "validate_evidence_release_dir", - lambda _path, **_kwargs: None, - ) + """A UK build publishes into its own folder through the emitter; this + publisher, which commits, tags and writes pointer files, refuses it + before any check or Hub call, on every path.""" + uk_dir = _write_uk_build_folder_release(release_id, release_dir, tmp_path) + uk_hub = FakeHub("policyengine/populace-uk-private") + uk_hub._download_dir = tmp_path / "uk-hub-cache" + message = "microcosm-publish-release-build" with pytest.raises(ValueError, match=message): - release_module.prepare_release(release_dir, line="national", **options) + release_module.prepare_release(uk_dir, artifact_root=artifact_root) + with pytest.raises(ValueError, match=message): + publish_release( + uk_dir, + "policyengine/populace-uk-private", + api=uk_hub, + artifact_root=artifact_root, + update_latest=False, + ) + with pytest.raises(ValueError, match=message): + publish_cli.main([str(uk_dir), "--preflight-only", "--no-latest"]) + assert uk_hub.events == [] + assert uk_hub.uploads == [] -def test_prepare_release_refuses_a_line_id_mismatch( - release_dir: Path, monkeypatch -) -> None: - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - with pytest.raises(ValueError, match="belongs to line None"): - release_module.prepare_release(release_dir, line="national") +def test_the_tagged_publisher_offers_no_line_promotion() -> None: + """Only UK releases had promotion lines, and they no longer publish here.""" + import inspect + + assert "line" not in inspect.signature(publish_release).parameters + assert "line" not in inspect.signature(release_module.prepare_release).parameters + with pytest.raises(SystemExit): + publish_cli.main(["releases/x", "--promote-line", "national"]) -def test_national_cut_promotes_only_its_line_pointer( - release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch +def test_prepare_build_folder_release_lists_each_file_with_its_role( + release_dir: Path, artifact_root: Path, monkeypatch ) -> None: - national = _as_uk_national_line_release(release_dir) + national = _as_uk_national_build_folder_release(release_dir) monkeypatch.setattr( release_module, "validate_release_dir", lambda _path, **_kwargs: [] ) - alerts: list = [] - monkeypatch.setattr( - release_module, - "notify_release", - lambda repo_id, release_id, updated_at, **kwargs: alerts.append( - (repo_id, release_id, updated_at, kwargs) - ), - ) - uk_hub = FakeHub("policyengine/populace-uk-private") - uk_hub._download_dir = tmp_path / "uk-hub-cache" - june_pointer = latest_pointer_payload( - JUNE_UK_RELEASE_ID, updated_at="2026-06-19T02:38:00+00:00" - ) - june_pointer_bytes = json.dumps(june_pointer, indent=1).encode() - uk_hub.seed_main_file(LATEST_POINTER_PATH, june_pointer_bytes) - published = publish_release( - national, - "policyengine/populace-uk-private", - api=uk_hub, - artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, - line="national", - updated_at="2026-09-20T12:00:00+00:00", + prepared = release_module.prepare_build_folder_release( + national, artifact_root=artifact_root ) - pointer_path = line_pointer_path("national") - main_files = uk_hub._commits[uk_hub._refs["main"]] - assert main_files[LATEST_POINTER_PATH] == june_pointer_bytes - assert { - path - for path in main_files - if path.startswith("latest") and path.endswith(".json") - } == {LATEST_POINTER_PATH, pointer_path} - assert uk_hub.events[-1][1]["paths"][-1] == pointer_path - assert uk_hub.uploads[-1][0] == pointer_path - assert uk_hub.tags == [{"tag": UK_NATIONAL_CUT_TAG, "revision": "commit-1"}] - assert published["revision"] == UK_NATIONAL_CUT_TAG - assert published["line"] == "national" - assert ( - latest_line_release( - "policyengine/populace-uk-private", line="national", api=uk_hub - ).revision - == UK_NATIONAL_CUT_TAG - ) - assert alerts == [ - ( - "policyengine/populace-uk-private", - UK_NATIONAL_RELEASE_ID, - "2026-09-20T12:00:00+00:00", - { - "warn_if_unset": True, - "line": "national", - "revision": UK_NATIONAL_CUT_TAG, - }, - ) - ] + assert prepared.repository == "policyengine/populace-uk-private" + assert (prepared.release, prepared.build) == ( + UK_NATIONAL_RELEASE_ID, + UK_NATIONAL_BUILD, + ) + assert prepared.release_role == "national" + files = {item.name: item for item in prepared.files} + assert {name: item.role for name, item in files.items()} == { + "release_manifest.json": "release_manifest", + "build_manifest.json": "build_manifest", + "populace_us_2024.h5": "dataset", + "populace_us_2024_calibration.npz": "calibration_weights", + "calibration_diagnostics.json": "calibration_diagnostics", + "us_source_coverage.json": "us_source_coverage", + "release_certification.json": "release_certification", + **{name: key for key, name in GATE_EVIDENCE_FILES.items()}, + US_STORED_INPUTS_EVIDENCE_FILE: US_STORED_INPUTS_EVIDENCE_KEY, + } + assert files["populace_us_2024.h5"].path == artifact_root / "populace_us_2024.h5" + assert files["build_manifest.json"].path == national / "build_manifest.json" + for item in prepared.files: + assert item.sha256 == _sha256(item.path) + assert item.bytes == item.path.stat().st_size -def test_local_k_role_moves_only_its_own_line_pointer(tmp_path: Path) -> None: +def test_prepare_build_folder_release_publishes_the_checksum_ledger( + tmp_path: Path, +) -> None: from .test_local_area_contract import _write_local_bundle release_dir = _write_local_bundle(tmp_path, release_id=UK_LOCAL_RELEASE_ID) - uk_hub = FakeHub("policyengine/populace-uk-private") - uk_hub._download_dir = tmp_path / "uk-local-hub-cache" - published = publish_release( - release_dir, - "policyengine/populace-uk-private", - api=uk_hub, - artifact_root=tmp_path, - line="local-k55000", - notify=False, + prepared = release_module.prepare_build_folder_release( + release_dir, artifact_root=tmp_path ) - pointer_path = line_pointer_path("local-k55000") - assert published["revision"] == UK_LOCAL_RELEASE_ID - assert uk_hub.tags == [{"tag": UK_LOCAL_RELEASE_ID, "revision": "commit-1"}] - assert uk_hub.events[-1][1]["paths"][-1] == pointer_path - assert all(path != LATEST_POINTER_PATH for path, _ in uk_hub.uploads) - assert all(path != LATEST_EVIDENCE_POINTER_PATH for path, _ in uk_hub.uploads) + roles = {item.name: item.role for item in prepared.files} + assert roles["sha256sums.txt"] == "checksums" + assert roles["populace_us_2024_acs_local.h5"] == "dataset" + assert prepared.release_role == "local_area" + + +def test_prepare_build_folder_release_refuses_a_tagged_release( + release_dir: Path, artifact_root: Path +) -> None: + with pytest.raises(ValueError, match="does not publish into build folders"): + release_module.prepare_build_folder_release( + release_dir, artifact_root=artifact_root + ) + + +def test_prepare_build_folder_release_refuses_changed_or_missing_files( + release_dir: Path, artifact_root: Path, monkeypatch +) -> None: + national = _as_uk_national_build_folder_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) + (artifact_root / "populace_us_2024.h5").write_bytes(b"other bytes") + with pytest.raises(ValueError, match="populace_us_2024.h5 has sha256"): + release_module.prepare_build_folder_release( + national, artifact_root=artifact_root + ) + (artifact_root / "populace_us_2024.h5").unlink() + with pytest.raises(FileNotFoundError, match="populace_us_2024.h5"): + release_module.prepare_build_folder_release( + national, artifact_root=artifact_root + ) + + +def test_prepare_build_folder_release_publishes_to_one_repository( + release_dir: Path, artifact_root: Path, monkeypatch +) -> None: + national = _as_uk_national_build_folder_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) + with pytest.raises(ValueError, match="names policyengine/populace-uk-private"): + release_module.prepare_build_folder_release( + national, artifact_root=artifact_root, repository="policyengine/other" + ) + manifest_path = national / "release_manifest.json" + manifest = json.loads(manifest_path.read_text()) + manifest["artifacts"]["calibration_diagnostics"]["repo_id"] = "policyengine/other" + manifest_path.write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match="more than one repository"): + release_module.prepare_build_folder_release( + national, artifact_root=artifact_root + ) def test_line_promotion_alert_names_the_line_and_revision() -> None: @@ -1781,132 +1822,94 @@ def no_hub(*args, **kwargs): assert hub.uploads == [] -def test_inspect_then_promote_reuses_the_immutable_tag( - release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch +def test_publish_then_promote_reuses_the_immutable_tag( + hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch ) -> None: - """The documented two-step sequence: publish for inspection under the cut - tag, then promote the same cut. The second call recognises the existing - tag that describes this release, writes no second immutable revision - and only the main commit carrying the pointer (review of #966).""" - national = _as_uk_national_line_release(release_dir) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) + """Publishing without the pointer, then with it: the second call + recognises the existing tag that describes this release, writes no second + immutable revision and only the main commit carrying the pointer.""" monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - hub = _uk_hub(tmp_path) - june_pointer_bytes = hub._commits[hub._refs["main"]][LATEST_POINTER_PATH] publish_release( - national, - "policyengine/populace-uk-private", + release_dir, + "policyengine/populace-us", api=hub, artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, update_latest=False, ) - assert line_pointer_path("national") not in hub._commits[hub._refs["main"]] + assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] events_after_inspect = len(hub.events) promoted = publish_release( - national, - "policyengine/populace-uk-private", + release_dir, + "policyengine/populace-us", api=hub, artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, - line="national", updated_at="2026-09-23T12:00:00+00:00", ) kinds = [event for event, _ in hub.events[events_after_inspect:]] assert kinds == ["create_commit"], kinds - assert hub.tags == [{"tag": UK_NATIONAL_CUT_TAG, "revision": "commit-1"}] - main_files = hub._commits[hub._refs["main"]] - assert main_files[LATEST_POINTER_PATH] == june_pointer_bytes - assert json.loads(main_files[line_pointer_path("national")])["revision"] == ( - UK_NATIONAL_CUT_TAG - ) - assert promoted["revision"] == UK_NATIONAL_CUT_TAG - assert ( - latest_line_release( - "policyengine/populace-uk-private", line="national", api=hub - ).revision - == UK_NATIONAL_CUT_TAG + assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] + assert promoted["release_id"] == RELEASE_ID + assert latest_release("policyengine/populace-us", api=hub).release_id == ( + RELEASE_ID ) def test_retry_after_a_failed_pointer_commit_reuses_the_tag( - release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch + hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch ) -> None: """A failure between tag creation and the pointer commit leaves the tag; the retry stands on it instead of dying on create_tag.""" - national = _as_uk_national_line_release(release_dir) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - hub = _uk_hub(tmp_path) hub.fail_main_commit = True with pytest.raises(RuntimeError, match="injected main commit failure"): publish_release( - national, - "policyengine/populace-uk-private", + release_dir, + "policyengine/populace-us", api=hub, artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, - line="national", ) - assert hub.tags == [{"tag": UK_NATIONAL_CUT_TAG, "revision": "commit-1"}] - assert line_pointer_path("national") not in hub._commits[hub._refs["main"]] + assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] + assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] hub.fail_main_commit = False publish_release( - national, - "policyengine/populace-uk-private", + release_dir, + "policyengine/populace-us", api=hub, artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, - line="national", ) - assert hub.tags == [{"tag": UK_NATIONAL_CUT_TAG, "revision": "commit-1"}] - assert line_pointer_path("national") in hub._commits[hub._refs["main"]] + assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] + assert LATEST_POINTER_PATH in hub._commits[hub._refs["main"]] -def test_promotion_refuses_a_tag_that_describes_another_release( - release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch +def test_publication_refuses_a_tag_that_describes_another_release( + hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch ) -> None: - national = _as_uk_national_line_release(release_dir) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - hub = _uk_hub(tmp_path) # A tag already pointing at a revision with no manifest for this release. - hub._refs[UK_NATIONAL_CUT_TAG] = hub._refs["main"] + hub._refs[RELEASE_ID] = hub._refs["main"] with pytest.raises(ValueError, match="does not describe this release"): publish_release( - national, - "policyengine/populace-uk-private", + release_dir, + "policyengine/populace-us", api=hub, artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, - line="national", ) - # A tag whose manifest is another cut's. - hub._commits["other"] = { - f"releases/{UK_NATIONAL_RELEASE_ID}/release_manifest.json": b"{}" - } - hub._refs[UK_NATIONAL_CUT_TAG] = "other" + # A tag whose manifest is another release's. + hub._commits["other"] = {f"releases/{RELEASE_ID}/release_manifest.json": b"{}"} + hub._refs[RELEASE_ID] = "other" with pytest.raises(ValueError, match="describes another release"): publish_release( - national, - "policyengine/populace-uk-private", + release_dir, + "policyengine/populace-us", api=hub, artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, - line="national", ) - assert line_pointer_path("national") not in hub._commits[hub._refs["main"]] + assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] def test_line_pointer_path_refuses_the_evidence_line() -> None: @@ -1914,44 +1917,17 @@ def test_line_pointer_path_refuses_the_evidence_line() -> None: line_pointer_path("evidence") -def test_line_promotion_refuses_a_release_whose_role_is_not_the_lines( - release_dir: Path, artifact_root: Path, monkeypatch -) -> None: - """The national line carries national-default releases only; a - local-area manifest cannot ride the national pointer on its id.""" - national = _as_uk_national_line_release(release_dir) - manifest_path = national / "release_manifest.json" - manifest = json.loads(manifest_path.read_text()) - manifest["dataset_role"] = "non_default_local_area" - manifest_path.write_text(json.dumps(manifest)) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) - with pytest.raises(ValueError, match="publishes only 'national_default'"): - release_module.prepare_release( - national, - artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, - line="national", - ) - - def test_transient_errors_while_checking_an_existing_tag_propagate( - release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch + hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch ) -> None: """Only "absent" answers are swallowed: a transient failure looking up - the tag or its manifest propagates, so a good cut is never orphaned + the tag or its manifest propagates, so a good tag is never orphaned and the create path is never re-entered with the tag in place.""" - national = _as_uk_national_line_release(release_dir) - monkeypatch.setattr( - release_module, "validate_release_dir", lambda _path, **_kwargs: [] - ) monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) - hub = _uk_hub(tmp_path) original_repo_info = hub.repo_info def flaky_repo_info(*, repo_id, repo_type, revision=None): - if revision == UK_NATIONAL_CUT_TAG: + if revision == RELEASE_ID: raise RuntimeError("injected transient Hub failure") return original_repo_info( repo_id=repo_id, repo_type=repo_type, revision=revision @@ -1960,18 +1936,16 @@ def flaky_repo_info(*, repo_id, repo_type, revision=None): monkeypatch.setattr(hub, "repo_info", flaky_repo_info) with pytest.raises(RuntimeError, match="injected transient Hub failure"): publish_release( - national, - "policyengine/populace-uk-private", + release_dir, + "policyengine/populace-us", api=hub, artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, - line="national", ) assert hub.tags == [] assert not [event for event, _ in hub.events if event == "create_branch"] monkeypatch.setattr(hub, "repo_info", original_repo_info) - hub._refs[UK_NATIONAL_CUT_TAG] = hub._refs["main"] + hub._refs[RELEASE_ID] = hub._refs["main"] def flaky_download(*, repo_id, filename, repo_type, revision=None): raise RuntimeError("injected transient download failure") @@ -1979,11 +1953,9 @@ def flaky_download(*, repo_id, filename, repo_type, revision=None): monkeypatch.setattr(hub, "hf_hub_download", flaky_download) with pytest.raises(RuntimeError, match="injected transient download failure"): publish_release( - national, - "policyengine/populace-uk-private", + release_dir, + "policyengine/populace-us", api=hub, artifact_root=artifact_root, - tag_name=UK_NATIONAL_CUT_TAG, - line="national", ) - assert line_pointer_path("national") not in hub._commits[hub._refs["main"]] + assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] diff --git a/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py b/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py index 109b9eb48d..c0a9eeb971 100644 --- a/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py +++ b/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py @@ -19,7 +19,8 @@ ) DENSE_ID = "microcosm-uk-2024-25-dense" -CUT_TAG = f"{DENSE_ID}-20260903T105422Z-ca611e43" +#: The calibration attempt the signed report is bound to: the dense build. +DENSE_BUILD = "uk-local-candidate-f100-s42-20260903T105422Z-ca611e43" KEY = base64.b64encode(b"\x07" * 32).decode() KEY_BYTES = base64.b64decode(KEY) @@ -117,13 +118,13 @@ def write_dense_bundle( root: Path, *, release_id: str = DENSE_ID, - revision: str = CUT_TAG, + revision: str | None = None, namespace: str = "uk_dense", default_datasets: dict | None = None, report: dict | None = None, drop_coverage_key: str | None = None, drop_households: bool = False, - attempt_id: str | None = None, + build: str | None = None, with_incumbent: bool = False, holdout: str = "skipped", sized: bool = False, @@ -141,7 +142,14 @@ def write_dense_bundle( coverage and the manifest's limitations, the areas in ``area_support``; the candidate manifest records the target-fit and input-mass names under ``reviewed_exclusions_stood_on``, as the build does. + + A release in the build-folder layout (the dense release) names its + ``build``, the signed report's attempt unless ``build`` says otherwise, in + both manifests, and pins no artifact ``revision`` unless ``revision`` asks + for one. Any other release ID gets the tagged layout, pinned to + ``revision`` or the release ID. """ + build_folder = release_id.startswith("microcosm-uk-2024-25-") release_dir = root / "releases" / release_id release_dir.mkdir(parents=True) report = report or _signed_report() @@ -257,12 +265,15 @@ def write_dense_bundle( } if drop_coverage_key: del coverage[drop_coverage_key] - build_manifest = { - "build_id": release_id, - "build_sha": "abc1234", - "code": {"git_commit": "a" * 40, "git_dirty": False}, - "attempt_id": attempt_id if attempt_id is not None else report["release_id"], - } + build_name = build if build is not None else report["release_id"] + build_manifest = ( + {"release": release_id, "build": build_name} + if build_folder + else {"build_id": release_id, "attempt_id": build_name} + ) + build_manifest.update( + build_sha="abc1234", code={"git_commit": "a" * 40, "git_dirty": False} + ) score = { "candidate_fitted_surface_loss": 0.01, "incumbent_fitted_surface_loss": 0.2, @@ -387,15 +398,44 @@ def write_dense_bundle( h5_bytes = b"dense-h5-stand-in" (root / "microcosm_uk_2024_25_dense.h5").write_bytes(h5_bytes) - def artifact(kind, path, sha): - return { + pinned = revision if revision is not None or build_folder else release_id + + def artifact(kind, path, sha, role): + entry = { "kind": kind, "path": path, "repo_id": "policyengine/populace-uk-private", - "revision": revision, "sha256": sha, } + if build_folder: + entry["role"] = role + if pinned is not None: + entry["revision"] = pinned + return entry + identity = ( + { + "release": release_id, + "build": build_name, + "built_at": "2026-09-03T12:00:00+00:00", + "built_with_core_package": { + "name": "policyengine-core", + "version": "3.33.3", + }, + "built_with_model_package": { + "name": "policyengine-uk", + "version": "2.165.1", + }, + "compatible_core_packages": [ + {"name": "policyengine-core", "specifier": "==3.33.3"} + ], + "compatible_model_packages": [ + {"name": "policyengine-uk", "specifier": "==2.165.1"} + ], + } + if build_folder + else {"build": {"build_id": release_id}} + ) manifest = { "schema_version": 1, "data_package": {"name": "microcosm-data", "version": "0.1.0"}, @@ -403,13 +443,15 @@ def artifact(kind, path, sha): "is_default": False, "default_datasets": default_datasets if default_datasets is not None else {}, "namespace": namespace, - "build": {"build_id": release_id}, + **identity, "artifacts": { "microcosm_uk_2024_25_dense": artifact( - "microdata", "microcosm_uk_2024_25_dense.h5", _sha(h5_bytes) + "microdata", "microcosm_uk_2024_25_dense.h5", _sha(h5_bytes), "dataset" ), **{ - Path(name).stem: artifact("diagnostics", name, _sha(payload)) + Path(name).stem: artifact( + "diagnostics", name, _sha(payload), Path(name).stem + ) for name, payload in payloads.items() if name != "build_manifest.json" }, @@ -750,8 +792,14 @@ def test_dense_bundle_rejects_stale_ledger_identity_key(tmp_path: Path) -> None: assert "identity.targets.chronicle" in _failures(release_dir) -def test_dense_bundle_accepts_the_release_id_as_revision(tmp_path: Path) -> None: - validate_release_dir(write_dense_bundle(tmp_path, revision=DENSE_ID)) +def test_dense_bundle_names_its_release_and_build_in_both_manifests( + tmp_path: Path, +) -> None: + release_dir = write_dense_bundle(tmp_path) + for name in ("build_manifest.json", "release_manifest.json"): + manifest = json.loads((release_dir / name).read_text()) + assert (manifest["release"], manifest["build"]) == (DENSE_ID, DENSE_BUILD) + validate_release_dir(release_dir) def _failures(release_dir: Path) -> str: @@ -760,8 +808,10 @@ def _failures(release_dir: Path) -> str: return str(excinfo.value) -def test_unpinned_revision_is_rejected(tmp_path: Path) -> None: - assert "not pinned" in _failures(write_dense_bundle(tmp_path, revision="main")) +@pytest.mark.parametrize("revision", ["main", DENSE_ID]) +def test_a_pinned_revision_is_rejected(tmp_path: Path, revision: str) -> None: + text = _failures(write_dense_bundle(tmp_path, revision=revision)) + assert f"pins revision {revision!r}" in text def test_wrong_namespace_is_rejected(tmp_path: Path) -> None: @@ -830,30 +880,62 @@ def test_missing_key_env_names_the_hole(tmp_path: Path, monkeypatch) -> None: def test_other_local_area_ids_keep_the_generic_contract(tmp_path: Path) -> None: # A non-dense local-area id never reaches the dense validator. - release_dir = write_dense_bundle( - tmp_path, - release_id="populace-uk-2025-frs-k9", - revision="populace-uk-2025-frs-k9", - ) + release_dir = write_dense_bundle(tmp_path, release_id="populace-uk-2025-frs-k9") text = _failures(release_dir) assert "us_source_coverage.json" in text def test_report_from_another_attempt_is_rejected(tmp_path: Path) -> None: release_dir = write_dense_bundle( - tmp_path, attempt_id="uk-local-candidate-f100-s42-20260101T000000Z-00000000" + tmp_path, build="uk-local-candidate-f100-s42-20260101T000000Z-00000000" ) assert "does not belong to this run" in _failures(release_dir) -def test_build_manifest_without_attempt_id_is_rejected(tmp_path: Path) -> None: +def test_build_manifest_without_its_build_is_rejected(tmp_path: Path) -> None: + release_dir = write_dense_bundle(tmp_path) + build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) + del build_manifest["build"] + (release_dir / "build_manifest.json").write_text( + json.dumps(build_manifest, indent=1) + ) + text = _failures(release_dir) + assert "build_manifest.json 'build' must be the build's name" in text + + +@pytest.mark.parametrize("field", ["attempt_id", "cut_tag", "build_id"]) +def test_a_build_manifest_with_a_retired_build_field_is_rejected( + tmp_path: Path, field: str +) -> None: release_dir = write_dense_bundle(tmp_path) build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) - del build_manifest["attempt_id"] + build_manifest[field] = DENSE_BUILD (release_dir / "build_manifest.json").write_text( json.dumps(build_manifest, indent=1) ) - assert "must carry the calibration 'attempt_id'" in _failures(release_dir) + assert f"build_manifest.json carries {field!r}" in _failures(release_dir) + + +def test_a_release_manifest_naming_another_build_is_rejected(tmp_path: Path) -> None: + release_dir = write_dense_bundle(tmp_path) + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + manifest["build"] = "uk-local-candidate-f100-s42-20260101T000000Z-00000000" + (release_dir / "release_manifest.json").write_text(json.dumps(manifest, indent=1)) + text = _failures(release_dir) + assert "name different builds" in text + + +@pytest.mark.parametrize( + "field", ["built_at", "built_with_core_package", "built_with_model_package"] +) +def test_a_dense_release_records_its_build_details_at_the_top_level( + tmp_path: Path, field: str +) -> None: + release_dir = write_dense_bundle(tmp_path) + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + del manifest[field] + (release_dir / "release_manifest.json").write_text(json.dumps(manifest, indent=1)) + assert field in _failures(release_dir) @pytest.mark.parametrize("dirty", [True, None, "false", 0, "missing"]) diff --git a/test_support/microcosm_build/emitter.py b/test_support/microcosm_build/emitter.py index 0912e5f908..d00422f06b 100644 --- a/test_support/microcosm_build/emitter.py +++ b/test_support/microcosm_build/emitter.py @@ -26,7 +26,12 @@ ``deliver=False`` and ``answer_receipts=False`` stand for an emitter that took the hand-over and then stopped; ``bundle_receipts`` scripts the answers instead, and ``never_copy`` names files the emitter leaves on - disk. + disk; +- a release change (``publish_release``, ``promote_build``) lands at once in + ``hub_files`` as the emitter's release writer documents it: the build + folder and ``releases.json`` in one commit, after the interface's shared + checks, or a ``refused`` receipt naming the first broken rule. + ``release_receipts`` scripts the answers instead. The emitter's own tests cover the process, its queues and the Hub. """ @@ -57,6 +62,27 @@ publication_id_of, unavailable_receipt, ) +from microcosm_emitter_interface.publication import ( + PromoteBuild, + PublishRelease, + ReleaseChange, + ReleaseReceipt, + WithdrawBuild, + unavailable_release_receipt, +) +from microcosm_emitter_interface.releases import ( + RELEASE_MANIFEST_NAME, + RELEASES_RECORD_PATH, + ReleaseRecordError, + ReleasesRecord, + add_build, + build_folder, + check_change, + check_commit, + check_repository, + make_current, + withdraw_build, +) from microcosm_emitter_interface.staging import ( ReadBackResult, RunFilesReceipt, @@ -76,6 +102,8 @@ #: together at most 64 MiB, before it answers the hand-over. MAX_COPIED_FILE_BYTES = 32 * 1024 * 1024 MAX_COPIED_BYTES = 64 * 1024 * 1024 +#: When the fake release writer records each build as published. +PUBLISHED_AT = "2026-11-04T12:00:00+00:00" #: What ``check_write_access`` answers for a credential that can write. WRITABLE = { "status": "checked", @@ -165,6 +193,7 @@ def __init__( queue: FakeHandoverQueue | None = None, deliver: bool = True, answer_receipts: bool = True, + release_receipts: Sequence[Mapping[str, Any]] | None = None, ) -> None: self._modules = frozenset(modules) self.accept_run_files = accept_run_files @@ -200,6 +229,14 @@ def __init__( self.hub_files = hub_files if hub_files is not None else {} #: Override for ``read_back_run_files``, when a test needs one. self.read_back_answer: ReadBackResult | None = None + #: Scripted release receipts: the change's answer, then each receipt + #: asked for (the last one repeats). + self.release_receipts = ( + None if release_receipts is None else list(release_receipts) + ) + #: Each release change handed over, and its latest receipt by ID. + self.release_requests: list[ReleaseChange] = [] + self._release_answers: dict[str, list[dict[str, Any]]] = {} self._committed: dict[tuple[str, str], tuple[str, str]] = {} self._deliveries: dict[tuple[str, str], dict[str, Any]] = {} self.telemetry = TelemetryRecorder(self) @@ -591,6 +628,143 @@ def _last_commit(api: Any, repository: str, path: str) -> str | None: return entry.last_commit.oid return api.repo_info(repo_id=repository, repo_type="dataset").sha + # Release changes ---------------------------------------------------------- + + def publish_release( + self, request: PublishRelease, *, wait_seconds: float = 300.0 + ) -> ReleaseReceipt: + self.calls.append("publish_release") + return self._release_change(request) + + def promote_build( + self, request: PromoteBuild, *, wait_seconds: float = 60.0 + ) -> ReleaseReceipt: + self.calls.append("promote_build") + return self._release_change(request) + + def withdraw_build( + self, request: WithdrawBuild, *, wait_seconds: float = 60.0 + ) -> ReleaseReceipt: + self.calls.append("withdraw_build") + return self._release_change(request) + + def release_receipt(self, handover_id: str) -> ReleaseReceipt | None: + self.calls.append("release_receipt") + answers = self._release_answers.get(handover_id) + if "huggingface" not in self.modules or not answers: + return None + return dict(answers.pop(0) if len(answers) > 1 else answers[0]) # type: ignore[return-value] + + def _release_change(self, request: ReleaseChange) -> ReleaseReceipt: + self.release_requests.append(request) + if "huggingface" not in self.modules: + return unavailable_release_receipt(request) + handover_id = request.handover_id() + base = { + "handover_id": handover_id, + "status": "published", + "error_code": None, + "message": None, + "commit": None, + "repository": request.repository, + "release": request.release, + "build": request.build, + "attempts": 1, + "current": None, + } + if self.release_receipts is not None: + answers = [{**base, **dict(receipt)} for receipt in self.release_receipts] + else: + answers = [{**base, **self._apply_release_change(request)}] + self._release_answers[handover_id] = answers[1:] or answers + return answers[0] # type: ignore[return-value] + + def _apply_release_change(self, request: ReleaseChange) -> dict[str, Any]: + """One commit as the release writer makes it, or why it is refused.""" + repository = request.repository + files = self.paths(repository) + record_bytes = self.hub_files.get((repository, RELEASES_RECORD_PATH)) + try: + before = ( + None if record_bytes is None else ReleasesRecord.parse(record_bytes) + ) + except ReleaseRecordError as error: + return _refused_release(error.violations) + record = before or ReleasesRecord.empty() + folder = build_folder(request.release, request.build) + new_files: dict[str, bytes] = {} + if isinstance(request, PublishRelease): + new_files = { + f"{folder}/{item.name}": Path(item.local_path).read_bytes() + for item in request.files + } + if any(path.startswith(folder + "/") for path in files): + manifest = f"{folder}/{RELEASE_MANIFEST_NAME}" + entry = record.releases.get(request.release) + if ( + entry is not None + and request.build in entry.builds + and self.hub_files.get((repository, manifest)) + == new_files[manifest] + ): + return {"current": entry.current} + return { + "status": "refused", + "error_code": "BUILD_FOLDER_EXISTS", + "message": f"{folder}/ already exists.", + } + try: + if isinstance(request, PublishRelease): + after = add_build( + record, + release=request.release, + build=request.build, + release_role=request.release_role, + published_at=PUBLISHED_AT, + make_current=request.make_current, + ) + elif isinstance(request, PromoteBuild): + after = make_current( + record, release=request.release, build=request.build + ) + else: + after = withdraw_build( + record, release=request.release, build=request.build + ) + except ReleaseRecordError as error: + return _refused_release(error.violations) + added = [*new_files, RELEASES_RECORD_PATH] + violations = [ + *check_change(before, after), + *check_commit( + before_files=files, + added_paths=added, + deleted_paths=[], + before=before, + after=after, + ), + *check_repository( + after, + [*files, *added], + lambda path: new_files.get(path) or self.hub_files[(repository, path)], + ), + ] + if violations: + return _refused_release(violations) + for path, content in new_files.items(): + self.hub_files[(repository, path)] = content + self.hub_files[(repository, RELEASES_RECORD_PATH)] = after.serialize() + commit = hashlib.sha1(str(len(self.release_requests)).encode()).hexdigest() + return {"commit": commit, "current": after.releases[request.release].current} + def close(self) -> None: self.calls.append("close") self.closed = True + + +def _refused_release(violations: Sequence[Any]) -> dict[str, Any]: + return { + "status": "refused", + "error_code": violations[0].code, + "message": "; ".join(item.message for item in violations), + } diff --git a/test_support/microcosm_data/build_folders.py b/test_support/microcosm_data/build_folders.py new file mode 100644 index 0000000000..d6f1ee5b74 --- /dev/null +++ b/test_support/microcosm_data/build_folders.py @@ -0,0 +1,90 @@ +"""Release fixtures in the build-folder layout (hand-over step H2c). + +A release that publishes each build into its own folder, +``releases///``, names the release and the build as two +strings in both manifests. Its release manifest records ``built_at`` and the +built-with packages at the top level, and each artifact's ``role`` without a +``revision``. These helpers rewrite a fixture written in the older tagged +shape, so each test keeps its own fixture builder. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +#: A calibration attempt ID, the build every UK fixture names by default. +UK_NATIONAL_BUILD = "uk-frs-calibration-attempt-20260920T120000Z-deadbeef" +UK_DENSE_BUILD = "uk-local-candidate-f100-s42-20260920T120000Z-deadbeef" +UK_LOCAL_BUILD = "uk-local-candidate-k55000-20260920T120000Z-deadbeef" + +#: The fields that named the build before the build-folder layout. +_RETIRED_BUILD_FIELDS = ("build_id", "attempt_id", "cut_tag") + + +def artifact_role(key: str, kind: object) -> str: + """The file role a build-folder manifest records for one artifact.""" + if kind == "microdata": + return "dataset" + if kind == "calibration": + return "calibration_weights" + return key + + +def build_folder_build_manifest( + manifest: Mapping[str, Any], *, release: str, build: str +) -> dict[str, Any]: + """The build manifest with ``release`` and ``build`` as its identity.""" + rewritten = { + key: value + for key, value in manifest.items() + if key not in _RETIRED_BUILD_FIELDS + } + return {"release": release, "build": build, **rewritten} + + +def build_folder_release_manifest( + manifest: Mapping[str, Any], *, release: str, build: str +) -> dict[str, Any]: + """The release manifest in the build-folder layout. + + The old ``build`` object's ``built_at`` and built-with packages move to + the top level; ``built_at`` gets a fixed time when the fixture has none. + """ + rewritten = dict(manifest) + old_build = rewritten.pop("build", None) + details = dict(old_build) if isinstance(old_build, Mapping) else {} + for field in _RETIRED_BUILD_FIELDS: + details.pop(field, None) + details.setdefault("built_at", "2026-09-20T12:00:00+00:00") + artifacts = rewritten.get("artifacts") + if isinstance(artifacts, Mapping): + rewritten["artifacts"] = { + key: { + **{name: value for name, value in entry.items() if name != "revision"}, + "role": artifact_role(key, entry.get("kind")), + } + if isinstance(entry, Mapping) + else entry + for key, entry in artifacts.items() + } + return {"release": release, "build": build, **details, **rewritten} + + +def to_build_folder_layout(release_dir: Path, *, build: str) -> Path: + """Rewrite a release directory's two manifests in the build-folder layout. + + The directory's name is the release. A checksum ledger is not refreshed. + """ + release = release_dir.name + for name, rewrite in ( + ("build_manifest.json", build_folder_build_manifest), + ("release_manifest.json", build_folder_release_manifest), + ): + path = release_dir / name + if path.is_file(): + manifest = json.loads(path.read_text()) + path.write_text(json.dumps(rewrite(manifest, release=release, build=build))) + return release_dir diff --git a/test_support/microcosm_data/release.py b/test_support/microcosm_data/release.py index 0b4ab99775..4a32607278 100644 --- a/test_support/microcosm_data/release.py +++ b/test_support/microcosm_data/release.py @@ -42,6 +42,10 @@ publish_release, ) from microcosm.data.stored_inputs import register_sha256 +from test_support.microcosm_data.build_folders import ( + UK_NATIONAL_BUILD, + to_build_folder_layout, +) @pytest.fixture(autouse=True) @@ -749,33 +753,30 @@ def artifact_root(tmp_path: Path) -> Path: return directory -def _as_uk_national_line_release(release_dir: Path) -> Path: - """Retarget the publisher fixture to the constant UK national line id.""" +def _as_uk_national_build_folder_release(release_dir: Path) -> Path: + """Retarget the publisher fixture to the UK national release. + + The national release publishes each build into its own folder, so the + manifests name the release and ``UK_NATIONAL_BUILD`` in that layout, and + every artifact lives in the UK repository. + """ national = release_dir.with_name(UK_NATIONAL_RELEASE_ID) release_dir.rename(national) - build_path = national / "build_manifest.json" - build = json.loads(build_path.read_text()) - build["build_id"] = UK_NATIONAL_RELEASE_ID - build_path.write_text(json.dumps(build)) - certification_path = national / "release_certification.json" certification_path.write_text("{}") manifest_path = national / "release_manifest.json" manifest = json.loads(manifest_path.read_text()) - manifest["build"]["build_id"] = UK_NATIONAL_RELEASE_ID for artifact in manifest["artifacts"].values(): artifact["repo_id"] = "policyengine/populace-uk-private" - artifact["revision"] = UK_NATIONAL_CUT_TAG manifest["artifacts"]["release_certification"] = { "kind": "diagnostics", "path": certification_path.name, "repo_id": "policyengine/populace-uk-private", - "revision": UK_NATIONAL_CUT_TAG, "sha256": _sha256(certification_path), } manifest_path.write_text(json.dumps(manifest)) - return national + return to_build_folder_layout(national, build=UK_NATIONAL_BUILD) @pytest.fixture @@ -873,14 +874,4 @@ def _declare_root_artifact(release_dir: Path, *, key: str, path: str) -> None: manifest_path.write_text(json.dumps(manifest)) -def _uk_hub(tmp_path: Path) -> FakeHub: - hub = FakeHub("policyengine/populace-uk-private") - hub._download_dir = tmp_path / "uk-hub-cache" - june_pointer = latest_pointer_payload( - JUNE_UK_RELEASE_ID, updated_at="2026-06-19T02:38:00+00:00" - ) - hub.seed_main_file(LATEST_POINTER_PATH, json.dumps(june_pointer, indent=1).encode()) - return hub - - __all__ = [name for name in globals() if not name.startswith("__")] From 55f350067ea95cd92431d845c446ff65e7543be7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:40:01 +0400 Subject: [PATCH 02/26] Publish UK release builds into their own folders through the emitter Hand-over step H2c. The UK national, dense and local-area releases hand each build to the separately installed emitter with the interface's `publish_release` call (`microcosm-publish-release-build`, in `microcosm.build.release_publication`). The emitter's release writer puts it in `releases///` and records it in `releases.json`; Microcosm no longer commits, tags or writes pointer files for them, and treats a build as current only when the receipt is `published` and names it as `current`. Both manifests name `release` and `build` (the calibration attempt) as strings; the release manifest records `built_at` and the built-with packages at its top level and a `role` per artifact, with no `revision`. The contract checks that layout for UK releases, the assemblers write it and print the new commands, and `microcosm-data`'s loader reads each UK release's current build from `releases.json`. US releases keep tags and `latest.json`; the tagged publisher refuses UK releases and loses line promotion. Co-Authored-By: Claude Opus 5.5 --- README.md | 57 ++- ...4-h2c-release-builds-in-folders.changed.md | 1 + docs/agent-guide.md | 15 +- docs/uk-dense-release-assembly-runbook-762.md | 57 ++- ...k-national-release-assembly-runbook-806.md | 119 ++--- packages/microcosm-build/pyproject.toml | 2 + .../microcosm/build/release_publication.py | 439 ++++++++++++++++++ .../uk/test_uk_release_publication.py | 46 +- packages/microcosm-data/README.md | 14 +- .../src/microcosm/data/contract.py | 410 ++++++++++++---- .../src/microcosm/data/loader.py | 357 ++++++++++---- .../src/microcosm/data/publish_cli.py | 108 ++--- .../src/microcosm/data/registry.py | 38 +- .../src/microcosm/data/release.py | 287 +++++++++--- .../src/microcosm/data/releases_record.py | 160 +++++++ .../tests/engine_free/shared/test_contract.py | 20 +- .../shared/test_local_area_contract.py | 4 +- .../tests/engine_free/shared/test_release.py | 5 +- tools/assemble_uk_dense_release_dir.py | 108 ++--- tools/assemble_uk_release_dir.py | 117 ++--- tools/publish_release.sh | 13 +- tools/release.env.example | 10 +- 22 files changed, 1780 insertions(+), 607 deletions(-) create mode 100644 changelog.d/1504-h2c-release-builds-in-folders.changed.md create mode 100644 packages/microcosm-build/src/microcosm/build/release_publication.py create mode 100644 packages/microcosm-data/src/microcosm/data/releases_record.py diff --git a/README.md b/README.md index cc0ac6a665..45b20f5314 100644 --- a/README.md +++ b/README.md @@ -424,24 +424,52 @@ and `calibration_diagnostics.v8.schema.json` beside it, for consumers that check the file without importing them, such as the collector. Its description lists the model rules a JSON Schema cannot express; see the [package README](packages/microcosm-diagnostics/README.md). -Standard publication uploads the locally built `releases//` artifacts to -the Hugging Face dataset, tags the release, and updates `latest.json`. It runs -on the build machine (it needs the freshly built H5), so it isn't a CI step: +Publication runs on the build machine (it needs the freshly built H5), so it +isn't a CI step. Releases use one of two layouts. + +**UK releases publish each build into its own folder.** The national, dense +and local-area releases (`microcosm.data.contract.publishes_to_build_folder`) +hand each build to the separately installed emitter, whose release writer +puts it in `releases///` and records it in the repository's +`releases.json`, the only record of each release's builds and which one is +current, in one commit. The build is the calibration attempt id. Both +manifests name the release and the build as strings; the release manifest +records `built_at`, `built_with_model_package` and `built_with_core_package` +at its top level and each file's `role`, and pins no revision. Nothing is +tagged and no pointer file is written: + +```bash +uv run microcosm-publish-release-build releases/ \ + --repo-id policyengine/populace-uk-private --artifact-root \ + [--make-current] +uv run microcosm-publish-release-build releases/ --promote +``` + +The first command publishes a build, and makes it current with +`--make-current`; the second makes a published build current. A build counts +as current only when the emitter's receipt is `published` and names it as +`current`. While the older `latest*.json` pointer files exist, the emitter +refuses every change to a release's current build. These publications send +no Slack alert; announcing release changes from `releases.json` is the +dashboard's job. The UK assemblers print the exact commands, and the +[national](docs/uk-national-release-assembly-runbook-806.md) and +[dense](docs/uk-dense-release-assembly-runbook-762.md) runbooks describe them. +`microcosm.data.load` reads the current build of such a release from +`releases.json`, or the listed build `build=` names. + +**US releases keep tags and `latest.json`** until the stable releases US +builds publish under are agreed with the US data builder. Publication uploads +the locally built `releases//` artifacts to the Hugging Face dataset, +tags the release, and updates `latest.json`: ```bash tools/publish_release.sh releases/ --repo-id policyengine/populace-us ``` `tools/publish_release.sh` is a thin wrapper around `microcosm-publish-release` -(all arguments pass straight through). The moment `latest.json` goes live, the -publish CLI posts a release alert to Slack — `#populace-us` or `#populace-uk`, -chosen from the repo id. - -Promotable UK release lines use pointers named `latest-.json`. Publish a -cut for inspection with `--no-latest --tag-name `, then promote the -reviewed cut with `--promote-line --tag-name `. Promotion moves -only that line pointer; the UK repository-global `latest.json` remains frozen -on the June 2023 release. Promotion reuses the immutable cut tag the inspect publication created (it checks the tagged manifest is byte-identical) and writes only the pointer commit, so the two-step sequence and a retry after a failed pointer commit both work. A line's registry entry is registered off the default variant until its first promotion; the default flips in a follow-up after the pointer exists. +(all arguments pass straight through), which refuses a UK release. The moment +`latest.json` goes live, the publish CLI posts a release alert to +`#populace-us`. The publisher uploads only the contract files, the release manifest's artifacts and any `--extra-file`. The US fiscal-refresh tool therefore binds @@ -560,9 +588,8 @@ cp tools/release.env.example tools/release.env # then paste the webhook URLs ``` `tools/release.env` is gitignored; the wrapper loads it (or you can just export -`SLACK_WEBHOOK_POPULACE_US` / `SLACK_WEBHOOK_POPULACE_UK` in your shell) and -warns if neither is set. After that, every release publishes with an automatic -Slack alert. +`SLACK_WEBHOOK_POPULACE_US` in your shell) and warns if it is not set. After +that, every US release publishes with an automatic Slack alert. Canonical UK exact-k builds also require a stable, base64-encoded 32-byte release key. Source `tools/release.env` before the national build as well as diff --git a/changelog.d/1504-h2c-release-builds-in-folders.changed.md b/changelog.d/1504-h2c-release-builds-in-folders.changed.md new file mode 100644 index 0000000000..c39a679aaf --- /dev/null +++ b/changelog.d/1504-h2c-release-builds-in-folders.changed.md @@ -0,0 +1 @@ +UK release builds publish into their own folders through the emitter. The UK national, dense and local-area releases (`microcosm.data.contract.publishes_to_build_folder`) hand each build to the separately installed `microcosm-emitter` with the interface's `publish_release` call, and its release writer puts the build in `releases///` and records it in the repository's `releases.json` in one commit; Microcosm no longer commits, tags or writes `latest*.json` pointer files for them. The new `microcosm-publish-release-build` command (`microcosm.build.release_publication`, in `microcosm-build`) checks the build with the release contract, hands every file over with its role and SHA-256, publishes with or without `--make-current`, makes a published build current with `--promote`, and succeeds only when the emitter's receipt is `published` and, when current was asked for, names the build as `current`. The build is the calibration attempt ID: both manifests name `release` and `build` as strings, the release manifest records `built_at`, `built_with_model_package` and `built_with_core_package` at its top level and a `role` on each artifact (`dataset`, `calibration_weights`, `calibration_diagnostics`, otherwise the artifact's key), and no artifact pins a `revision`. The fields `build_id`, `attempt_id` and `cut_tag` are gone from UK manifests, and the assemblers' `--cut-tag` option with them. Each release's role in `releases.json` is `national` or `local_area`, from its `dataset_role`. The UK national assembler prints a publication command and a separate promotion command; the dense assembler's command makes each new dense build current. The release contract checks this layout for UK releases and refuses the tagged one. `microcosm.data.load` reads a UK release's current build from `releases.json` (or the listed build `build=` names, a withdrawn one with a warning), then its manifest and dataset from the build's folder; `unverified_root=True` is refused for such a release, and the loader no longer follows `latest-.json` pointers. `microcosm-publish-release` and `tools/publish_release.sh` keep publishing US releases with tags and `latest.json`, refuse UK releases, and lose `--promote-line`. UK publications send no Slack alert. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index abd943d171..0ef3e38e67 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -235,10 +235,17 @@ no secret. Green PR checks mean the code contracts hold — they do **not** certify data artifacts. Builds, calibrations, and releases run outside PR CI, need gated Hugging Face data and credentials, and cannot run from forks. Release publication is a -deliberate human step (`tools/publish_release.sh` → -`microcosm-publish-release`), gated by `tools/preflight_us_release_gates.py`; -reviewed line promotion is a separate deliberate call to the same CLI with -`--promote-line`. See README "Releasing & alerts". Before launching a US +deliberate human step. A US release publishes with tags and `latest.json` +(`tools/publish_release.sh` → `microcosm-publish-release`), checked by +`tools/preflight_us_release_gates.py`. A UK release publishes each build into +its own folder through the emitter (`microcosm-publish-release-build`, from +`microcosm.build.release_publication`), which records it in the repository's +`releases.json`; making a published build current is a separate deliberate +call to the same command with `--promote`. The emitter refuses that while the +older `latest*.json` pointer files exist. Tests hand release changes to the +in-memory client (`client.release_requests`), which applies them to +`hub_files` with the interface's shared `releases.json` checks. See README +"Releasing & alerts". Before launching a US release, dry-run it with `tools/dry_run_us_release_gates.py` (or the release tool's `--dry-run-gates-report`). It replays the release's own input stages and grades every waiver register on the staged frame before the solve; see README diff --git a/docs/uk-dense-release-assembly-runbook-762.md b/docs/uk-dense-release-assembly-runbook-762.md index 8eaf2185e6..12cb202f75 100644 --- a/docs/uk-dense-release-assembly-runbook-762.md +++ b/docs/uk-dense-release-assembly-runbook-762.md @@ -5,10 +5,13 @@ through the atomic output-area assignment and calibrated to the national and loc target surfaces in one solve (`microcosm-build-uk --release-role dense`, the graph driver `tools/build_uk_full.py`; `tools/build_uk_rowwise_candidate.py` is a stub over it). It ships -on the **inspect lane only**: a constant release id, an immutable per-cut tag, -`dataset_role: non_default_local_area`, an empty `default_datasets` map, and -`--no-latest` at publication, so it can never displace the default artifact. -It is registered as `("uk", 2025, "dense")` in the private repo +as its own release, never the default one: a constant release id, +`dataset_role: non_default_local_area` (the role `local_area` in +`releases.json`) and an empty `default_datasets` map. Each build is published +once into its own folder, `releases/microcosm-uk-2024-25-dense//`, +through the emitter, and becomes the dense release's current build when it is +published; `releases.json` keeps the national release as the repository's +default. It is registered as `("uk", 2025, "dense")` in the private repo `policyengine/populace-uk-private`. Publication is a separate human step. Since microcosm#1124 (ruling of 2026-10-13, amended for microcosm#1301) the line may ship the 150,000-household exact-k selection from that pool instead @@ -527,9 +530,11 @@ id, and the full gate report `outputs.full_gate_report` against its digest), requires the manifest's `staging_delivery` receipt (the run's version 2 staging telemetry evidence, copied into `build_manifest.json` as `staging` so publication can apply its undelivered-staging refusal, as on the national -lane), re-runs the candidate pre-flight, mints the cut tag -`microcosm-uk-2024-25-dense--` from the run's attempt -id, clones the H5 beside itself as `microcosm_uk_2024_25_dense.h5`, stages +lane), re-runs the candidate pre-flight, names the build after the run's +attempt id in both manifests (`release` and `build`; the release manifest +also records `built_at` and the built-with packages at its top level and each +file's `role`, and no artifact pins a revision), clones the H5 beside itself +as `microcosm_uk_2024_25_dense.h5`, stages `build_manifest.json`, `release_manifest.json`, `calibration_diagnostics.json`, `gate_summary.json`, `uk_source_coverage.json`, the signed `uk_local_gates.json`, the original `rowwise_candidate_manifest.json`, @@ -584,30 +589,36 @@ repeats its warnings. Separate support and binding adjudications keep their own policies. The gate thresholds and existing approvals have not been widened or renewed. -## 5. Publish for inspection (human step) +## 5. Publish (human step) Run the printed command. Its shape is: ```bash -uv run python -m microcosm.data.publish_cli releases/microcosm-uk-2024-25-dense \ +uv run microcosm-publish-release-build releases/microcosm-uk-2024-25-dense \ --repo-id policyengine/populace-uk-private --artifact-root \ - --no-latest --tag-only --tag-name microcosm-uk-2024-25-dense-- + --make-current ``` -`--no-latest` is mandatory and enforced: publication refuses to move -`latest.json` for a non-default role. `--tag-only` publishes the immutable tag -revision without a main-branch commit. The artifact is reachable by its tag and -by the registry key `("uk", 2025, "dense")` only. - -A contract warning reaches the publisher's JSON output as well as stderr: -`--preflight-only` adds it to its verdict under `contract_warnings`, and -publication lists it the same way beside the pointer it prints. Neither -refuses on one. The immutable tag's message records that the release was -published past them and how many there were, never what they say. No dense +It checks the build against the release contract again and hands every file +to the separately installed emitter with its role and SHA-256. The emitter +writes the build's folder and `releases.json` in one commit. The command +succeeds only when the receipt is `published` and names this build as +`current`; a change to the dense release's current build requested after +this one can land first and leave another build current. Running the same +command again is safe: an already published build with the same release +manifest is reported `published`. + +While the repository still holds the older `latest*.json` pointer files, the +emitter refuses every change to a release's current build +(`POINTER_FILES_PRESENT`). Until those files are deleted, publish without +`--make-current`, and make the build current later with `--promote`. + +A contract warning reaches the command's stderr, and `--preflight-only` adds +it to its verdict under `contract_warnings`. Neither refuses on one. No dense release raises any since the disclosure walk was dropped. ## Promotion is a separate change -Making the dense line (or a sparse successor via the L0 penalty, #762 I10) a -default dataset is a registry and contract change with its own review; nothing -in this runbook promotes anything. +Making the dense release (or a sparse successor via the L0 penalty, #762 I10) +the default dataset is a registry and contract change with its own review; +nothing in this runbook changes the repository's default release. diff --git a/docs/uk-national-release-assembly-runbook-806.md b/docs/uk-national-release-assembly-runbook-806.md index 38a19e3e6c..df1cc500f9 100644 --- a/docs/uk-national-release-assembly-runbook-806.md +++ b/docs/uk-national-release-assembly-runbook-806.md @@ -1,9 +1,12 @@ # UK national release assembly runbook (#806) -This runbook turns a green UK national calibration candidate into an -inspectable release without promoting it to `latest.json`. The release id is -constant across cuts (`microcosm-uk-2024-25-national`); each cut gets an -immutable tag derived from the calibration attempt id. +This runbook turns a green UK national calibration candidate into a +published build of the national release, `microcosm-uk-2024-25-national`, +and then, after review, makes it the release's current build. Each build is +published once into its own folder, +`releases/microcosm-uk-2024-25-national//`, through the emitter, and +the repository's `releases.json` records which build is current. The build is +the calibration attempt id; nothing is tagged. Do not run this sequence in PR CI. Calibration, certification, assembly, and publication consume licensed data and operator credentials. @@ -15,11 +18,14 @@ Before starting, export: - `MICROCOSM_UK_TERMINAL_GATE_SIGNING_KEY`, containing the stable release key as base64-encoded 32 bytes. Certification signs with it and assembly uses it to re-verify the copied certification. -- `HF_TOKEN`, authenticated for write access to - `policyengine/populace-uk-private`. -- `SLACK_WEBHOOK_POPULACE_UK`, for the eventual promoted-release alert. The - inspect publication below uses `--no-latest`, so it does not announce a new - latest release. +- `HF_TOKEN` (or `HUGGINGFACE_TOKEN`, or a token saved by `hf auth login`), + with write access to `policyengine/populace-uk-private`. The publication + command starts the separately installed `microcosm-emitter` (0.11.9 or + later) as its child process, and the emitter uses the token it inherits. + +Publication sends no Slack alert. Alerts for new and current builds will come +from the dashboard, which compares `releases.json` before and after each +change; until that is in place, announce a build by hand. Keep the spine H5, its sibling `.build.json` and `.spine_gates.json`, the Ledger consumer artifact and manifest digest, and the licensed input-mass @@ -65,8 +71,8 @@ no overrides. It writes `microcosm_uk_2024_25.h5`, surface takes its band edges from) and `rowwise_candidate_manifest.json` into ``. The build record's id has the form -`uk-frs-calibration-attempt--`; assembly derives the -per-cut tag from that suffix. +`uk-frs-calibration-attempt--`; it is the build's +name in both release manifests and in its folder on the Hub. ## 2. Score and certify the cut @@ -144,11 +150,13 @@ uv run --no-sync python tools/assemble_uk_release_dir.py \ ``` The output is -`releases/microcosm-uk-2024-25-national/`. The JSON summary records every -digest, the derived cut tag, and the exact publication command. Use -`--cut-tag microcosm-uk-2024-25-national--` only to -override the derived tag deliberately; the override must keep that grammar, -which the contract validates on every artifact revision. +`releases/microcosm-uk-2024-25-national/`. Both manifests name the release +and the build (`release` and `build`), the release manifest records +`built_at`, `built_with_model_package` and `built_with_core_package` at its +top level and each file's `role` (`dataset`, `calibration_weights`, +`calibration_diagnostics`, and each evidence file's key), and no artifact +pins a revision. The JSON summary records every digest, the release and the +build, and the exact publication and promotion commands. Assembly stages into a private directory, validates there, and atomically renames into empty destinations: re-assembling a cut requires removing the @@ -163,46 +171,34 @@ as an operator cross-check but refuses to replace one. Run the assembler's `publish_command` first. Its shape is: ```bash -uv run python -m microcosm.data.publish_cli \ +uv run microcosm-publish-release-build \ releases/microcosm-uk-2024-25-national \ --repo-id policyengine/populace-uk-private \ - --artifact-root \ - --no-latest \ - --tag-name microcosm-uk-2024-25-national-- + --artifact-root ``` +It checks the build against the release contract again, then hands every +file to the emitter with its role and SHA-256. The emitter writes the build's +folder and `releases.json` in one commit, listing the build without making +it current. The command waits for the emitter's answer and prints its +receipt: `status` is `published`, `pending` (the emitter is still trying, and +keeps the change queued for an hour) or `refused` with an `error_code`. +Running the same command again is safe: a build already published with the +same release manifest is reported `published`, and one published with a +different manifest is refused (`BUILD_FOLDER_EXISTS`), since a build is never +changed after publishing. `--preflight-only` runs the checks and starts no +emitter. + The assembler also prints this `promote_command`; keep it for §6 and run it -only after the cut passes the review in §5: +only after the build passes the review in §5: ```bash -uv run python -m microcosm.data.publish_cli \ +uv run microcosm-publish-release-build \ releases/microcosm-uk-2024-25-national \ --repo-id policyengine/populace-uk-private \ - --artifact-root \ - --promote-line national \ - --tag-name microcosm-uk-2024-25-national-- + --promote ``` -Do not omit `--tag-name`, and do not pass `--no-create-tag`: every artifact in -the manifest is pinned to that immutable per-cut tag. `--no-latest` is -mandatory for the inspect publication. The promotion command replaces it with -`--promote-line national`; the CLI requires that flag to accompany -`--tag-name` and refuses to combine it with `--no-latest`. A per-cut tag without -either flag cannot move the repository-global `latest.json`. - -The two commands share the cut tag by design: the promotion recognises the -immutable tag the inspect publication created, checks that the tagged -`release_manifest.json` is byte-identical to the local one, creates no second -immutable revision, and writes only the main commit carrying -`latest-national.json`. The same recognition makes a retry safe after a -failure between tag creation and the pointer commit: rerun the same command. -A tag that describes another release refuses; publish under a fresh cut tag. - -Only a failure before the tag exists (the staging commit itself) can leave -the constant branch `release-staging/microcosm-uk-2024-25-national` behind. -Delete that branch manually in the private Hugging Face repository before -retrying. Never delete an immutable cut tag. - ## 5. Inspect on the dashboard Open the calibration-diagnostics dashboard with: @@ -215,19 +211,24 @@ Adjudicate the release using the copied certification, scoped gate reports, calibration diagnostics, and score receipt. The release remains inspect-only until that review is complete. -## 6. Promote the reviewed cut +The dashboard shows a build published into its own folder only once it reads +`releases.json`; until then, review the assembled directory's files. + +## 6. Make the reviewed build current After completing the review in §5, run the assembler's `promote_command` shown -in §4. The promotion moves only `latest-national.json`, recording `national` as -the line and the reviewed cut tag as its `revision`. It never moves the -repository-global `latest.json`, which remains on the June 2023 release. - -The 2025 national entry was registered off the default variant until the -first promotion, so that a default load never chased a pointer that did not -exist yet. The first certified cut was promoted on 2026-10-26, and the entry -is now the default variant (microcosm#823): `microcosm.data.load("uk")` and -`microcosm.data.load("uk", 2025)` follow `latest-national.json`. An explicit -`microcosm.data.load("uk", 2023)` continues to follow `latest.json`. - -With `SLACK_WEBHOOK_POPULACE_UK` configured, successful promotion sends an -alert naming the `national` line and the promoted revision. +in §4. The emitter sets the national release's `current` in `releases.json` +to this build. The command succeeds only when the receipt is `published` and +names this build as `current`. + +While the repository still holds the older `latest*.json` pointer files, the +emitter refuses every change to a release's current build +(`POINTER_FILES_PRESENT`), so that the pointer files and `releases.json` +cannot disagree. Until those files are deleted, a build can be published but +not made current. + +The 2025 national release is the default UK load (microcosm#823): +`microcosm.data.load("uk")` and `microcosm.data.load("uk", 2025)` read its +current build from `releases.json`, and `load(..., build=)` loads a +listed build instead. An explicit `microcosm.data.load("uk", 2023)` +continues to follow `latest.json`. diff --git a/packages/microcosm-build/pyproject.toml b/packages/microcosm-build/pyproject.toml index c5c650bf33..b4a205dcf2 100644 --- a/packages/microcosm-build/pyproject.toml +++ b/packages/microcosm-build/pyproject.toml @@ -56,6 +56,8 @@ uk = ["policyengine-uk>=2.165.1", "microcosm-data>=0.1,<0.2", "h5py>=3", "tables [project.scripts] microcosm-build-uk = "microcosm.build.uk_runtime.full_build_cli:main" microcosm-export-us-l0-refit-h5 = "microcosm.build.us_runtime.l0_refit_export:main" +# Publishes a release build into its own folder through the emitter. +microcosm-publish-release-build = "microcosm.build.release_publication:main" [project.urls] Homepage = "https://microcosm.institute" diff --git a/packages/microcosm-build/src/microcosm/build/release_publication.py b/packages/microcosm-build/src/microcosm/build/release_publication.py new file mode 100644 index 0000000000..766c0fbd9e --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/release_publication.py @@ -0,0 +1,439 @@ +"""Publish a release build into its own folder through the emitter. + +A release whose builds publish into their own folders (every UK release: +``microcosm.data.contract.publishes_to_build_folder``) is handed to the +separately installed emitter with the interface's ``publish_release`` call. +Microcosm decides what the build contains and checks it with the release +contract; the emitter's release writer puts the files in +``releases///`` and records the build in the repository's +``releases.json`` in one commit, refusing a change that breaks the shared +rules in ``microcosm_emitter_interface.releases``. Nothing here commits, +tags or writes a pointer file. + +A build is current only when the emitter's receipt says so: ``status`` is +``published`` and ``current`` is the build. A publication with +``make_current`` can land without making its build current, when a change to +the release's current build requested after it landed first. + +The emitter finds its Hugging Face credential the way a build's emitter +does: it is this command's child process and inherits its environment +(``HF_TOKEN``, then ``HUGGINGFACE_TOKEN``, then the token saved by +``hf auth login``). Publication sends no Slack alert; announcing release +changes from ``releases.json`` is the dashboard's job. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Any, Protocol + +from microcosm_emitter_interface import PromoteBuild, PublishRelease, ReleaseFile +from microcosm_emitter_interface.publication import ( + ReleaseChange, + ReleaseReceipt, + unavailable_release_receipt, +) + +from microcosm.build.telemetry_emitter import emitter_problem, start_bundle_emitter +from microcosm.data.contract import publishes_to_build_folder +from microcosm.data.publish_cli import publication_refusal +from microcosm.data.release import ( + BuildFolderRelease, + build_folder_identity, + prepare_build_folder_release, +) + +if TYPE_CHECKING: + from microcosm_emitter_interface import EmitterStartupError, RequestFailure + +__all__ = [ + "PROMOTION_WAIT_SECONDS", + "PUBLICATION_WAIT_SECONDS", + "ReleaseEmitter", + "ReleasePublication", + "main", + "promote_release_build", + "publish_release_build", +] + +#: How long the command waits for a publication to land or be refused. The +#: emitter uploads a build's files in its one commit, and the largest UK +#: build recorded (about 2.4 GB) takes about 16 minutes at 20 Mbit/s; the +#: emitter refuses a change still pending an hour after it was handed over +#: (``REQUEST_EXPIRED``), so the wait covers that hour and one long upload. +PUBLICATION_WAIT_SECONDS = 2 * 3600.0 +#: How long the command waits for a promotion, which changes only +#: ``releases.json``. +PROMOTION_WAIT_SECONDS = 300.0 +#: What the emitter's refusal codes mean for the operator, where its own +#: message does not say what to do next. +_REFUSAL_ADVICE = { + "POINTER_FILES_PRESENT": ( + "The repository still has latest*.json pointer files, and the emitter " + "changes no release's current build while any exists, so that they " + "and releases.json cannot disagree. Publish the build without " + "--make-current, and make it current with --promote once the pointer " + "files are deleted." + ), + "BUILD_FOLDER_EXISTS": ( + "Another build with this name was published already, with a different " + "release manifest; builds are never changed after publishing." + ), + "NEWER_CHANGE_LANDED": ( + "A change to the release's current build requested after this one " + "landed first; run the command again if this build should still be " + "current." + ), + "REQUEST_EXPIRED": ( + "The change was still waiting an hour after it was handed over, so " + "the emitter dropped it; run the command again." + ), +} + + +class ReleaseEmitter(Protocol): + """The interface ``EmitterClient``'s release calls and state.""" + + startup_error: EmitterStartupError | None + last_failure: RequestFailure | None + + @property + def available(self) -> bool: ... + + @property + def modules(self) -> frozenset[str]: ... + + def publish_release( + self, request: PublishRelease, *, wait_seconds: float = 300.0 + ) -> ReleaseReceipt: ... + + def promote_build( + self, request: PromoteBuild, *, wait_seconds: float = 60.0 + ) -> ReleaseReceipt: ... + + def close(self) -> None: ... + + +#: Starts the short-lived emitter a publication uses (only its Hugging Face +#: module); tests replace it. +_start_release_emitter = start_bundle_emitter + + +@dataclass(frozen=True) +class ReleasePublication: + """What became of one release change: the emitter's receipt, read. + + ``wanted_current`` says whether the change asked for the build to become + current: a promotion, or a publication with ``make_current``. ``problem`` + says why no emitter could take the change, when none could. + """ + + repository: str + release: str + build: str + wanted_current: bool + receipt: ReleaseReceipt + problem: str | None = None + + @property + def published(self) -> bool: + """Whether the build is listed: the change landed, or had already.""" + return self.receipt["status"] == "published" + + @property + def current(self) -> bool: + """Whether the build is the release's current build after the change.""" + return self.published and self.receipt.get("current") == self.build + + @property + def succeeded(self) -> bool: + """Published, and current when that was asked for.""" + return self.published and (self.current or not self.wanted_current) + + def explanation(self) -> str: + """A sentence or two on the outcome, for the operator.""" + status, code = self.receipt["status"], self.receipt.get("error_code") + if self.problem is not None: + return f"No emitter took the change: {self.problem}." + if status == "unavailable": + return "The emitter did not answer; nothing was handed over." + if status == "pending": + return ( + f"The emitter is still trying ({code}); it keeps the change " + "queued for an hour after the hand-over. Run the same command " + "again later to see whether it landed." + ) + if status == "refused": + advice = _REFUSAL_ADVICE.get(str(code)) + reason = self.receipt.get("message") or code + return f"The emitter refused it ({code}): {reason}" + ( + f" {advice}" if advice else "" + ) + if self.wanted_current and not self.current: + current = self.receipt.get("current") + note = self.receipt.get("message") + return ( + f"Build {self.build} is published but is not current: the " + f"release's current build is {current}." + (f" {note}" if note else "") + ) + return f"Build {self.build} of {self.release} is published" + ( + " and current." if self.current else "." + ) + + def as_json(self) -> dict[str, Any]: + """The outcome as the command prints it.""" + return { + "repository": self.repository, + "release": self.release, + "build": self.build, + "status": self.receipt["status"], + "current": self.current, + "current_build": self.receipt.get("current"), + "error_code": self.receipt.get("error_code"), + "message": self.receipt.get("message"), + "commit": self.receipt.get("commit"), + "handover_id": self.receipt.get("handover_id"), + } + + +def _hand_over( + change: ReleaseChange, + *, + client: ReleaseEmitter | None, + wait_seconds: float, + wanted_current: bool, +) -> ReleasePublication: + owned = client is None + emitter: ReleaseEmitter = _start_release_emitter() if owned else client + try: + problem = emitter_problem(emitter) + if problem is not None: + receipt = unavailable_release_receipt(change) + elif isinstance(change, PublishRelease): + receipt = emitter.publish_release(change, wait_seconds=wait_seconds) + else: + receipt = emitter.promote_build(change, wait_seconds=wait_seconds) + finally: + if owned: + emitter.close() + return ReleasePublication( + repository=change.repository, + release=change.release, + build=change.build, + wanted_current=wanted_current, + receipt=receipt, + problem=problem, + ) + + +def publication_request( + prepared: BuildFolderRelease, *, make_current: bool +) -> PublishRelease: + """The ``publish_release`` request for a checked build.""" + return PublishRelease( + repository=prepared.repository, + release=prepared.release, + build=prepared.build, + release_role=prepared.release_role, + make_current=make_current, + files=[ + ReleaseFile( + name=item.name, + role=item.role, + local_path=item.path, + sha256=item.sha256, + bytes=item.bytes, + ) + for item in prepared.files + ], + ) + + +def publish_release_build( + release_dir: Path | str, + *, + repository: str | None = None, + artifact_root: Path | str | None = None, + make_current: bool = False, + client: ReleaseEmitter | None = None, + wait_seconds: float = PUBLICATION_WAIT_SECONDS, +) -> ReleasePublication: + """Check a build and hand it to the emitter to publish into its folder. + + The build is checked first (:func:`prepare_build_folder_release`), so a + build that breaks its release contract is never handed over. Without a + ``client``, a short-lived emitter is started and closed afterwards; its + queue is the one builds on this machine share, so a change still pending + when it closes is retried by the next emitter started here. + """ + prepared = prepare_build_folder_release( + release_dir, artifact_root=artifact_root, repository=repository + ) + return _hand_over( + publication_request(prepared, make_current=make_current), + client=client, + wait_seconds=wait_seconds, + wanted_current=make_current, + ) + + +def promote_release_build( + release_dir: Path | str, + *, + repository: str | None = None, + client: ReleaseEmitter | None = None, + wait_seconds: float = PROMOTION_WAIT_SECONDS, +) -> ReleasePublication: + """Make a published build, named by its local manifest, the current build.""" + named_repository, release, build = build_folder_identity(release_dir) + if repository is not None and repository != named_repository: + raise ValueError( + f"release {release!r} names {named_repository} in its artifacts, not " + f"{repository}." + ) + return _hand_over( + PromoteBuild(repository=named_repository, release=release, build=build), + client=client, + wait_seconds=wait_seconds, + wanted_current=True, + ) + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="microcosm-publish-release-build", + description=( + "Publish a build of a release whose builds publish into their own " + "folders (every UK release) through the emitter, or make a " + "published build current. Releases that publish with tags and " + "latest.json use tools/publish_release.sh." + ), + ) + parser.add_argument("release_dir", type=Path, help="The local release directory.") + parser.add_argument( + "--repo-id", + help=( + "The Hugging Face dataset repository; it must be the one the " + "release manifest's artifacts name, which is the default." + ), + ) + parser.add_argument( + "--artifact-root", + type=Path, + help="Where artifacts not in the release directory are, such as the H5.", + ) + action = parser.add_mutually_exclusive_group() + action.add_argument( + "--make-current", + action="store_true", + help="Make the build the release's current build when it is published.", + ) + action.add_argument( + "--promote", + action="store_true", + help="Make this already published build the release's current build.", + ) + action.add_argument( + "--preflight-only", + action="store_true", + help="Check the build and list what would be published; start no emitter.", + ) + parser.add_argument( + "--wait-seconds", + type=float, + help=( + "How long to wait for the change to land or be refused (default " + f"{PUBLICATION_WAIT_SECONDS:.0f} for a publication, " + f"{PROMOTION_WAIT_SECONDS:.0f} for a promotion)." + ), + ) + parser.add_argument( + "--allow-missing-staging", + action="store_true", + help=( + "Publish even if the build recorded staging that never arrived. A " + "build that declared --no-staging publishes without the flag." + ), + ) + return parser + + +def main(argv: list[str] | None = None) -> int: + """``microcosm-publish-release-build``: 0 when the change did what it asked. + + A build that fails its checks (the release contract, a file whose bytes + differ, another repository) is refused with the reason and status 1, + before any emitter starts. + """ + parser = _parser() + args = parser.parse_args(argv) + release_dir: Path = args.release_dir + if not publishes_to_build_folder(release_dir.name): + parser.error( + f"release {release_dir.name!r} publishes with tags and latest.json; " + "publish it with tools/publish_release.sh." + ) + try: + return _run(args) + except (ValueError, FileNotFoundError) as error: + print(f"refusing to publish: {error}", file=sys.stderr) + return 1 + + +def _run(args: argparse.Namespace) -> int: + release_dir: Path = args.release_dir + if args.promote: + outcome = promote_release_build( + release_dir, + repository=args.repo_id, + wait_seconds=( + PROMOTION_WAIT_SECONDS + if args.wait_seconds is None + else args.wait_seconds + ), + ) + else: + refusal = publication_refusal( + release_dir, allow_missing_staging=args.allow_missing_staging + ) + if refusal is not None: + print(refusal, file=sys.stderr) + return 1 + if args.preflight_only: + prepared = prepare_build_folder_release( + release_dir, artifact_root=args.artifact_root, repository=args.repo_id + ) + verdict: dict[str, Any] = { + "valid": True, + "published": False, + "release": prepared.release, + "build": prepared.build, + "repository": prepared.repository, + "release_role": prepared.release_role, + } + if prepared.contract_warnings: + verdict["contract_warnings"] = list(prepared.contract_warnings) + print(json.dumps(verdict)) + return 0 + outcome = publish_release_build( + release_dir, + repository=args.repo_id, + artifact_root=args.artifact_root, + make_current=args.make_current, + wait_seconds=( + PUBLICATION_WAIT_SECONDS + if args.wait_seconds is None + else args.wait_seconds + ), + ) + print(json.dumps(outcome.as_json(), indent=2)) + print(outcome.explanation(), file=sys.stderr) + return 0 if outcome.succeeded else 1 + + +if __name__ == "__main__": # pragma: no cover + raise SystemExit(main()) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py index a428f027e8..04d1f813b6 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py @@ -276,15 +276,23 @@ def test_the_command_promotes_with_promote( monkeypatch, capsys, ) -> None: - client = FakeEmitterClient() - monkeypatch.setattr(release_publication, "_start_release_emitter", lambda: client) + """Each command starts its own emitter; both write to one repository.""" + repository: dict = {} + emitters: list[FakeEmitterClient] = [] + + def start() -> FakeEmitterClient: + emitters.append(FakeEmitterClient(hub_files=repository)) + return emitters[-1] + + monkeypatch.setattr(release_publication, "_start_release_emitter", start) assert _run([str(national), "--artifact-root", str(artifact_root)], capsys)[0] == 0 code, output, _ = _run([str(national), "--promote"], capsys) assert code == 0 assert output["current"] is True - assert client.calls.count("promote_build") == 1 + assert [emitter.calls.count("promote_build") for emitter in emitters] == [0, 1] + assert all(emitter.closed for emitter in emitters) def test_preflight_checks_the_build_without_an_emitter( @@ -315,19 +323,11 @@ def test_preflight_checks_the_build_without_an_emitter( } -@pytest.mark.parametrize( - "arguments", - [ - ["--repo-id", "policyengine/populace-uk-staging"], - ["--promote", "--make-current"], - ], -) -def test_the_command_refuses_conflicting_arguments( +def test_the_command_refuses_another_repository( national: Path, artifact_root: Path, # noqa: F811 monkeypatch, capsys, - arguments: list[str], ) -> None: monkeypatch.setattr( release_publication, @@ -335,10 +335,24 @@ def test_the_command_refuses_conflicting_arguments( lambda: pytest.fail("a refused command starts no emitter"), ) - with pytest.raises((SystemExit, ValueError)): - release_publication.main( - [str(national), "--artifact-root", str(artifact_root), *arguments] - ) + code, output, error = _run( + [ + str(national), + "--artifact-root", + str(artifact_root), + "--repo-id", + "policyengine/populace-uk-staging", + ], + capsys, + ) + + assert (code, output) == (1, None) + assert "names policyengine/populace-uk-private" in error + + +def test_the_command_does_one_thing_at_a_time(national: Path) -> None: # noqa: F811 + with pytest.raises(SystemExit): + release_publication.main([str(national), "--promote", "--make-current"]) def test_the_command_refuses_a_release_that_still_publishes_with_tags( diff --git a/packages/microcosm-data/README.md b/packages/microcosm-data/README.md index 5561b14dd2..a0f9cd105d 100644 --- a/packages/microcosm-data/README.md +++ b/packages/microcosm-data/README.md @@ -22,7 +22,15 @@ sim.calculate("household_net_income", 2024).sum() `load("us")` (no year) loads the latest published compact year. It resolves `latest.json`, reads the selected release manifest at the immutable release tag, verifies the artifact SHA-256, and refuses model or Core versions outside -the release's certified compatibility specifiers. `available()` lists +the release's certified compatibility specifiers. + +A UK release publishes each build into its own folder, +`releases///`, and the repository's `releases.json` records +which build of each release is current. `load("uk")` reads that record, then +the current build's `release_manifest.json`, then the dataset it names, all +from the build's folder, and checks the SHA-256 and engine versions the same +way. `load("uk", build="")` loads a listed build instead (a withdrawn +one with a warning). `available()` lists the default-variant `(country, year)` pairs (the ones a bare ``load(country, year)`` resolves); `available_variants()` lists every published `(country, year, variant)`, non-default lines included. @@ -30,6 +38,7 @@ resolves); `available_variants()` lists every published The old mutable-root behavior is available only as an unsafe escape hatch: `load("us", 2024, unverified_root=True)`. It emits a runtime warning because it bypasses the release pointer, manifest, digest, and engine compatibility checks. +A build-folder release has no root file, so it refuses the option. ## Why a shard, not a repo per country @@ -68,7 +77,8 @@ benchmark comparisons live outside this package. ## Release contract -Published releases live under `releases//` in the Hub dataset repo. +Published US releases live under `releases//` in the Hub dataset +repo, and UK release builds under `releases///`. Each release must include `build_manifest.json` and `release_manifest.json`; US releases must also include `us_source_coverage.json`. A current release manifest contains a typed `calibration_diagnostics` status. `available` binds a diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index 0c8f2bf34e..cb0ccc0db9 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -40,7 +40,7 @@ import math import os import re -from collections.abc import Callable, Mapping +from collections.abc import Mapping from datetime import date from pathlib import Path @@ -162,6 +162,72 @@ def compatibility_claim_declarer_error(declared_by: object) -> str | None: NATIONAL_DEFAULT_DATASET_ROLE = "national_default" NON_DEFAULT_LOCAL_AREA_DATASET_ROLE = "non_default_local_area" +# --- The build-folder layout (hand-over step H2c) -------------------------- +# A release that publishes each build into its own folder, +# ``releases///``, through the emitter's ``publish_release`` +# call. The repository's ``releases.json`` is the only record of each +# release's builds and which one is current. Both manifests name the release +# and the build as two strings; the release manifest records the build's +# ``built_at`` and built-with packages at the top level and each file's +# ``role``, and pins no revision, since nothing is tagged. + +#: Each release's role in ``releases.json``, from its manifest's +#: ``dataset_role``. A release keeps the role it was first published with. +RELEASE_ROLES: Mapping[str, str] = { + NATIONAL_DEFAULT_DATASET_ROLE: "national", + NON_DEFAULT_LOCAL_AREA_DATASET_ROLE: "local_area", +} +#: The roles of a build folder's own files. The emitter interface names the +#: same strings (``microcosm_emitter_interface.publication`` and ``.bundles``); +#: this package supports Python versions the interface does not, so it +#: repeats them, and a build-shard test holds the two equal. +RELEASE_MANIFEST_FILE_ROLE = "release_manifest" +BUILD_MANIFEST_FILE_ROLE = "build_manifest" +CHECKSUMS_FILE_ROLE = "checksums" +DATASET_FILE_ROLE = "dataset" +CALIBRATION_DIAGNOSTICS_FILE_ROLE = "calibration_diagnostics" +CALIBRATION_WEIGHTS_FILE_ROLE = "calibration_weights" +#: A build folder's checksum ledger, published when the release directory +#: carries one (the local-area contracts require it). +CHECKSUMS_FILE = "sha256sums.txt" +#: The fields that named the build before the build-folder layout. The build +#: is the calibration attempt ID, so ``attempt_id`` is ``build``; there is no +#: tag, so no ``cut_tag``; and ``build_id`` held the release's name. +RETIRED_BUILD_FIELDS = ("build_id", "attempt_id", "cut_tag") +#: The emitter interface's identifier rule for a release or build name. +_SAFE_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") +_ROLE_IDENTIFIER_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") + + +def publishes_to_build_folder(release_id: str) -> bool: + """Whether builds of ``release_id`` publish into their own build folders. + + This is the one place that says which releases use the build-folder + layout: the UK national, dense and local-area releases. Every US release + keeps the tagged layout and ``latest.json`` until the stable releases US + builds publish under are agreed with the US data builder; this function + then names them too, and their builders write the same manifests. + """ + return ( + release_id in {_UK_NATIONAL_RELEASE_ID, _UK_DENSE_RELEASE_ID} + or _UK_LOCAL_LINE_RELEASE_ID_RE.fullmatch(release_id) is not None + ) + + +def release_artifact_role(key: str, kind: object) -> str: + """The role a build folder's manifest records for one artifact. + + The microdata is ``dataset`` and the calibration weights are + ``calibration_weights``; every other artifact's role is its key, so the + calibration diagnostics keep ``calibration_diagnostics``. + """ + if kind == "microdata": + return DATASET_FILE_ROLE + if kind == "calibration": + return CALIBRATION_WEIGHTS_FILE_ROLE + return key + + #: Files a non-default local-area release directory must carry. The source #: coverage entry matches :data:`US_SOURCE_COVERAGE_DIAGNOSTICS_FILE`. LOCAL_AREA_REQUIRED_RELEASE_FILES = ( @@ -749,7 +815,13 @@ def _is_hierarchy_diagnostics_version(value: object) -> bool: def line_for_release_id(release_id: str) -> str | None: - """Return the promotable UK publication line for ``release_id``.""" + """Return the ```` name of the ``latest-.json`` pointer file. + + Each such pointer file named the current build of one UK release before + UK releases published into build folders: ``national`` for the national + release and ``local-k`` for a local-area one. Only the pointer reader + still needs it. + """ if release_id == _UK_NATIONAL_RELEASE_ID: return "national" match = _UK_LOCAL_LINE_RELEASE_ID_RE.fullmatch(release_id) @@ -758,32 +830,12 @@ def line_for_release_id(release_id: str) -> str | None: return None -def dataset_role_for_line(line: str) -> str: - """The one dataset role a publication line may carry. - - The national line publishes national-default releases; every local-area - line publishes non-default local-area releases. The publisher refuses a - line promotion whose manifest declares another role, and the loader - refuses a manifest that reached a line pointer with the wrong role, so a - local-area release can never ride the national pointer (or the reverse) - on the strength of its release id alone. - """ - if line == "national": - return NATIONAL_DEFAULT_DATASET_ROLE - if re.fullmatch(r"local-k[1-9][0-9]*", line): - return NON_DEFAULT_LOCAL_AREA_DATASET_ROLE - raise ValueError(f"{line!r} is not a publication line.") - - # The dense joint national + local line (microcosm#762 A18, ruling # 2026-09-03): the same constant-id approach, published on the inspect lane # under the non-default local-area role. Mirrored from # microcosm.build.uk_runtime.release_identity.UK_DENSE_RELEASE_ID; lockstep- # tested in test_gate_battery_contract_pins.py. _UK_DENSE_RELEASE_ID = "microcosm-uk-2024-25-dense" -_UK_DENSE_CUT_TAG_RE = re.compile( - re.escape(_UK_DENSE_RELEASE_ID) + r"-[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}" -) #: The dense line's published microdata filename; mirrors #: ``tools/assemble_uk_dense_release_dir.py::_DATASET_FILENAME`` (lockstep test #: in the build shard's contract-pin suite). @@ -1233,19 +1285,160 @@ def _check_base_pool_not_denied(manifest: Mapping, failures: list[str]) -> None: ) +def _check_build_folder_identity( + manifest: Mapping, release_id: str, *, filename: str, failures: list[str] +) -> None: + """A build-folder manifest names its release and its build, and only so. + + The release is the release directory's name, and the build is a name the + emitter accepts for a folder. The fields that named the build before the + layout (:data:`RETIRED_BUILD_FIELDS`) must be gone. + """ + release = manifest.get("release") + if release != release_id: + failures.append( + f"{filename} 'release' is {release!r} but the release directory is " + f"named {release_id!r}." + ) + build = manifest.get("build") + if not isinstance(build, str) or _SAFE_IDENTIFIER_RE.fullmatch(build) is None: + failures.append( + f"{filename} 'build' must be the build's name, matching " + f"{_SAFE_IDENTIFIER_RE.pattern}; got {build!r}." + ) + for field in RETIRED_BUILD_FIELDS: + if field in manifest: + failures.append( + f"{filename} carries {field!r}; a build-folder manifest names " + "its build only as 'build', and the build has no tag." + ) + + +def _check_build_folder_builds_agree( + build_manifest: Mapping | None, + release_manifest: Mapping | None, + failures: list[str], +) -> None: + """Both manifests of a build folder name the same build.""" + if build_manifest is None or release_manifest is None: + return + builds = (build_manifest.get("build"), release_manifest.get("build")) + if all(isinstance(build, str) for build in builds) and builds[0] != builds[1]: + failures.append( + "build_manifest.json and release_manifest.json name different " + f"builds ({builds[0]!r} and {builds[1]!r})." + ) + + +def _is_bare_file_name(path: str) -> bool: + return bool(path) and path not in {".", ".."} and not set(path) & {"/", "\\"} + + +def _check_build_folder_release_details( + manifest: Mapping, release_id: str, failures: list[str] +) -> None: + """``built_at`` and the built-with packages, at the manifest's top level.""" + built_at = manifest.get("built_at") + if not isinstance(built_at, str) or not built_at: + failures.append( + "release_manifest.json 'built_at' must be the time the build was made." + ) + built_with_core_package = manifest.get("built_with_core_package") + built_with_model_package = manifest.get("built_with_model_package") + model_package = _expected_model_package(release_id) + _check_release_manifest_package( + built_with_core_package, + field="built_with_core_package", + expected_name="policyengine-core", + failures=failures, + ) + _check_release_manifest_package( + built_with_model_package, + field="built_with_model_package", + expected_name=model_package, + failures=failures, + ) + _check_compatible_package_entries( + manifest.get("compatible_core_packages"), + field="compatible_core_packages", + expected_name="policyengine-core", + built_with_package=built_with_core_package, + built_with_field="built_with_core_package", + failures=failures, + ) + _check_compatible_package_entries( + manifest.get("compatible_model_packages"), + field="compatible_model_packages", + expected_name=model_package, + built_with_package=built_with_model_package, + built_with_field="built_with_model_package", + failures=failures, + ) + + +def _check_build_folder_artifacts(artifacts: Mapping, failures: list[str]) -> None: + """Each file of a build folder: its role, a bare name and no revision.""" + for key, entry in artifacts.items(): + if not isinstance(entry, Mapping): + failures.append( + f"release_manifest.json artifact {key!r} must be an object." + ) + continue + for field in ("kind", "path", "repo_id", "sha256", "role"): + if not entry.get(field): + failures.append( + f"release_manifest.json artifact {key!r} is missing {field!r}." + ) + if "revision" in entry: + failures.append( + f"release_manifest.json artifact {key!r} pins revision " + f"{entry['revision']!r}; a build folder's files are found through " + "releases.json, and the build has no tag." + ) + path = entry.get("path") + if isinstance(path, str) and path and not _is_bare_file_name(path): + failures.append( + f"release_manifest.json artifact {key!r} path {path!r} must be a " + "bare file name in the build's folder." + ) + role = entry.get("role") + expected_role = release_artifact_role(str(key), entry.get("kind")) + if role and role != expected_role: + failures.append( + f"release_manifest.json artifact {key!r} role is {role!r}, not " + f"{expected_role!r}." + ) + if isinstance(role, str) and _ROLE_IDENTIFIER_RE.fullmatch(role) is None: + failures.append( + f"release_manifest.json artifact {key!r} role {role!r} must match " + f"{_ROLE_IDENTIFIER_RE.pattern}." + ) + _check_sha256_field( + filename="release_manifest.json", + owner=f"artifact {key!r}.sha256", + value=entry.get("sha256"), + failures=failures, + ) + + def _check_build_manifest( manifest: Mapping, release_id: str, failures: list[str] ) -> None: _check_base_pool_not_denied(manifest, failures) - build_id = manifest.get("build_id") - if not build_id: - failures.append("build_manifest.json is missing 'build_id'.") - elif build_id != release_id: - failures.append( - f"build_manifest.json 'build_id' is {build_id!r} but the release " - f"directory is named {release_id!r}; the directory name IS the " - f"build id." + if publishes_to_build_folder(release_id): + _check_build_folder_identity( + manifest, release_id, filename="build_manifest.json", failures=failures ) + else: + build_id = manifest.get("build_id") + if not build_id: + failures.append("build_manifest.json is missing 'build_id'.") + elif build_id != release_id: + failures.append( + f"build_manifest.json 'build_id' is {build_id!r} but the release " + f"directory is named {release_id!r}; the directory name IS the " + f"build id." + ) code = manifest.get("code") if not isinstance(code, Mapping): failures.append( @@ -1442,8 +1635,14 @@ def _check_release_manifest( f"this library publishes version " f"{expected_schema_version!r}." ) + build_folder = publishes_to_build_folder(release_id) build = manifest.get("build") - if not isinstance(build, Mapping) or not build.get("build_id"): + if build_folder: + _check_build_folder_identity( + manifest, release_id, filename="release_manifest.json", failures=failures + ) + _check_build_folder_release_details(manifest, release_id, failures) + elif not isinstance(build, Mapping) or not build.get("build_id"): failures.append("release_manifest.json is missing 'build.build_id'.") elif build["build_id"] != release_id: failures.append( @@ -1452,7 +1651,7 @@ def _check_release_manifest( f"{release_id!r}." ) _check_uk_release_identity(manifest, release_id, failures) - if isinstance(build, Mapping): + if not build_folder and isinstance(build, Mapping): built_with_core_package = build.get("built_with_core_package") built_with_model_package = build.get("built_with_model_package") _check_release_manifest_package( @@ -1503,8 +1702,11 @@ def _check_release_manifest( failures.append( "release_manifest.json must declare a non-empty 'artifacts' mapping." ) + elif build_folder: + _check_calibration_diagnostics_declaration(manifest, artifacts, failures) + _check_build_folder_artifacts(artifacts, failures) + _check_default_dataset_artifact(default_datasets, artifacts, failures) else: - line_cut_tag_re = _uk_line_cut_tag_re(release_id) _check_calibration_diagnostics_declaration(manifest, artifacts, failures) for key, entry in artifacts.items(): if not isinstance(entry, Mapping): @@ -1518,14 +1720,8 @@ def _check_release_manifest( f"release_manifest.json artifact {key!r} is missing {field!r}." ) revision = entry.get("revision") - revision_matches_release = ( - revision == release_id - or (annual_revision is not None and revision == annual_revision) - or ( - line_cut_tag_re is not None - and isinstance(revision, str) - and line_cut_tag_re.fullmatch(revision) is not None - ) + revision_matches_release = revision == release_id or ( + annual_revision is not None and revision == annual_revision ) # A present-but-non-string revision must fail here rather than # slide past the isinstance guard: publish collects only string @@ -1534,15 +1730,9 @@ def _check_release_manifest( if revision and ( not isinstance(revision, str) or not revision_matches_release ): - expected = ( - f"the release id {release_id!r} or a " - f"'{release_id}--' per-cut tag" - if line_cut_tag_re is not None - else f"the release id {release_id!r}" - ) failures.append( f"release_manifest.json artifact {key!r} revision is " - f"{revision!r}, expected {expected}." + f"{revision!r}, expected the release id {release_id!r}." ) if isinstance(entry, Mapping): _check_sha256_field( @@ -1596,24 +1786,32 @@ def _check_release_manifest( "release_manifest.json terminal gate report artifact " "must have kind 'diagnostics'." ) - if isinstance(default_datasets, Mapping): - national = default_datasets.get("national") - if isinstance(national, str) and national not in artifacts: - failures.append( - "release_manifest.json 'default_datasets.national' " - f"points to {national!r}, which is not an artifact key." - ) - elif isinstance(national, str): - default_artifact = artifacts.get(national) - if ( - isinstance(default_artifact, Mapping) - and default_artifact.get("kind") != "microdata" - ): - failures.append( - "release_manifest.json 'default_datasets.national' " - f"points to artifact {national!r}, whose kind is " - f"{default_artifact.get('kind')!r}, not 'microdata'." - ) + _check_default_dataset_artifact(default_datasets, artifacts, failures) + + +def _check_default_dataset_artifact( + default_datasets: object, artifacts: Mapping, failures: list[str] +) -> None: + """``default_datasets.national`` names a microdata artifact.""" + if not isinstance(default_datasets, Mapping): + return + national = default_datasets.get("national") + if isinstance(national, str) and national not in artifacts: + failures.append( + "release_manifest.json 'default_datasets.national' " + f"points to {national!r}, which is not an artifact key." + ) + elif isinstance(national, str): + default_artifact = artifacts.get(national) + if ( + isinstance(default_artifact, Mapping) + and default_artifact.get("kind") != "microdata" + ): + failures.append( + "release_manifest.json 'default_datasets.national' " + f"points to artifact {national!r}, whose kind is " + f"{default_artifact.get('kind')!r}, not 'microdata'." + ) def _calibration_diagnostics_required(manifest: object) -> bool: @@ -1908,6 +2106,7 @@ def _check_compatible_package_entries( expected_name: str | None, built_with_package: object, failures: list[str], + built_with_field: str | None = None, ) -> None: if expected_name is None: return @@ -1978,7 +2177,7 @@ def _check_compatible_package_entries( try: version = Version(built_version) except InvalidVersion: - built_field = ( + built_field = built_with_field or ( "build.built_with_core_package" if field == "compatible_core_packages" else "build.built_with_model_package" @@ -1999,7 +2198,8 @@ def _check_compatible_package_entries( def _expected_model_package(release_id: str) -> str | None: if release_id.startswith("populace-us-"): return "policyengine-us" - if release_id == _UK_NATIONAL_RELEASE_ID: + if release_id.startswith("microcosm-uk-"): + # The national, dense and local-area releases. return "policyengine-uk" if release_id.startswith("populace-uk-"): return "policyengine-uk" @@ -4490,7 +4690,15 @@ def _validate_local_area_release_dir(release_dir: Path, release_id: str) -> None build_manifest_path = release_dir / "build_manifest.json" if build_manifest_path.is_file(): build_manifest = _load_json(build_manifest_path, failures) - if build_manifest is not None: + if build_manifest is not None and publishes_to_build_folder(release_id): + _check_build_folder_identity( + build_manifest, + release_id, + filename="build_manifest.json", + failures=failures, + ) + _check_build_folder_builds_agree(build_manifest, release_manifest, failures) + elif build_manifest is not None: build_id = build_manifest.get("build_id") if build_id != release_id: failures.append( @@ -4600,7 +4808,8 @@ def _validate_uk_dense_release_dir(release_dir: Path, release_id: str) -> list[s opt-in diagnostics (microcosm#1301): the coverage says whether each ran, the incumbent files ship all together or not at all, and the manifest's reviewed limitations must say what the release does not claim. - Artifacts pin to the release id or to one of its immutable per-cut tags. + Its builds publish into their own folders, so the manifests name the + build (the calibration attempt) and its artifacts pin no revision. Per-area support figures ship (María's ruling of 2026-10-26 dropped their withholding, microcosm#1301), so the line returns no warnings. """ @@ -4617,15 +4826,7 @@ def _validate_uk_dense_release_dir(release_dir: Path, release_id: str) -> list[s release_dir, release_manifest or {}, failures ) if release_manifest is not None: - _check_local_area_release_manifest( - release_manifest, - release_id, - failures, - revision_ok=lambda revision: ( - revision == release_id - or _UK_DENSE_CUT_TAG_RE.fullmatch(revision) is not None - ), - ) + _check_local_area_release_manifest(release_manifest, release_id, failures) namespace = release_manifest.get("namespace") if namespace != _UK_DENSE_NAMESPACE: failures.append( @@ -4633,6 +4834,7 @@ def _validate_uk_dense_release_dir(release_dir: Path, release_id: str) -> list[s f"{_UK_DENSE_NAMESPACE!r}, got {namespace!r}." ) build_manifest_path = release_dir / "build_manifest.json" + # The build is the calibration attempt the signed report is bound to. attempt_id: str | None = None if build_manifest_path.is_file(): build_manifest = _load_json(build_manifest_path, failures) @@ -4642,20 +4844,16 @@ def _validate_uk_dense_release_dir(release_dir: Path, release_id: str) -> list[s failures.append( "build_manifest.json code.git_dirty must be false for release." ) - candidate_attempt = build_manifest.get("attempt_id") - if isinstance(candidate_attempt, str) and candidate_attempt: - attempt_id = candidate_attempt - else: - failures.append( - "build_manifest.json must carry the calibration 'attempt_id' " - "the signed gate report is bound to." - ) - if build_manifest is not None and build_manifest.get("build_id") != release_id: - failures.append( - "build_manifest.json 'build_id' is " - f"{build_manifest.get('build_id')!r} but the release directory " - f"is named {release_id!r}." + _check_build_folder_identity( + build_manifest, + release_id, + filename="build_manifest.json", + failures=failures, ) + _check_build_folder_builds_agree(build_manifest, release_manifest, failures) + build = build_manifest.get("build") + if isinstance(build, str) and build: + attempt_id = build gate_path = release_dir / "gate_summary.json" if gate_path.is_file(): gate_summary = _load_json(gate_path, failures) @@ -5419,8 +5617,6 @@ def _check_local_area_release_manifest( manifest: Mapping, release_id: str, failures: list[str], - *, - revision_ok: Callable[[str], bool] | None = None, ) -> None: schema_version = manifest.get("schema_version") if schema_version != RELEASE_MANIFEST_SCHEMA_VERSION: @@ -5428,8 +5624,14 @@ def _check_local_area_release_manifest( f"release_manifest.json 'schema_version' is {schema_version!r}; " f"this library publishes version {RELEASE_MANIFEST_SCHEMA_VERSION}." ) + build_folder = publishes_to_build_folder(release_id) build = manifest.get("build") - if not isinstance(build, Mapping) or not build.get("build_id"): + if build_folder: + _check_build_folder_identity( + manifest, release_id, filename="release_manifest.json", failures=failures + ) + _check_build_folder_release_details(manifest, release_id, failures) + elif not isinstance(build, Mapping) or not build.get("build_id"): failures.append("release_manifest.json is missing 'build.build_id'.") elif build["build_id"] != release_id: failures.append( @@ -5489,6 +5691,9 @@ def _check_local_area_release_manifest( "release_manifest.json must declare exactly one microdata " f"artifact; found {sorted(microdata)!r}." ) + if build_folder: + _check_build_folder_artifacts(artifacts, failures) + return for name, entry in artifacts.items(): if not isinstance(entry, Mapping): failures.append( @@ -5501,11 +5706,7 @@ def _check_local_area_release_manifest( f"release_manifest.json artifact {name!r} is missing {field!r}." ) revision = entry.get("revision") - pinned = ( - revision == release_id - if revision_ok is None - else bool(revision_ok(str(revision))) - ) + pinned = revision == release_id if revision is not None and not pinned: failures.append( f"release_manifest.json artifact {name!r} revision " @@ -6661,7 +6862,10 @@ def validate_release_dir( The directory name is the build id (``populace-us-2024--``) and both manifests must agree with the directory about which build this - is. Which checks apply is keyed off ``release_manifest.json``'s + is. A release that publishes each build into its own folder + (:func:`publishes_to_build_folder`) is named by the directory instead, + and both manifests name it and the build in the build-folder layout. + Which checks apply is keyed off ``release_manifest.json``'s ``dataset_role`` (microcosm#398): - ``national_default`` (or absent — every pre-role release): the full @@ -6960,6 +7164,8 @@ def validate_release_dir( failures, ) + if publishes_to_build_folder(release_id): + _check_build_folder_builds_agree(build_manifest, release_manifest, failures) _check_cross_manifest_consistency( build_manifest, release_manifest, @@ -8014,7 +8220,7 @@ def _check_uk_dense_surface_files( "calibration_diagnostics.json changed original evaluated " "diagnostic values." ) - if build and report and report.get("release_id") != build.get("attempt_id"): + if build and report and report.get("release_id") != build.get("build"): failures.append( "the signed gate report is not bound to the released attempt." ) diff --git a/packages/microcosm-data/src/microcosm/data/loader.py b/packages/microcosm-data/src/microcosm/data/loader.py index 9f5c63cc2f..0e1fd7379c 100644 --- a/packages/microcosm-data/src/microcosm/data/loader.py +++ b/packages/microcosm-data/src/microcosm/data/loader.py @@ -1,12 +1,21 @@ """Resolve, verify, download, and load a certified microcosm release. -The normal path follows the repository's release certificate: resolve the -registry-selected pointer, read that release's manifest at the pointer's -immutable revision, download the manifest-selected dataset at the same -revision, verify its SHA-256, and enforce the certified model/Core versions -before constructing the engine dataset. Mutable root artifacts are available -only through the explicitly unsafe ``load(..., unverified_root=True)`` escape -hatch. +A release whose builds publish into their own folders (every UK release in +the registry) is read through the repository's ``releases.json``: the record +names the release's current build (or ``build=`` pins a listed one), the +loader reads ``releases///release_manifest.json``, downloads +the dataset that manifest names from the same folder, verifies its SHA-256, +and enforces the certified model/Core versions before constructing the engine +dataset. Build folders never change after publishing, so every file is read +at ``main``. + +A release that keeps the tagged layout (every US release) follows the +repository's release certificate: resolve the registry-selected pointer, read +that release's manifest at the pointer's immutable revision, download the +manifest-selected dataset at the same revision and check it the same way. +Its mutable root artifacts are available only through the explicitly unsafe +``load(..., unverified_root=True)`` escape hatch; a build-folder release has +no root file. """ from __future__ import annotations @@ -27,19 +36,22 @@ from packaging.version import InvalidVersion, Version from microcosm.data.contract import ( + DATASET_FILE_ROLE, NATIONAL_DEFAULT_DATASET_ROLE, NON_DEFAULT_LOCAL_AREA_DATASET_ROLE, RELEASE_MANIFEST_SCHEMA_VERSION, - dataset_role_for_line, + RELEASE_ROLES, ) from microcosm.data.registry import DEFAULT_VARIANT, REGISTRY, DatasetSpec from microcosm.data.release import ( LATEST_POINTER_PATH, - LINE_POINTER_PATH_TEMPLATE, LatestPointer, - latest_line_release, latest_release, - line_pointer_path, +) +from microcosm.data.releases_record import ( + RELEASES_RECORD_PATH, + build_folder, + parse_releases_record, ) __all__ = [ @@ -52,25 +64,9 @@ ] _SHA256_PATTERN = re.compile(r"[0-9a-fA-F]{64}") -_LINE_POINTER_PATH_PATTERN = re.compile( - re.escape(LINE_POINTER_PATH_TEMPLATE).replace(re.escape("{line}"), r"(?P.+)") -) _HubDownload = Callable[..., str] -def _line_from_pointer_path(pointer_path: str) -> str | None: - """Invert the shared line-pointer template and validate its line.""" - match = _LINE_POINTER_PATH_PATTERN.fullmatch(pointer_path) - if match is None: - return None - line = match.group("line") - try: - rendered_path = line_pointer_path(line) - except ValueError: - return None - return line if rendered_path == pointer_path else None - - @dataclass(frozen=True) class _PackageCertification: name: str @@ -80,13 +76,21 @@ class _PackageCertification: @dataclass(frozen=True) class _CertifiedRelease: + """A release's certified dataset: where it is and what it was built with. + + For a build-folder release, ``build`` is the build that was loaded, + ``artifact_path`` is inside its folder and ``artifact_revision`` is + ``None`` (the folder never changes, so it is read at ``main``). + """ + release_id: str artifact_repo_id: str artifact_path: str - artifact_revision: str + artifact_revision: str | None artifact_sha256: str model: _PackageCertification core: _PackageCertification + build: str | None = None class _CertifiedPackageCompatibilityError(ValueError): @@ -211,6 +215,7 @@ def _package_certification( package_name: str, built_field: str, release_id: str, + build_folder: bool = False, ) -> _PackageCertification: entries = manifest.get(field) if not isinstance(entries, list): @@ -236,8 +241,14 @@ def _package_certification( f"{package_name}." ) - build = _required_mapping(manifest, "build", release_id=release_id) - built_package = _required_mapping(build, built_field, release_id=release_id) + # A build-folder manifest records what the build was built with at its + # top level; a tagged one, in its ``build`` object. + owner = ( + manifest + if build_folder + else _required_mapping(manifest, "build", release_id=release_id) + ) + built_package = _required_mapping(owner, built_field, release_id=release_id) if built_package.get("name") != package_name: raise ValueError( f"Release {release_id!r} build provenance does not name {package_name}." @@ -265,9 +276,16 @@ def _certified_release_from_manifest( release_id: str, manifest: Mapping[str, Any], *, - expected_revision: str, + expected_revision: str | None, + build: str | None = None, + release_role: str | None = None, ) -> _CertifiedRelease: - """Validate and select ``spec`` from one release manifest.""" + """Validate and select ``spec`` from one release manifest. + + With ``build``, the manifest is that build's, read from its folder in a + build-folder release whose ``releases.json`` gives it ``release_role``; + otherwise it is a tagged release's, read at ``expected_revision``. + """ schema_version = manifest.get("schema_version") if schema_version != RELEASE_MANIFEST_SCHEMA_VERSION: raise ValueError( @@ -275,12 +293,23 @@ def _certified_release_from_manifest( f"{schema_version!r}; this microcosm-data reads version " f"{RELEASE_MANIFEST_SCHEMA_VERSION}. Upgrade microcosm-data." ) - build = _required_mapping(manifest, "build", release_id=release_id) - if build.get("build_id") != release_id: - raise ValueError( - f"{spec.pointer_path} points to release {release_id!r}, but its release " - f"manifest declares build_id {build.get('build_id')!r}." - ) + build_folder_release = build is not None + if build_folder_release: + folder = build_folder(release_id, build) + named = (manifest.get("release"), manifest.get("build")) + if named != (release_id, build): + raise ValueError( + f"{folder}/release_manifest.json names release {named[0]!r} and " + f"build {named[1]!r}, not {release_id!r} and {build!r}." + ) + else: + tagged_build = _required_mapping(manifest, "build", release_id=release_id) + if tagged_build.get("build_id") != release_id: + raise ValueError( + f"{spec.pointer_path} points to release {release_id!r}, but its " + "release manifest declares build_id " + f"{tagged_build.get('build_id')!r}." + ) dataset_role = manifest.get("dataset_role", NATIONAL_DEFAULT_DATASET_ROLE) if dataset_role not in { @@ -290,17 +319,14 @@ def _certified_release_from_manifest( raise ValueError( f"Release {release_id!r} has unknown dataset_role {dataset_role!r}." ) - pointer_line = _line_from_pointer_path(spec.pointer_path) - if pointer_line is not None: - # A line pointer carries one role: the manifest it names must - # declare it, whatever its release id says. - expected_role = dataset_role_for_line(pointer_line) - if dataset_role != expected_role: - raise ValueError( - f"Release {release_id!r} declares dataset_role {dataset_role!r}; " - f"{spec.pointer_path!r} follows line {pointer_line!r}, which " - f"publishes only {expected_role!r} releases." - ) + if build_folder_release and release_role != RELEASE_ROLES[dataset_role]: + # releases.json gives a release one role, so a manifest whose role + # differs is not this release's, whatever its names say. + raise ValueError( + f"Release {release_id!r} is listed with role {release_role!r} in " + f"releases.json, but build {build!r} declares dataset_role " + f"{dataset_role!r}." + ) default_datasets = _required_mapping( manifest, "default_datasets", release_id=release_id ) @@ -312,11 +338,11 @@ def _certified_release_from_manifest( ) artifact_label = "default" else: - if _line_from_pointer_path(spec.pointer_path) is None: + if not build_folder_release: raise ValueError( f"Release {release_id!r} declares dataset_role " - f"{NON_DEFAULT_LOCAL_AREA_DATASET_ROLE!r}; it may be selected only " - f"through a {LINE_POINTER_PATH_TEMPLATE!r} line pointer, not " + f"{NON_DEFAULT_LOCAL_AREA_DATASET_ROLE!r}; a local-area release " + "is loaded from its build folder through releases.json, not " f"{spec.pointer_path!r}." ) if default_datasets != {}: @@ -328,23 +354,40 @@ def _certified_release_from_manifest( artifact_label = "local-area" artifacts = _required_mapping(manifest, "artifacts", release_id=release_id) - # One revision per pointer, by intent: the loader follows a pointer to a - # single immutable revision and downloads every artifact of the release - # from it, so every artifact must be pinned to exactly that revision. - # This is stricter than the publisher contract's annual-revision - # allowance for mixed-revision releases; a release that mixes revisions - # is publishable for inspection but never resolvable as a default here. - mismatched_revisions = { - str(key): candidate.get("revision") if isinstance(candidate, Mapping) else None - for key, candidate in artifacts.items() - if not isinstance(candidate, Mapping) - or candidate.get("revision") != expected_revision - } - if mismatched_revisions: - raise ValueError( - f"Release {release_id!r} has artifacts not pinned to expected revision " - f"{expected_revision!r}: {mismatched_revisions}." + if build_folder_release: + # A build folder's files are found through releases.json; nothing is + # tagged, so a manifest that pins a revision is not this layout's. + pinned = sorted( + str(key) + for key, candidate in artifacts.items() + if not isinstance(candidate, Mapping) or "revision" in candidate ) + if pinned: + raise ValueError( + f"Release {release_id!r} build {build!r} pins a revision on " + f"artifact(s) {pinned}; a build folder's files carry none." + ) + else: + # One revision per pointer, by intent: the loader follows a pointer + # to a single immutable revision and downloads every artifact of the + # release from it, so every artifact must be pinned to exactly that + # revision. This is stricter than the publisher contract's + # annual-revision allowance for mixed-revision releases; a release + # that mixes revisions is publishable for inspection but never + # resolvable as a default here. + mismatched_revisions = { + str(key): candidate.get("revision") + if isinstance(candidate, Mapping) + else None + for key, candidate in artifacts.items() + if not isinstance(candidate, Mapping) + or candidate.get("revision") != expected_revision + } + if mismatched_revisions: + raise ValueError( + f"Release {release_id!r} has artifacts not pinned to expected " + f"revision {expected_revision!r}: {mismatched_revisions}." + ) if dataset_role == NON_DEFAULT_LOCAL_AREA_DATASET_ROLE: microdata_keys = [ key @@ -370,10 +413,14 @@ def _certified_release_from_manifest( f"Release {release_id!r} {artifact_label} artifact {artifact_key!r} has kind " f"{artifact.get('kind')!r}, not 'microdata'." ) + if build_folder_release and artifact.get("role") != DATASET_FILE_ROLE: + raise ValueError( + f"Release {release_id!r} {artifact_label} artifact {artifact_key!r} has " + f"role {artifact.get('role')!r}, not {DATASET_FILE_ROLE!r}." + ) artifact_repo_id = artifact.get("repo_id") artifact_path = artifact.get("path") - artifact_revision = artifact.get("revision") artifact_sha256 = artifact.get("sha256") if artifact_repo_id != spec.hf_repo: raise ValueError( @@ -399,6 +446,7 @@ def _certified_release_from_manifest( package_name=spec.engine_package, built_field="built_with_model_package", release_id=release_id, + build_folder=build_folder_release, ) core = _package_certification( manifest, @@ -406,12 +454,24 @@ def _certified_release_from_manifest( package_name="policyengine-core", built_field="built_with_core_package", release_id=release_id, + build_folder=build_folder_release, ) + if build_folder_release: + return _CertifiedRelease( + release_id=release_id, + artifact_repo_id=artifact_repo_id, + artifact_path=f"{folder}/{artifact_path}", + artifact_revision=None, + artifact_sha256=artifact_sha256.lower(), + model=model, + core=core, + build=build, + ) return _CertifiedRelease( release_id=release_id, artifact_repo_id=artifact_repo_id, artifact_path=artifact_path, - artifact_revision=artifact_revision, + artifact_revision=artifact.get("revision"), artifact_sha256=artifact_sha256.lower(), model=model, core=core, @@ -429,32 +489,110 @@ def _sha256(path: Path) -> str: def _pointer_for( spec: DatasetSpec, *, hub_download: _HubDownload | None = None ) -> LatestPointer: - """Read the release pointer configured for ``spec``.""" + """Read the release pointer configured for a tagged release's ``spec``.""" + if spec.pointer_path != LATEST_POINTER_PATH: + raise ValueError( + f"Unsupported release pointer path {spec.pointer_path!r} for {spec.key}; " + f"a tagged release follows {LATEST_POINTER_PATH!r}, and a release " + "whose builds publish into their own folders is named by the " + "registry entry's release." + ) if hub_download is None: hub_download = _hub_download() - api = SimpleNamespace(hf_hub_download=hub_download) - if spec.pointer_path == LATEST_POINTER_PATH: - return latest_release(spec.hf_repo, api=api) - line = _line_from_pointer_path(spec.pointer_path) - if line is not None: - return latest_line_release( - spec.hf_repo, - line=line, - api=api, - ) - raise ValueError( - f"Unsupported release pointer path {spec.pointer_path!r} for {spec.key}; " - f"expected {LATEST_POINTER_PATH!r} or the " - f"{LINE_POINTER_PATH_TEMPLATE!r} line-pointer form." + return latest_release( + spec.hf_repo, api=SimpleNamespace(hf_hub_download=hub_download) + ) + + +def _resolve_build_folder_release( + spec: DatasetSpec, *, build: str | None, hub_download: _HubDownload +) -> _CertifiedRelease: + """Select a build of ``spec.release`` from ``releases.json`` and check it. + + The current build, unless ``build`` pins a listed one; a pinned build + that has been withdrawn loads with a warning, since a pin is a deliberate + choice. A missing ``releases.json`` raises the Hub's own error. + """ + release = spec.release + assert release is not None + record_path = Path( + hub_download( + repo_id=spec.hf_repo, filename=RELEASES_RECORD_PATH, repo_type="dataset" + ) + ) + try: + record = parse_releases_record(record_path.read_bytes()) + except ValueError as exc: + raise ValueError( + f"{RELEASES_RECORD_PATH} in {spec.hf_repo} is not a valid release " + f"record: {exc}." + ) from exc + entry = record.releases.get(release) + if entry is None: + raise ValueError( + f"{RELEASES_RECORD_PATH} in {spec.hf_repo} does not list release " + f"{release!r}." + ) + if build is None: + build = entry.current + if build is None: + raise ValueError( + f"Release {release!r} in {spec.hf_repo} has no current build; " + "pass build= to load one of its listed builds." + ) + elif build not in entry.builds: + raise ValueError( + f"Build {build!r} of release {release!r} is not listed in " + f"{RELEASES_RECORD_PATH} in {spec.hf_repo}." + ) + elif entry.builds[build].withdrawn: + warnings.warn( + f"Build {build!r} of release {release!r} has been withdrawn; it is " + "loaded because build= pins it.", + UserWarning, + stacklevel=3, + ) + manifest_path = Path( + hub_download( + repo_id=spec.hf_repo, + filename=f"{build_folder(release, build)}/release_manifest.json", + repo_type="dataset", + ) + ) + manifest = _load_manifest(manifest_path, repo_id=spec.hf_repo, release_id=release) + return _certified_release_from_manifest( + spec, + release, + manifest, + expected_revision=None, + build=build, + release_role=entry.role, ) def _resolve_certified_release( - spec: DatasetSpec, *, hub_download: _HubDownload | None = None + spec: DatasetSpec, + *, + hub_download: _HubDownload | None = None, + build: str | None = None, ) -> _CertifiedRelease: - """Resolve and validate the release pointer and its pinned manifest.""" + """Resolve and validate the release's selected build and its manifest. + + A build-folder release reads ``releases.json``; a tagged release follows + its pointer to a pinned manifest, and ``build`` cannot pin one of its + builds. + """ + if spec.release is None and build is not None: + raise ValueError( + f"{spec.key} keeps the tagged layout; build= pins a build only for " + "releases whose builds publish into their own folders." + ) if hub_download is None: hub_download = _hub_download() + if spec.release is not None: + return _resolve_build_folder_release( + spec, build=build, hub_download=hub_download + ) pointer = _pointer_for(spec, hub_download=hub_download) manifest_path = Path( hub_download( @@ -477,9 +615,11 @@ def _resolve_certified_release( ) -def _verified_download(spec: DatasetSpec) -> tuple[Path, _CertifiedRelease]: +def _verified_download( + spec: DatasetSpec, *, build: str | None = None +) -> tuple[Path, _CertifiedRelease]: hub_download = _hub_download() - certified = _resolve_certified_release(spec, hub_download=hub_download) + certified = _resolve_certified_release(spec, hub_download=hub_download, build=build) artifact_path = Path( hub_download( repo_id=certified.artifact_repo_id, @@ -499,6 +639,11 @@ def _verified_download(spec: DatasetSpec) -> tuple[Path, _CertifiedRelease]: def _unverified_root_download(spec: DatasetSpec) -> Path: + if spec.release is not None: + raise ValueError( + f"Release {spec.release!r} publishes each build into its own folder " + "and has no root file to load unverified; load its current build." + ) return Path( _hub_download()( repo_id=spec.hf_repo, @@ -513,20 +658,23 @@ def download( year: int | None = None, *, variant: str = DEFAULT_VARIANT, + build: str | None = None, ) -> Path: - """Download and SHA-verify the latest certified release artifact. + """Download and SHA-verify a certified release artifact. - The registry-selected mutable pointer selects a release; both its manifest - and dataset artifact are then fetched at the pointer's immutable revision. - Uses the Hugging Face cache, so repeated calls do not re-download unchanged - files. + A build-folder release's current build (or the listed ``build`` it pins) + comes from ``releases.json``, and its manifest and dataset from that + build's folder. A tagged release's mutable pointer selects a release; + both its manifest and dataset artifact are then fetched at the pointer's + immutable revision. Uses the Hugging Face cache, so repeated calls do not + re-download unchanged files. Raises: ImportError: If ``huggingface_hub`` is not installed. ValueError: If release metadata or the artifact digest is invalid. """ spec = resolve(country, year, variant=variant) - path, _ = _verified_download(spec) + path, _ = _verified_download(spec, build=build) return path @@ -577,6 +725,7 @@ def load( *, variant: str = DEFAULT_VARIANT, unverified_root: bool = False, + build: str | None = None, ): """Return a certified population as its engine dataset object. @@ -585,15 +734,25 @@ def load( year: Population year; ``None`` loads the latest published year. variant: Dataset variant; ``"compact"`` is the default fast national microsimulation artifact. - unverified_root: Load the mutable root convenience artifact while - bypassing release metadata, SHA-256, and engine certification. - This unsafe compatibility escape hatch emits a loud warning. + unverified_root: Load a tagged release's mutable root convenience + artifact while bypassing release metadata, SHA-256, and engine + certification. This unsafe compatibility escape hatch emits a + loud warning; a build-folder release has no root file. + build: Load this listed build of a build-folder release instead of + its current one. Raises: ImportError: If the country engine is not installed. ValueError: If release verification or engine compatibility fails. """ spec = resolve(country, year, variant=variant) + if unverified_root and (spec.release is not None or build is not None): + raise ValueError( + f"{spec.key} publishes each build into its own folder and has no " + "root file to load unverified; load a build without unverified_root." + if spec.release is not None + else "unverified_root cannot be combined with build=." + ) dataset_class = _dataset_class(spec) if unverified_root: warnings.warn( @@ -605,7 +764,7 @@ def load( ) path = _unverified_root_download(spec) else: - path, certified = _verified_download(spec) + path, certified = _verified_download(spec, build=build) _enforce_package_compatibility(certified.model, release_id=certified.release_id) _enforce_package_compatibility(certified.core, release_id=certified.release_id) return dataset_class(file_path=str(path)) diff --git a/packages/microcosm-data/src/microcosm/data/publish_cli.py b/packages/microcosm-data/src/microcosm/data/publish_cli.py index 29cffb2a48..4ed74a81ec 100644 --- a/packages/microcosm-data/src/microcosm/data/publish_cli.py +++ b/packages/microcosm-data/src/microcosm/data/publish_cli.py @@ -1,4 +1,9 @@ -"""CLI for contract-gated Microcosm release publication.""" +"""CLI for contract-checked Microcosm release publication. + +It publishes releases that keep the tagged layout and ``latest.json``: every +US release. A UK release publishes each build into its own folder through the +emitter (``microcosm-publish-release-build``), and this command refuses it. +""" from __future__ import annotations @@ -141,6 +146,48 @@ def _reform_validation_skipped(release_dir: Path) -> bool: return payload.get("out_of_sample_simulated") is False +def publication_refusal( + release_dir: Path, + *, + allow_incomplete_reform_validation: bool = False, + allow_missing_staging: bool = False, +) -> str | None: + """Why a release must not be published, read from its local files, or None. + + The checks every publication path shares: non-release smoke output, a + reform validation built with out-of-sample reforms skipped, and staging + telemetry that never arrived. Each override flag lifts one check. + """ + if _non_release_artifact(release_dir): + return ( + "refusing to publish: build_manifest.json identifies this as " + "non-release smoke output." + ) + if not allow_incomplete_reform_validation and _reform_validation_skipped( + release_dir + ): + return ( + "refusing to publish: reform_validation.json has " + "out_of_sample_simulated=false (built with " + "--skip-out-of-sample-reforms), so the dashboard would show blank " + "out-of-sample reforms. Rebuild without skipping, or pass " + "--allow-incomplete-reform-validation to publish anyway." + ) + if not allow_missing_staging and _staging_undelivered(release_dir): + return ( + "refusing to publish: this release's build_manifest records no " + "delivered staging telemetry, so the build never appeared on the " + "staging dashboard and there is no pre-publication review of it. " + "Either the staging destination was lost mid-build (uploads " + "self-disable after repeated failures — check the build machine's " + "Hugging Face write token), or the manifest predates staging " + "provenance. Rebuild with staging reaching its repo, or pass " + "--allow-missing-staging to publish anyway. A build that declared " + "--no-staging publishes without the flag." + ) + return None + + def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("release_dir", help="Local releases/ directory.") @@ -195,14 +242,6 @@ def main(argv: list[str] | None = None) -> int: "--tag-name", help="Optional tag name override; defaults to the release id.", ) - parser.add_argument( - "--promote-line", - metavar="LINE", - help=( - "Promote the release through latest-.json. Requires " - "--tag-name and never writes latest.json." - ), - ) parser.add_argument( "--extra-file", action="append", @@ -263,54 +302,18 @@ def main(argv: list[str] | None = None) -> int: ) args = parser.parse_args(argv) - if args.promote_line is not None: - if args.no_latest: - parser.error("--promote-line cannot be combined with --no-latest.") - if args.tag_only: - parser.error("--promote-line cannot be combined with --tag-only.") - if args.evidence: - parser.error("--promote-line cannot be combined with --evidence.") - if not args.tag_name: - parser.error("--promote-line requires --tag-name.") if args.tag_only and not args.no_latest: parser.error("--tag-only requires --no-latest.") if args.tag_only and not args.create_tag: parser.error("--tag-only requires tag creation; remove --no-create-tag.") - if _non_release_artifact(Path(args.release_dir)): - print( - "refusing to publish: build_manifest.json identifies this as " - "non-release smoke output.", - file=sys.stderr, - ) - return 1 - - if not args.allow_incomplete_reform_validation and _reform_validation_skipped( - Path(args.release_dir) - ): - print( - "refusing to publish: reform_validation.json has " - "out_of_sample_simulated=false (built with " - "--skip-out-of-sample-reforms), so the dashboard would show blank " - "out-of-sample reforms. Rebuild without skipping, or pass " - "--allow-incomplete-reform-validation to publish anyway.", - file=sys.stderr, - ) - return 1 - - if not args.allow_missing_staging and _staging_undelivered(Path(args.release_dir)): - print( - "refusing to publish: this release's build_manifest records no " - "delivered staging telemetry, so the build never appeared on the " - "staging dashboard and there is no pre-publication review of it. " - "Either the staging destination was lost mid-build (uploads " - "self-disable after repeated failures — check the build machine's " - "Hugging Face write token), or the manifest predates staging " - "provenance. Rebuild with staging reaching its repo, or pass " - "--allow-missing-staging to publish anyway. A build that declared " - "--no-staging publishes without the flag.", - file=sys.stderr, - ) + refusal = publication_refusal( + Path(args.release_dir), + allow_incomplete_reform_validation=args.allow_incomplete_reform_validation, + allow_missing_staging=args.allow_missing_staging, + ) + if refusal is not None: + print(refusal, file=sys.stderr) return 1 preparation_options = dict( @@ -323,7 +326,6 @@ def main(argv: list[str] | None = None) -> int: update_latest=not args.no_latest, tag_only=args.tag_only, evidence=args.evidence, - line=args.promote_line, ) from microcosm.data.source_enrichment import ( recorded_claim_measurement, diff --git a/packages/microcosm-data/src/microcosm/data/registry.py b/packages/microcosm-data/src/microcosm/data/registry.py index 385a062c01..58a386df11 100644 --- a/packages/microcosm-data/src/microcosm/data/registry.py +++ b/packages/microcosm-data/src/microcosm/data/registry.py @@ -47,7 +47,12 @@ class DatasetSpec: ``"policyengine-us"`` — named in the install extra and in the ImportError when the engine is absent. pointer_path: The repository-root release pointer followed by the - certified loader. + certified loader, for a release that keeps the tagged layout. + release: The release whose builds publish into their own folders, + ``releases///``. The loader then reads the + repository's ``releases.json`` for the release's current build + and loads ``filename`` from that build's folder; ``pointer_path`` + is not read. ``None`` for a release that keeps the tagged layout. """ country: str @@ -59,6 +64,7 @@ class DatasetSpec: engine_package: str variant: str = DEFAULT_VARIANT pointer_path: str = "latest.json" + release: str | None = None @property def key(self) -> tuple[str, int, str]: @@ -113,13 +119,12 @@ def register(spec: DatasetSpec) -> DatasetSpec: register( DatasetSpec( - # microcosm#823: the UK 2024-25 national line, followed through its - # own pointer, is the default UK load. It stayed off the default - # variant until its first certified cut was promoted (review of #966; - # Max's #823 ruling), and latest-national.json has named - # microcosm-uk-2024-25-national-20261025T091414Z-a6299504 since - # 2026-10-26. resolve("uk") picks the latest default-variant year, so - # it loads this line; the June 2023 artifact stays at ("uk", 2023). + # microcosm#823: the UK 2024-25 national release is the default UK + # load, since its first certified build was made current on + # 2026-10-26. Its builds publish into their own folders, so the loader + # reads its current build from releases.json. resolve("uk") picks the + # latest default-variant year, so it loads this release; the June 2023 + # artifact stays at ("uk", 2023). country="uk", year=2025, variant=DEFAULT_VARIANT, @@ -128,15 +133,16 @@ def register(spec: DatasetSpec) -> DatasetSpec: engine_module="policyengine_uk.data", engine_class="UKSingleYearDataset", engine_package="policyengine-uk", - pointer_path="latest-national.json", + release="microcosm-uk-2024-25-national", ) ) register( DatasetSpec( - # microcosm#762 A18: the dense joint national + local UK build is - # tag-only; no pointer. It carries every constituency and local - # authority at K=15 clones per spine household. + # microcosm#762 A18: the dense joint national + local UK release. It + # carries every constituency and local authority at K=15 clones per + # spine household. Each new dense build becomes current when it is + # published. country="uk", year=2025, variant="dense", @@ -145,12 +151,14 @@ def register(spec: DatasetSpec) -> DatasetSpec: engine_module="policyengine_uk.data", engine_class="UKSingleYearDataset", engine_package="policyengine-uk", + release="microcosm-uk-2024-25-dense", ) ) -# microcosm#898 reserves the local-area line as variant "local", with pointer -# latest-local-k.json and artifact microcosm_uk_2024_25_local_k.h5. Add -# its registry entry only once a certified artifact exists. +# microcosm#898 reserves the local-area release as variant "local", named +# microcosm-uk-2024-25-local-k with artifact +# microcosm_uk_2024_25_local_k.h5. Add its registry entry only once a +# certified build exists. register( DatasetSpec( diff --git a/packages/microcosm-data/src/microcosm/data/release.py b/packages/microcosm-data/src/microcosm/data/release.py index 4545fec77f..288189f2c8 100644 --- a/packages/microcosm-data/src/microcosm/data/release.py +++ b/packages/microcosm-data/src/microcosm/data/release.py @@ -1,5 +1,15 @@ """Publish a release and move its approved repository pointer. +**UK releases no longer publish here.** The UK national, dense and +local-area releases publish each build into its own folder, +``releases///``, through the emitter's ``publish_release`` +call (``microcosm-publish-release-build``, in ``microcosm-build``), and the +repository's ``releases.json`` records which build is current. +:func:`prepare_build_folder_release` checks such a build and lists its files +with their roles; :func:`prepare_release` and :func:`publish_release` refuse +it. Everything below describes the tagged layout the US releases keep until +the stable releases US builds publish under are agreed. + The Hub repo publishes builds under ``releases//``, but nothing identified which release is *current*: a consumer had to list the tree and guess, and because build ids end in a date (``populace-us-2024-9f1260b- @@ -19,9 +29,11 @@ returns the typed pointer, the one-call answer to "which release is current?" for dashboards and scorers. -Approved UK lines coexist through ``latest-.json``. Those schema-1 -pointers add ``line`` and ``revision`` so a line can name an immutable cut tag -without changing the frozen repository-global ``latest.json``. +UK releases were made current through pointer files named +``latest-.json``. Those schema-1 pointers add the fields ``line`` and +``revision``, so each could name an immutable per-build tag without changing +the frozen repository-global ``latest.json``. Nothing writes them any more; +:func:`latest_line_release` still reads them until they are deleted. The EVIDENCE tier (microcosm#506) publishes through the same producer with ``evidence=True``: identical immutable-tag mechanics, but the pointer that @@ -47,11 +59,16 @@ from typing import Any from microcosm.data.contract import ( + BUILD_MANIFEST_FILE_ROLE, + CHECKSUMS_FILE, + CHECKSUMS_FILE_ROLE, EVIDENCE_RELEASE_ID_SEGMENT, NATIONAL_DEFAULT_DATASET_ROLE, + RELEASE_MANIFEST_FILE_ROLE, + RELEASE_ROLES, _uk_line_cut_tag_re, - dataset_role_for_line, line_for_release_id, + publishes_to_build_folder, release_dataset_role, required_release_files, validate_evidence_release_dir, @@ -60,6 +77,9 @@ from microcosm.data.slack import notify_release __all__ = [ + "BUILD_FOLDER_PUBLICATION_COMMAND", + "BuildFolderFile", + "BuildFolderRelease", "LATEST_EVIDENCE_POINTER_PATH", "LATEST_POINTER_PATH", "LATEST_POINTER_SCHEMA_VERSION", @@ -68,6 +88,8 @@ "RELEASE_TIER_EVIDENCE", "LatestPointer", "PreparedRelease", + "build_folder_identity", + "prepare_build_folder_release", "prepare_release", "latest_evidence_pointer_payload", "latest_line_release", @@ -271,12 +293,191 @@ class PreparedRelease: tag: str filenames: list[str] root_artifacts: dict[str, str] - line: str | None pointer_path: str calibration_diagnostics_available: bool contract_warnings: tuple[str, ...] = () +#: Where a build-folder release publishes from: the workspace command that +#: hands each build to the emitter (``microcosm.build.release_publication``). +BUILD_FOLDER_PUBLICATION_COMMAND = "microcosm-publish-release-build" + + +def _refuse_build_folder_release(release_id: str) -> None: + if publishes_to_build_folder(release_id): + raise ValueError( + f"release {release_id!r} publishes each build into its own folder " + "through the emitter, which also records it in releases.json; " + f"publish it with `{BUILD_FOLDER_PUBLICATION_COMMAND}`. This " + "publisher commits, tags and writes latest*.json pointer files." + ) + + +@dataclass(frozen=True) +class BuildFolderFile: + """One file of a build folder: its bare name, role, local path and digest.""" + + name: str + role: str + path: Path + sha256: str + bytes: int + + +@dataclass(frozen=True) +class BuildFolderRelease: + """A checked build of a build-folder release, ready to hand to the emitter. + + ``release_role`` is the release's role in ``releases.json`` + (:data:`~microcosm.data.contract.RELEASE_ROLES`). ``files`` lists the + release manifest, the build manifest, every artifact the release manifest + declares and the checksum ledger when there is one, each once. + ``contract_warnings`` are the release contract's warnings, which never + refuse a build. + """ + + release_dir: Path + repository: str + release: str + build: str + release_role: str + files: tuple[BuildFolderFile, ...] + calibration_diagnostics_available: bool + contract_warnings: tuple[str, ...] = () + + +def build_folder_identity(release_dir: Path | str) -> tuple[str, str, str]: + """``(repository, release, build)`` named by a build folder's release manifest. + + Reads only the manifest, so a published build can be promoted from its + local directory without checking it again; raises ``ValueError`` if the + directory is not a build-folder release or its manifest does not name + the release, the build and one repository. + """ + release_dir = Path(release_dir) + if not publishes_to_build_folder(release_dir.name): + raise ValueError( + f"release {release_dir.name!r} does not publish into build folders; " + "it publishes with tags and latest.json (tools/publish_release.sh)." + ) + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + if not isinstance(manifest, Mapping): + raise ValueError(f"{release_dir}/release_manifest.json is not an object.") + release, build = manifest.get("release"), manifest.get("build") + if release != release_dir.name or not isinstance(build, str) or not build: + raise ValueError( + f"{release_dir}/release_manifest.json does not name release " + f"{release_dir.name!r} and a build." + ) + artifacts = manifest.get("artifacts") + repositories = sorted( + { + str(entry.get("repo_id")) + for entry in (artifacts.values() if isinstance(artifacts, Mapping) else ()) + if isinstance(entry, Mapping) + } + ) + if len(repositories) != 1: + raise ValueError( + f"release {release!r} declares artifacts in more than one repository " + f"({repositories}); a build is published into one repository." + ) + return repositories[0], release, build + + +def prepare_build_folder_release( + release_dir: Path | str, + *, + artifact_root: Path | str | None = None, + repository: str | None = None, +) -> BuildFolderRelease: + """Check a build-folder release's build and list the files it publishes. + + The release contract runs first. Each artifact is read from the release + directory, or else from ``artifact_root`` (the H5 and the calibration + weights live beside the candidate), and must match the SHA-256 its + manifest records. ``repository``, when given, must be the one the + artifacts name. Nothing on the Hub is read or written. + + Raises: + ReleaseContractError: If the build breaks its release contract. + ValueError: If the directory is not a build-folder release, names more + than one repository, or a file's bytes differ from the manifest. + FileNotFoundError: If an artifact is in neither directory. + """ + release_dir = Path(release_dir) + named_repository, release, build = build_folder_identity(release_dir) + contract_warnings = validate_release_dir(release_dir, artifact_root=artifact_root) + for contract_warning in contract_warnings: + warnings.warn(f"release contract: {contract_warning}", stacklevel=2) + if repository is not None and repository != named_repository: + raise ValueError( + f"release {release!r} names {named_repository} in its artifacts, not " + f"{repository}." + ) + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + dataset_role = manifest.get("dataset_role", NATIONAL_DEFAULT_DATASET_ROLE) + release_role = RELEASE_ROLES.get(dataset_role) + if release_role is None: + raise ValueError( + f"release {release!r} declares dataset_role {dataset_role!r}, which " + "has no role in releases.json." + ) + root = Path(artifact_root) if artifact_root is not None else None + sources: list[tuple[str, str, Path, str | None]] = [ + ("release_manifest.json", RELEASE_MANIFEST_FILE_ROLE, release_dir, None), + ("build_manifest.json", BUILD_MANIFEST_FILE_ROLE, release_dir, None), + ] + if (release_dir / CHECKSUMS_FILE).is_file(): + sources.append((CHECKSUMS_FILE, CHECKSUMS_FILE_ROLE, release_dir, None)) + for entry in manifest["artifacts"].values(): + name = entry["path"] + directory = release_dir + if not (release_dir / name).is_file() and root is not None: + directory = root + sources.append((name, entry["role"], directory, entry["sha256"])) + files: list[BuildFolderFile] = [] + for name, role, directory, expected_sha256 in sources: + local = directory / name + if not local.is_file(): + raise FileNotFoundError( + f"{name} of release {release!r} is in neither {release_dir} nor " + f"the artifact root {root}." + ) + digest = _sha256(local) + if expected_sha256 is not None and digest != expected_sha256: + raise ValueError( + f"{name} has sha256 {digest}, but release_manifest.json records " + f"{expected_sha256}." + ) + files.append(BuildFolderFile(name, role, local, digest, local.stat().st_size)) + names = [item.name for item in files] + if len(set(names)) != len(names): + raise ValueError(f"release {release!r} names a file twice: {sorted(names)}.") + diagnostics_declaration = manifest.get("calibration_diagnostics") + diagnostics_available = not ( + isinstance(diagnostics_declaration, Mapping) + and diagnostics_declaration.get("status") == "failed" + ) + if not diagnostics_available: + warnings.warn( + "Publishing a dataset whose calibration diagnostics generation failed: " + f"{diagnostics_declaration.get('error_code')}: " + f"{diagnostics_declaration.get('message')}", + stacklevel=2, + ) + return BuildFolderRelease( + release_dir=release_dir, + repository=named_repository, + release=release, + build=build, + release_role=release_role, + files=tuple(files), + calibration_diagnostics_available=diagnostics_available, + contract_warnings=tuple(contract_warnings), + ) + + def prepare_release( release_dir: Path | str, *, @@ -289,7 +490,6 @@ def prepare_release( update_latest: bool = True, tag_only: bool = False, evidence: bool = False, - line: str | None = None, ) -> PreparedRelease: """Run every local publisher guard and collect the files to upload. @@ -298,8 +498,10 @@ def prepare_release( replays any required source-enrichment compatibility checks. No Hub client is constructed, no Hub activity occurs, and no release alert is sent. Publication must prepare again so preflight cannot authorize stale inputs. + A release that publishes into build folders is refused first. """ release_dir = Path(release_dir) + _refuse_build_folder_release(release_dir.name) if parent_h5 is not None or compatibility_wheels: from microcosm.data.compatibility_recertification import ( RECERTIFICATION_RELEASE_TYPE, @@ -342,29 +544,8 @@ def prepare_release( warnings.warn(f"release contract: {contract_warning}", stacklevel=2) release_id = release_dir.name role = release_dataset_role(release_dir) - if line is not None: - pointer_path = line_pointer_path(line) - if evidence: - raise ValueError("line promotion cannot publish at the evidence tier.") - if not update_latest: - raise ValueError("line promotion requires update_latest=True.") - if tag_only: - raise ValueError("line promotion cannot use tag_only=True.") - expected_line = line_for_release_id(release_id) - if line != expected_line: - raise ValueError( - f"release {release_id!r} belongs to line {expected_line!r}, " - f"not {line!r}." - ) - expected_role = dataset_role_for_line(line) - if role != expected_role: - raise ValueError( - f"release {release_id!r} declares dataset_role {role!r}; line " - f"{line!r} publishes only {expected_role!r} releases." - ) - else: - pointer_path = LATEST_EVIDENCE_POINTER_PATH if evidence else LATEST_POINTER_PATH - if role != NATIONAL_DEFAULT_DATASET_ROLE and update_latest and line is None: + pointer_path = LATEST_EVIDENCE_POINTER_PATH if evidence else LATEST_POINTER_PATH + if role != NATIONAL_DEFAULT_DATASET_ROLE and update_latest: # microcosm#398 defense in depth beyond --no-latest: a non-default # release can never move the global default pointer, even if a # caller asks. @@ -516,13 +697,12 @@ def prepare_release( "match the release id or uniform per-cut artifact revision." ) # The repository-global pointer may only name a release whose immutable tag - # IS the release id. Approved line pointers have their own reader contract - # and may follow a per-cut tag; latest.json still may not. - if update_latest and tag != release_id and line is None: + # IS the release id. + if update_latest and tag != release_id: raise ValueError( f"latest.json may not name per-cut tag {tag!r} for release " - f"{release_id!r}; without an approved line pointer, per-cut tags " - "publish inspect-only. Pass update_latest=False (--no-latest)." + f"{release_id!r}; a tag other than the release id publishes " + "inspect-only. Pass update_latest=False (--no-latest)." ) if root_artifacts and artifact_root is None: raise ValueError( @@ -551,7 +731,6 @@ def prepare_release( tag=tag, filenames=filenames, root_artifacts=root_artifacts, - line=line, pointer_path=pointer_path, calibration_diagnostics_available=calibration_diagnostics_available, contract_warnings=tuple(contract_warnings), @@ -574,10 +753,12 @@ def publish_release( tag_only: bool = False, notify: bool = True, evidence: bool = False, - line: str | None = None, ) -> dict: """Publish a release directory and optionally point ``latest.json`` at it. + A release that publishes into build folders (every UK release) is + refused before any check or Hub call; see the module docstring. + The order is the guarantee: the release contract is validated first (an invalid release never reaches the Hub), then an immutable branch commit is created with every release file and artifact and tagged. A tag-only publish @@ -638,20 +819,17 @@ def publish_release( the certified default or feed pe.py certification. Tag and upload mechanics are otherwise identical. ``update_latest`` then governs the evidence pointer. - line: Promote an approved release line through ``latest-.json``. - Line promotion requires ``update_latest=True``, a matching line - release id, the line's dataset role, and artifact revisions - pinned to the selected tag. A cut published for inspection - earlier (``update_latest=False`` under the same tag) is promoted - by the same call: the publisher recognises the existing tag that - already describes this release, creates no second immutable - revision, and writes only the main commit carrying the pointer. - The same recognition makes a retry after a failure between tag - creation and the pointer commit safe. + + A release published earlier without the pointer (``update_latest=False`` + under the same tag) is pointed to by a later call: the publisher + recognises the existing tag that already describes this release, creates + no second immutable revision, and writes only the main commit carrying + the pointer. The same recognition makes a retry after a failure between + tag creation and the pointer commit safe. Returns: The release's pointer payload (``latest.json`` shape, plus ``tier`` at - the evidence tier or ``line`` and ``revision`` for a line promotion). + the evidence tier). It is uploaded only when ``update_latest=True``. When the release contract warned, the returned payload also lists the warnings under ``contract_warnings``; the uploaded pointer never carries them, and @@ -674,7 +852,6 @@ def publish_release( update_latest=update_latest, tag_only=tag_only, evidence=evidence, - line=line, ) release_id = prepared.release_id @@ -704,17 +881,6 @@ def publish_release( ), ) pointer_label = "evidence release" - elif prepared.line is not None: - payload = line_pointer_payload( - release_id, - line=prepared.line, - revision=prepared.tag, - updated_at=updated_at, - calibration_diagnostics_available=( - prepared.calibration_diagnostics_available - ), - ) - pointer_label = f"{prepared.line} line" else: payload = latest_pointer_payload( release_id, @@ -771,9 +937,6 @@ def publish_release( if evidence: # The alert must never read as a certified release announcement. notify_kwargs["tier"] = RELEASE_TIER_EVIDENCE - if prepared.line is not None: - notify_kwargs["line"] = prepared.line - notify_kwargs["revision"] = prepared.tag notify_release(repo_id, release_id, payload.get("updated_at"), **notify_kwargs) if prepared.contract_warnings: return {**payload, "contract_warnings": list(prepared.contract_warnings)} diff --git a/packages/microcosm-data/src/microcosm/data/releases_record.py b/packages/microcosm-data/src/microcosm/data/releases_record.py new file mode 100644 index 0000000000..48f2d428e2 --- /dev/null +++ b/packages/microcosm-data/src/microcosm/data/releases_record.py @@ -0,0 +1,160 @@ +"""Reading ``releases.json``: which build of each release is current. + +A dataset repository whose releases publish each build into its own folder, +``releases///``, has one ``releases.json`` at its root. The +emitter's release writer is its only writer. It records each release's role +(``national`` or ``local_area``), its current build or ``null``, and every +published build with its ``published_at`` and whether it is withdrawn:: + + { + "schema_version": 1, + "default": "microcosm-uk-2024-25-national", + "releases": { + "microcosm-uk-2024-25-national": { + "role": "national", + "current": "uk-frs-calibration-attempt-20261019T083323Z-6cba5d71", + "builds": { + "uk-frs-calibration-attempt-20261019T083323Z-6cba5d71": { + "published_at": "2026-10-19T09:00:00+00:00", + "withdrawn": false + } + } + } + } + } + +The writer's rules live in ``microcosm_emitter_interface.releases``. This +package also supports Python versions that the interface does not, so it +repeats the rules a reader needs instead of importing them; a build-shard +test runs both on the same records. A reader accepts exactly the records the +writer accepts. +""" + +from __future__ import annotations + +import json +import re +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Final + +__all__ = [ + "MAX_RECORD_BYTES", + "RELEASES_RECORD_PATH", + "BuildEntry", + "ReleaseEntry", + "ReleasesRecord", + "build_folder", + "parse_releases_record", +] + +RELEASES_RECORD_PATH: Final = "releases.json" +_SCHEMA_VERSION: Final = 1 +#: The largest record the writer writes, and so the largest a reader reads. +MAX_RECORD_BYTES: Final = 4 * 1024 * 1024 +_SAFE_IDENTIFIER: Final = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") +_ROLE_IDENTIFIER: Final = re.compile(r"^[a-z][a-z0-9_]{0,63}$") +_RECORD_KEYS: Final = frozenset({"schema_version", "default", "releases"}) +_RELEASE_KEYS: Final = frozenset({"role", "current", "builds"}) +_BUILD_KEYS: Final = frozenset({"published_at", "withdrawn"}) + + +@dataclass(frozen=True) +class BuildEntry: + """One published build: when it was published and whether it is withdrawn.""" + + published_at: str + withdrawn: bool + + +@dataclass(frozen=True) +class ReleaseEntry: + """One release: its role, its current build or ``None``, and its builds.""" + + role: str + current: str | None + builds: Mapping[str, BuildEntry] + + +@dataclass(frozen=True) +class ReleasesRecord: + """A ``releases.json`` the release writer would accept.""" + + default: str | None + releases: Mapping[str, ReleaseEntry] + + +def build_folder(release: str, build: str) -> str: + """A build's folder in the repository, ``releases//``.""" + return f"releases/{release}/{build}" + + +def _safe(value: object) -> bool: + return isinstance(value, str) and _SAFE_IDENTIFIER.fullmatch(value) is not None + + +def parse_releases_record(content: bytes) -> ReleasesRecord: + """Parse ``releases.json``; raise ``ValueError`` naming the first broken rule. + + The rules are the writer's: at most ``MAX_RECORD_BYTES``; exactly the + documented keys at every level; the integer ``schema_version`` 1; release + and build names the emitter accepts for a folder; role names; a non-empty + ``published_at`` and a boolean ``withdrawn`` on every build; a ``default`` + that is ``null`` or a listed release; and a ``current`` that is ``null`` + or a listed build that is not withdrawn. + """ + if len(content) > MAX_RECORD_BYTES: + raise ValueError(f"it is larger than {MAX_RECORD_BYTES} bytes") + try: + document = json.loads(content) + except (ValueError, RecursionError): + raise ValueError("it is not a readable JSON document") from None + if not isinstance(document, dict) or set(document) != _RECORD_KEYS: + raise ValueError(f"it must have exactly the keys {sorted(_RECORD_KEYS)}") + version = document["schema_version"] + # True and 1.0 equal 1 in Python; only the integer is the version. + if type(version) is not int or version != _SCHEMA_VERSION: + raise ValueError(f"its schema_version must be {_SCHEMA_VERSION}") + releases_document = document["releases"] + if not isinstance(releases_document, dict): + raise ValueError("its releases must be an object") + releases: dict[str, ReleaseEntry] = {} + for release, entry in releases_document.items(): + if not _safe(release): + raise ValueError("a release name is not a safe identifier") + if not isinstance(entry, dict) or set(entry) != _RELEASE_KEYS: + raise ValueError(f"release {release} must have {sorted(_RELEASE_KEYS)}") + role = entry["role"] + if not isinstance(role, str) or _ROLE_IDENTIFIER.fullmatch(role) is None: + raise ValueError(f"release {release} has an invalid role") + current = entry["current"] + if current is not None and not isinstance(current, str): + raise ValueError(f"release {release} current must be a build or null") + if not isinstance(entry["builds"], dict): + raise ValueError(f"release {release} builds must be an object") + builds: dict[str, BuildEntry] = {} + for build, build_entry in entry["builds"].items(): + if not _safe(build): + raise ValueError("a build name is not a safe identifier") + if ( + not isinstance(build_entry, dict) + or set(build_entry) != _BUILD_KEYS + or not isinstance(build_entry["published_at"], str) + or not build_entry["published_at"] + or not isinstance(build_entry["withdrawn"], bool) + ): + raise ValueError(f"build {build} of {release} is malformed") + builds[build] = BuildEntry( + build_entry["published_at"], build_entry["withdrawn"] + ) + if current is not None and current not in builds: + raise ValueError(f"current build {current} of {release} is not listed") + if current is not None and builds[current].withdrawn: + raise ValueError(f"current build {current} of {release} is withdrawn") + releases[release] = ReleaseEntry(role, current, builds) + default = document["default"] + if default is not None and not isinstance(default, str): + raise ValueError("its default must be a release name or null") + if default is not None and default not in releases: + raise ValueError(f"its default {default} is not listed") + return ReleasesRecord(default=default, releases=releases) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_contract.py index 652a74135f..4ef6158b82 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_contract.py @@ -2540,7 +2540,7 @@ def test_release_artifact_role_keeps_the_general_roles( assert contract.release_artifact_role(key, kind) == role -def _rewrite_json(path: Path, mutate) -> None: +def _rewrite_document(path: Path, mutate) -> None: document = json.loads(path.read_text()) mutate(document) path.write_text(json.dumps(document)) @@ -2581,7 +2581,7 @@ def tagged(release: dict) -> None: "cut_tag": f"{UK_NATIONAL_RELEASE_ID}-20260920T120000Z-deadbeef", } - _rewrite_json(directory / "release_manifest.json", tagged) + _rewrite_document(directory / "release_manifest.json", tagged) assert "'build' must be the build's name" in _uk_national_failures(directory) @@ -2591,7 +2591,7 @@ def test_uk_national_build_folder_refuses_the_retired_build_fields( tmp_path: Path, field: str ) -> None: directory = _write_uk_national_release_dir(tmp_path) - _rewrite_json( + _rewrite_document( directory / "build_manifest.json", lambda build: build.update({field: UK_NATIONAL_RELEASE_ID}), ) @@ -2604,7 +2604,7 @@ def test_uk_national_build_folder_release_must_be_the_directory( tmp_path: Path, manifest: str ) -> None: directory = _write_uk_national_release_dir(tmp_path) - _rewrite_json( + _rewrite_document( directory / manifest, lambda document: document.update(release="microcosm-uk-2024-25-dense"), ) @@ -2620,7 +2620,7 @@ def test_uk_national_build_folder_build_must_be_a_safe_name( ) -> None: directory = _write_uk_national_release_dir(tmp_path) for manifest in ("build_manifest.json", "release_manifest.json"): - _rewrite_json( + _rewrite_document( directory / manifest, lambda document: document.update(build=build) ) @@ -2631,7 +2631,7 @@ def test_uk_national_build_folder_manifests_must_name_the_same_build( tmp_path: Path, ) -> None: directory = _write_uk_national_release_dir(tmp_path) - _rewrite_json( + _rewrite_document( directory / "build_manifest.json", lambda build: build.update( build="uk-frs-calibration-attempt-20260101T000000Z-00000000" @@ -2650,7 +2650,7 @@ def test_uk_national_build_folder_records_build_details_at_the_top_level( tmp_path: Path, field: str ) -> None: directory = _write_uk_national_release_dir(tmp_path) - _rewrite_json( + _rewrite_document( directory / "release_manifest.json", lambda release: release.pop(field) ) @@ -2665,7 +2665,7 @@ def test_uk_national_build_folder_refuses_an_artifact_revision( def pin(release: dict) -> None: release["artifacts"]["calibration_diagnostics"]["revision"] = "main" - _rewrite_json(directory / "release_manifest.json", pin) + _rewrite_document(directory / "release_manifest.json", pin) assert "artifact 'calibration_diagnostics' pins revision 'main'" in ( _uk_national_failures(directory) @@ -2691,7 +2691,7 @@ def set_role(release: dict) -> None: else: artifact["role"] = role - _rewrite_json(directory / "release_manifest.json", set_role) + _rewrite_document(directory / "release_manifest.json", set_role) assert message in _uk_national_failures(directory) @@ -2707,7 +2707,7 @@ def test_uk_national_build_folder_artifact_paths_are_bare_file_names( def move(release: dict) -> None: release["artifacts"]["release_certification"]["path"] = path - _rewrite_json(directory / "release_manifest.json", move) + _rewrite_document(directory / "release_manifest.json", move) assert "artifact 'release_certification' path" in _uk_national_failures(directory) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py index 5ebae9d563..c7bb873f2e 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py @@ -319,7 +319,9 @@ def test_uk_local_area_bundle_refuses_the_tagged_layout(tmp_path: Path) -> None: build_manifest_path.write_text(json.dumps(build_manifest)) failures = _failures(release_dir) - assert any("build_manifest.json carries 'build_id'" in line for line in failures) + assert any( + "build_manifest.json carries 'build_id'" in failure for failure in failures + ) def test_valid_local_area_bundle_passes(tmp_path: Path) -> None: diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release.py b/packages/microcosm-data/tests/engine_free/shared/test_release.py index be1f036d8b..da9bb54935 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release.py @@ -211,8 +211,9 @@ def test_the_tagged_publisher_refuses_every_build_folder_release( assert uk_hub.uploads == [] -def test_the_tagged_publisher_offers_no_line_promotion() -> None: - """Only UK releases had promotion lines, and they no longer publish here.""" +def test_the_tagged_publisher_has_no_pointer_promotion_option() -> None: + """Only UK releases were made current through latest-.json pointer + files, and they no longer publish here.""" import inspect assert "line" not in inspect.signature(publish_release).parameters diff --git a/tools/assemble_uk_dense_release_dir.py b/tools/assemble_uk_dense_release_dir.py index b8b52fb098..8909419c48 100644 --- a/tools/assemble_uk_dense_release_dir.py +++ b/tools/assemble_uk_dense_release_dir.py @@ -1,16 +1,20 @@ """Assemble the dense joint UK line's release directory (microcosm#762 A18). Mirrors ``assemble_uk_release_dir.py`` for the ``microcosm-uk-2024-25-dense`` -line: verify the complete hash join over a finished ``--release-candidate`` -run of ``build_uk_rowwise_candidate.py`` (its manifest, signed gate report, -full gate report and diagnostics, plus the spine, ladder and Ledger artifact -it stood on), run the release-candidate pre-flight, mint the per-cut tag from -the run's attempt id, stage the bundle under the non-default local-area role -with UK evidence, validate it with the release contract, and only then rename -it into place. The candidate H5 is cloned beside itself under the published -filename; nothing is uploaded — the summary prints the exact ``publish_cli`` -command for the human step (``--no-latest --tag-only``, per-cut tag, private -repo). +release: verify the complete hash join over a finished +``--release-candidate`` run of ``build_uk_rowwise_candidate.py`` (its +manifest, its signed ``local_gate_report`` and ``full_gate_report`` outputs +and its diagnostics, plus the spine, ladder and Ledger artifact it stood +on), run the release-candidate +pre-flight, stage the bundle under the non-default local-area role with UK +evidence, validate it with the release contract, and only then rename it +into place. The candidate H5 is cloned beside itself under the published +filename; nothing is uploaded. The release publishes each build into its own +folder through the emitter: the build is the run's attempt ID, both manifests +name the release and the build, and nothing is tagged. The summary prints the +exact ``microcosm-publish-release-build`` command for the human step, which +makes the build the release's current build when it is published (private +repository). The rotated holdout and the incumbent comparison are opt-in diagnostics (microcosm#1301). The manifest's reviewed limitations say what the release @@ -55,6 +59,7 @@ from microcosm.data.contract import ( _UK_DENSE_SIGNED_EXCLUSION_GATES, _check_uk_incumbent_surface_evaluation, + release_artifact_role, validate_release_dir, ) from microcosm.diagnostics import ( @@ -70,7 +75,6 @@ # pins the two. _DATASET_KEY = "microcosm_uk_2024_25_dense" _DATASET_FILENAME = f"{_DATASET_KEY}.h5" -_ATTEMPT_SUFFIX = re.compile(r"[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}") _RUNTIME_PACKAGES = ("policyengine-core", "policyengine-uk", "microcosm-data") _GIT_COMMIT = re.compile(r"^[0-9a-f]{40}$") #: The gates whose reviewed exclusions the manifest names, each with its @@ -188,24 +192,6 @@ def _preflight_module(): return module -def _cut_tag(attempt_id: str, override: str | None) -> str: - prefix = UK_DENSE_RELEASE_ID + "-" - if override is not None: - if not override.startswith(prefix) or not _ATTEMPT_SUFFIX.fullmatch( - override[len(prefix) :] - ): - raise SystemExit( - f"error: --cut-tag must be {prefix}-" - ) - return override - match = re.search(r"([0-9]{8}T[0-9]{6}Z-[0-9a-f]{8})$", attempt_id) - if match is None: - raise SystemExit( - "error: the run's build id must end with -" - ) - return f"{UK_DENSE_RELEASE_ID}-{match.group(1)}" - - def _holdout_limitation(fit: Mapping[str, object]) -> dict[str, object]: """What the release claims about fit on rows the solve never saw.""" @@ -743,7 +729,6 @@ def output_path(key: str) -> Path: raise SystemExit( "error: manifest.identity.code.git_commit must be a 40-hex commit" ) - cut_tag = _cut_tag(attempt_id, args.cut_tag) parameters = _mapping(manifest.get("parameters"), "manifest.parameters") if parameters.get("release_candidate") is not True: raise SystemExit("error: the run was not a --release-candidate run") @@ -776,7 +761,6 @@ def output_path(key: str) -> Path: incumbent=incumbent, measured=measured, attempt_id=attempt_id, - cut_tag=cut_tag, runtime=runtime, code_pin=code_pin, report_path=report_path, @@ -812,7 +796,6 @@ def _stage_and_finalize( incumbent: _IncumbentAttachment | None, measured: Mapping[str, str], attempt_id: str, - cut_tag: str, runtime: Mapping[str, str], code_pin: str, report_path: Path, @@ -973,8 +956,11 @@ def _stage_and_finalize( "git_dirty" ) git_dirty = recorded_dirty if isinstance(recorded_dirty, bool) else None + # The build is the calibration attempt: both manifests name it, and the + # release, so the emitter can publish it into its own folder. build_manifest = { - "build_id": UK_DENSE_RELEASE_ID, + "release": UK_DENSE_RELEASE_ID, + "build": attempt_id, "build_sha": code_pin[:7], "code": { "repository": "PolicyEngine/microcosm", @@ -1001,20 +987,18 @@ def _stage_and_finalize( for gate_id, entry in gates.items() if isinstance(entry, Mapping) }, - "attempt_id": attempt_id, - "cut_tag": cut_tag, "created_at": created_at, "staging": dict(staging_delivery), } _write_json(release_dir / "build_manifest.json", build_manifest) - def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: + def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: return { "kind": kind, "path": path, "repo_id": _REPO_ID, - "revision": cut_tag, "sha256": sha256, + "role": release_artifact_role(key, kind), } evidence_files = ( @@ -1051,19 +1035,16 @@ def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: "is_default": False, "default_datasets": {}, "namespace": _NAMESPACE, - "build": { - "build_id": UK_DENSE_RELEASE_ID, - "built_at": created_at, - "built_with_core_package": { - "name": "policyengine-core", - "version": runtime["policyengine-core"], - }, - "built_with_model_package": { - "name": "policyengine-uk", - "version": runtime["policyengine-uk"], - }, - "attempt_id": attempt_id, - "cut_tag": cut_tag, + "release": UK_DENSE_RELEASE_ID, + "build": attempt_id, + "built_at": created_at, + "built_with_core_package": { + "name": "policyengine-core", + "version": runtime["policyengine-core"], + }, + "built_with_model_package": { + "name": "policyengine-uk", + "version": runtime["policyengine-uk"], }, "compatible_core_packages": [ { @@ -1076,18 +1057,25 @@ def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: ], "artifacts": { _DATASET_KEY: { - **artifact("microdata", _DATASET_FILENAME, measured["candidate"]), + **artifact( + _DATASET_KEY, "microdata", _DATASET_FILENAME, measured["candidate"] + ), "spi_public_use_tape_dependent": bool(spi_marker["dependent"]), }, **{ - Path(name).stem: artifact("diagnostics", name, evidence_sha[name]) + Path(name).stem: artifact( + Path(name).stem, "diagnostics", name, evidence_sha[name] + ) for name in evidence_files if name != "build_manifest.json" }, }, "reviewed_limitations": gate_summary["reviewed_limitations"], "area_support": _area_support_block(solve), - "description": f"UK dense joint national + local line assembled from attempt {attempt_id} at immutable cut {cut_tag}; inspect lane, never the default slot.", + "description": ( + "UK dense joint national + local release build assembled from " + f"attempt {attempt_id}; never the default release." + ), "publisher_labels": { "obr": "Office for Budget Responsibility", "hmrc": "HM Revenue and Customs", @@ -1112,28 +1100,25 @@ def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: for contract_warning in contract_warnings: print(f"warning: {contract_warning}", file=sys.stderr) release_dir.rename(destination) + # Each new dense build becomes current when it is published. publish_command = shlex.join( [ "uv", "run", - "python", - "-m", - "microcosm.data.publish_cli", + "microcosm-publish-release-build", str(destination), "--repo-id", _REPO_ID, "--artifact-root", str(artifact_root), - "--no-latest", - "--tag-only", - "--tag-name", - cut_tag, + "--make-current", ] ) return { "release_id": UK_DENSE_RELEASE_ID, + "release": UK_DENSE_RELEASE_ID, + "build": attempt_id, "release_dir": str(destination), - "cut_tag": cut_tag, "dataset": { "path": str(artifact_root / _DATASET_FILENAME), "sha256": measured["candidate"], @@ -1170,7 +1155,6 @@ def _parse_args(argv: list[str] | None) -> argparse.Namespace: type=Path, help="where the published H5 is cloned (default: beside the candidate)", ) - parser.add_argument("--cut-tag") parser.add_argument( "--allow-missing-staging", action="store_true", diff --git a/tools/assemble_uk_release_dir.py b/tools/assemble_uk_release_dir.py index decc753c08..d4ab612d2c 100644 --- a/tools/assemble_uk_release_dir.py +++ b/tools/assemble_uk_release_dir.py @@ -1,9 +1,16 @@ -"""Assemble a certified UK national candidate into a publishable release. +"""Assemble a certified UK national candidate into a publishable release build. This derivative packaging step closes the certification/build-record identity join, mints the calibration weight bundle, writes the two release manifests, copies the signed evidence byte-for-byte, and validates the finished release -directory before printing the inspect-lane publication command. +directory before printing its publication and promotion commands. + +The national release publishes each build into its own folder, +``releases/microcosm-uk-2024-25-national//``, through the emitter. +The build is the calibration attempt ID, and both manifests name the release +and the build; nothing is tagged. The publication command lists the build +without making it current; the promotion command, run after review, makes +it the release's current build. """ from __future__ import annotations @@ -38,10 +45,8 @@ uk_spi_public_use_tape_marker_for_stage_names, ) from microcosm.build.uk_runtime.weight_year import uk_weights_are_at_dataset_year -from microcosm.data.contract import validate_release_dir +from microcosm.data.contract import release_artifact_role, validate_release_dir -_ATTEMPT_PREFIX = "uk-frs-calibration-attempt-" -_ATTEMPT_SUFFIX = re.compile(r"(?P\d{8}T\d{6}Z)-(?P[0-9a-f]{8})") _GIT_COMMIT = re.compile(r"[0-9a-f]{40}") _REPO_ID = "policyengine/populace-uk-private" _DATASET_KEY = "microcosm_uk_2024_25" @@ -256,7 +261,6 @@ def _assemble(args: argparse.Namespace) -> dict[str, object]: measured["spine H5"], signed_input_posture.get("sha256"), ) - cut_tag = _cut_tag(attempt_id, args.cut_tag) spi_marker = _spi_public_use_tape_marker(build_block) runtime = _runtime_versions(build_block, dict(args.runtime_version)) code_pin = _diagnostics_code_pin(diagnostics) @@ -348,7 +352,6 @@ def _assemble(args: argparse.Namespace) -> dict[str, object]: initial_household_weight=initial_household_weight, household_weight_year=household_weight_year, measured=measured, - cut_tag=cut_tag, attempt_id=attempt_id, runtime=runtime, code_pin=code_pin, @@ -378,7 +381,6 @@ def _stage_and_finalize( initial_household_weight: np.ndarray, household_weight_year: Mapping[str, object], measured: Mapping[str, str], - cut_tag: str, attempt_id: str, runtime: Mapping[str, str], code_pin: str, @@ -401,8 +403,11 @@ def _stage_and_finalize( created_at = datetime.now(UTC).isoformat() release_dir = staging_parent / UK_NATIONAL_RELEASE_ID release_dir.mkdir(parents=True) + # The build is the calibration attempt: both manifests name it, and the + # release, so the emitter can publish it into its own folder. build_manifest = { - "build_id": UK_NATIONAL_RELEASE_ID, + "release": UK_NATIONAL_RELEASE_ID, + "build": attempt_id, "code": { "repository": "PolicyEngine/microcosm", "git_commit": code_pin, @@ -438,8 +443,6 @@ def _stage_and_finalize( "calibration_seam": seam_part.get("statuses"), "release_cut": release_cut_part.get("statuses"), }, - "attempt_id": attempt_id, - "cut_tag": cut_tag, "created_at": created_at, "staging": dict(staging_delivery), } @@ -467,36 +470,33 @@ def _stage_and_finalize( ), } - def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: + def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: return { "kind": kind, "path": path, "repo_id": _REPO_ID, - "revision": cut_tag, "sha256": sha256, + "role": release_artifact_role(key, kind), } release_manifest = { "schema_version": 1, + "release": UK_NATIONAL_RELEASE_ID, + "build": attempt_id, + "built_at": created_at, + "built_with_core_package": { + "name": "policyengine-core", + "version": runtime["policyengine-core"], + }, + "built_with_model_package": { + "name": "policyengine-uk", + "version": runtime["policyengine-uk"], + }, "data_package": { "name": "microcosm-data", "version": runtime["microcosm-data"], }, "default_datasets": {"national": _DATASET_KEY}, - "build": { - "build_id": UK_NATIONAL_RELEASE_ID, - "built_at": created_at, - "built_with_core_package": { - "name": "policyengine-core", - "version": runtime["policyengine-core"], - }, - "built_with_model_package": { - "name": "policyengine-uk", - "version": runtime["policyengine-uk"], - }, - "attempt_id": attempt_id, - "cut_tag": cut_tag, - }, "compatible_core_packages": [ { "name": "policyengine-core", @@ -513,14 +513,19 @@ def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: # The microdata's own entry says whether it rests on the SPI # Public Use Tape; licensed_data carries the tape's conditions. _DATASET_KEY: { - **artifact("microdata", _DATASET_FILENAME, measured["candidate"]), + **artifact( + _DATASET_KEY, "microdata", _DATASET_FILENAME, measured["candidate"] + ), "spi_public_use_tape_dependent": bool(spi_marker["dependent"]), }, f"{_DATASET_KEY}_calibration": artifact( - "calibration", calibration_filename, calibration_sha + f"{_DATASET_KEY}_calibration", + "calibration", + calibration_filename, + calibration_sha, ), **{ - key: artifact("diagnostics", filename, measured[name]) + key: artifact(key, "diagnostics", filename, measured[name]) for key, (_source, filename), name in ( ( "calibration_diagnostics", @@ -556,8 +561,8 @@ def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: }, }, "description": ( - "UK national calibration pipeline release assembled from attempt " - f"{attempt_id} at immutable cut {cut_tag}." + "UK national calibration pipeline release build assembled from " + f"attempt {attempt_id}." ), "publisher_labels": _uk_publisher_labels(), "licensed_data": {UK_SPI_PUBLIC_USE_TAPE_KEY: dict(spi_marker)}, @@ -590,45 +595,36 @@ def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: npz_destination.unlink(missing_ok=True) raise + # Publication lists the build without making it current; the reviewed + # promotion is the second command. publish_command = shlex.join( [ "uv", "run", - "python", - "-m", - "microcosm.data.publish_cli", + "microcosm-publish-release-build", str(destination), "--repo-id", _REPO_ID, "--artifact-root", str(args.candidate_h5.parent), - "--no-latest", - "--tag-name", - cut_tag, ] ) promote_command = shlex.join( [ "uv", "run", - "python", - "-m", - "microcosm.data.publish_cli", + "microcosm-publish-release-build", str(destination), "--repo-id", _REPO_ID, - "--artifact-root", - str(args.candidate_h5.parent), - "--promote-line", - "national", - "--tag-name", - cut_tag, + "--promote", ] ) return { "release_id": UK_NATIONAL_RELEASE_ID, + "release": UK_NATIONAL_RELEASE_ID, + "build": attempt_id, "release_dir": str(destination), - "cut_tag": cut_tag, "dataset": { "path": str(args.candidate_h5), "sha256": measured["candidate"], @@ -662,7 +658,6 @@ def _parse_args(argv: list[str] | None) -> argparse.Namespace: parser.add_argument("--release-cut-gate-json", type=Path) parser.add_argument("--score-receipt", required=True, type=Path) parser.add_argument("--out-dir", type=Path, default=Path("releases")) - parser.add_argument("--cut-tag") parser.add_argument( "--runtime-version", action="append", @@ -774,30 +769,6 @@ def _diagnostics_code_pin(diagnostics: Mapping[str, object]) -> str: return code_pin -def _cut_tag(attempt_id: str, override: str | None) -> str: - prefix = UK_NATIONAL_RELEASE_ID + "-" - if override is not None: - # The override may re-tag a cut but never leave the grammar the - # contract validates: prefix plus an attempt-shaped suffix. - if not override.startswith(prefix) or not _ATTEMPT_SUFFIX.fullmatch( - override[len(prefix) :] - ): - raise SystemExit( - f"error: --cut-tag must be {prefix}-" - ) - return override - if not attempt_id.startswith(_ATTEMPT_PREFIX): - raise SystemExit( - f"error: build_record.build_id must start with {_ATTEMPT_PREFIX!r}" - ) - suffix = attempt_id.removeprefix(_ATTEMPT_PREFIX) - if not _ATTEMPT_SUFFIX.fullmatch(suffix): - raise SystemExit( - "error: build_record.build_id must end with -" - ) - return f"{UK_NATIONAL_RELEASE_ID}-{suffix}" - - def _load_json(path: Path, *, label: str) -> Mapping[str, object]: return _load_json_bytes(path.read_bytes(), label=label) diff --git a/tools/publish_release.sh b/tools/publish_release.sh index e760f2c440..665c6e4881 100755 --- a/tools/publish_release.sh +++ b/tools/publish_release.sh @@ -1,6 +1,11 @@ #!/usr/bin/env bash # -# Publish a Microcosm release and fire its Slack alert, in one tracked path. +# Publish a Microcosm release that keeps tags and latest.json (every US +# release) and fire its Slack alert, in one tracked path. +# +# UK releases publish each build into its own folder through the emitter +# with `microcosm-publish-release-build` instead; `microcosm-publish-release` +# refuses them, and they send no Slack alert. # # Thin wrapper around `microcosm-publish-release` so that every ship goes # through the same command and the release alert is guaranteed to be wired. @@ -14,7 +19,7 @@ # # One-time setup on the build machine (see README "Releasing & alerts"): # cp tools/release.env.example tools/release.env # then fill in the URLs -# or just export SLACK_WEBHOOK_POPULACE_US / _UK in your shell. +# or just export SLACK_WEBHOOK_POPULACE_US in your shell. set -euo pipefail @@ -26,8 +31,8 @@ if [[ -f "$ENV_FILE" ]]; then set +a fi -if [[ -z "${SLACK_WEBHOOK_POPULACE_US:-}" && -z "${SLACK_WEBHOOK_POPULACE_UK:-}" ]]; then - echo "warning: no SLACK_WEBHOOK_POPULACE_US/_UK set — this release will" >&2 +if [[ -z "${SLACK_WEBHOOK_POPULACE_US:-}" ]]; then + echo "warning: no SLACK_WEBHOOK_POPULACE_US set — this release will" >&2 echo " publish WITHOUT a Slack alert. Set them in your shell or in" >&2 echo " $ENV_FILE (see README 'Releasing & alerts')." >&2 fi diff --git a/tools/release.env.example b/tools/release.env.example index 02c5e5b1af..072843a849 100644 --- a/tools/release.env.example +++ b/tools/release.env.example @@ -1,16 +1,16 @@ # Release alert configuration for tools/publish_release.sh. # # Copy this file to tools/release.env (gitignored) on the build machine and -# paste the Slack *incoming webhook* URLs for #populace-us and #populace-uk. -# Once set, every `tools/publish_release.sh …` (and any direct -# `microcosm-publish-release`) posts a release alert to the matching channel. +# paste the Slack *incoming webhook* URL for #populace-us. Once set, every +# `tools/publish_release.sh …` (and any direct `microcosm-publish-release`) +# posts a release alert there. UK releases publish into build folders through +# the emitter and send no alert from here. # # cp tools/release.env.example tools/release.env # -# Leave a line blank to skip alerts for that country. +# Leave it blank to skip the alerts. export SLACK_WEBHOOK_POPULACE_US= -export SLACK_WEBHOOK_POPULACE_UK= # Canonical UK exact-k terminal reports are authenticated with a stable # 32-byte release key encoded as base64. Generate and store this once on the From a90363de71be41034deed8e23d031aad4c1dad43 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:43:34 +0400 Subject: [PATCH 03/26] Test that the proposed US releases are recorded but not used The stable releases proposed for US builds are not agreed with the US data builder, so the contract should record them, with their `releases.json` roles, in one place while no US release publishes into build folders. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/shared/test_contract.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_contract.py index 4ef6158b82..6c10ad4262 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_contract.py @@ -2518,6 +2518,22 @@ def test_publishes_to_build_folder_names_only_the_uk_releases( assert contract.publishes_to_build_folder(release_id) is publishes +def test_the_proposed_us_releases_are_recorded_but_not_used() -> None: + """The US stable releases are proposed, not agreed with the US data + builder: the contract records them with their roles in one place, and no + US release publishes into build folders until they are agreed.""" + assert contract.PROPOSED_US_RELEASES == { + "populace-us-2024-national": "national", + "populace-us-2024-acs-local": "local_area", + } + assert set(contract.PROPOSED_US_RELEASES.values()) <= set( + contract.RELEASE_ROLES.values() + ) + for release in contract.PROPOSED_US_RELEASES: + assert release.startswith("populace-us-") + assert contract.publishes_to_build_folder(release) is False + + def test_release_roles_record_national_and_local_area() -> None: assert contract.RELEASE_ROLES == { "national_default": "national", From 06b25fe1473eed6f59ef8c3bed85ed6324e9aba9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:44:00 +0400 Subject: [PATCH 04/26] Record the proposed US releases without using them `PROPOSED_US_RELEASES` names `populace-us-2024-national` (role `national`, the default) and `populace-us-2024-acs-local` (role `local_area`), the stable releases proposed for US builds. They are not agreed with the US data builder, so `publishes_to_build_folder` names no US release and US releases keep tags and `latest.json`. Co-Authored-By: Claude Opus 5.5 --- ...04-h2c-release-builds-in-folders.changed.md | 2 +- .../src/microcosm/data/contract.py | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/changelog.d/1504-h2c-release-builds-in-folders.changed.md b/changelog.d/1504-h2c-release-builds-in-folders.changed.md index c39a679aaf..14d0a0edbe 100644 --- a/changelog.d/1504-h2c-release-builds-in-folders.changed.md +++ b/changelog.d/1504-h2c-release-builds-in-folders.changed.md @@ -1 +1 @@ -UK release builds publish into their own folders through the emitter. The UK national, dense and local-area releases (`microcosm.data.contract.publishes_to_build_folder`) hand each build to the separately installed `microcosm-emitter` with the interface's `publish_release` call, and its release writer puts the build in `releases///` and records it in the repository's `releases.json` in one commit; Microcosm no longer commits, tags or writes `latest*.json` pointer files for them. The new `microcosm-publish-release-build` command (`microcosm.build.release_publication`, in `microcosm-build`) checks the build with the release contract, hands every file over with its role and SHA-256, publishes with or without `--make-current`, makes a published build current with `--promote`, and succeeds only when the emitter's receipt is `published` and, when current was asked for, names the build as `current`. The build is the calibration attempt ID: both manifests name `release` and `build` as strings, the release manifest records `built_at`, `built_with_model_package` and `built_with_core_package` at its top level and a `role` on each artifact (`dataset`, `calibration_weights`, `calibration_diagnostics`, otherwise the artifact's key), and no artifact pins a `revision`. The fields `build_id`, `attempt_id` and `cut_tag` are gone from UK manifests, and the assemblers' `--cut-tag` option with them. Each release's role in `releases.json` is `national` or `local_area`, from its `dataset_role`. The UK national assembler prints a publication command and a separate promotion command; the dense assembler's command makes each new dense build current. The release contract checks this layout for UK releases and refuses the tagged one. `microcosm.data.load` reads a UK release's current build from `releases.json` (or the listed build `build=` names, a withdrawn one with a warning), then its manifest and dataset from the build's folder; `unverified_root=True` is refused for such a release, and the loader no longer follows `latest-.json` pointers. `microcosm-publish-release` and `tools/publish_release.sh` keep publishing US releases with tags and `latest.json`, refuse UK releases, and lose `--promote-line`. UK publications send no Slack alert. +UK release builds publish into their own folders through the emitter. The UK national, dense and local-area releases (`microcosm.data.contract.publishes_to_build_folder`) hand each build to the separately installed `microcosm-emitter` with the interface's `publish_release` call, and its release writer puts the build in `releases///` and records it in the repository's `releases.json` in one commit; Microcosm no longer commits, tags or writes `latest*.json` pointer files for them. The new `microcosm-publish-release-build` command (`microcosm.build.release_publication`, in `microcosm-build`) checks the build with the release contract, hands every file over with its role and SHA-256, publishes with or without `--make-current`, makes a published build current with `--promote`, and succeeds only when the emitter's receipt is `published` and, when current was asked for, names the build as `current`. The build is the calibration attempt ID: both manifests name `release` and `build` as strings, the release manifest records `built_at`, `built_with_model_package` and `built_with_core_package` at its top level and a `role` on each artifact (`dataset`, `calibration_weights`, `calibration_diagnostics`, otherwise the artifact's key), and no artifact pins a `revision`. The fields `build_id`, `attempt_id` and `cut_tag` are gone from UK manifests, and the assemblers' `--cut-tag` option with them. Each release's role in `releases.json` is `national` or `local_area`, from its `dataset_role`. The UK national assembler prints a publication command and a separate promotion command; the dense assembler's command makes each new dense build current. The release contract checks this layout for UK releases and refuses the tagged one. `microcosm.data.load` reads a UK release's current build from `releases.json` (or the listed build `build=` names, a withdrawn one with a warning), then its manifest and dataset from the build's folder; `unverified_root=True` is refused for such a release, and the loader no longer follows `latest-.json` pointers. `microcosm-publish-release` and `tools/publish_release.sh` keep publishing US releases with tags and `latest.json`, refuse UK releases, and lose `--promote-line`. UK publications send no Slack alert. The stable releases proposed for US builds, `populace-us-2024-national` (`national`, the default) and `populace-us-2024-acs-local` (`local_area`), are recorded in `microcosm.data.contract.PROPOSED_US_RELEASES` but not used until they are agreed with the US data builder. diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index cb0ccc0db9..3c4e4a1a73 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -199,14 +199,28 @@ def compatibility_claim_declarer_error(declared_by: object) -> str | None: _ROLE_IDENTIFIER_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") +#: The stable releases proposed for US builds, with each one's role in +#: ``releases.json``: the national release (the repository's default) and the +#: ACS local-area release. They are proposals the US data builder has not +#: agreed yet, so nothing reads them: :func:`publishes_to_build_folder` names +#: no US release, and every US release keeps tags and ``latest.json``. Once +#: they are agreed, that function names them, the US builders write the +#: build-folder manifests under them and the registry's US entries name them. +PROPOSED_US_RELEASES: Mapping[str, str] = { + "populace-us-2024-national": "national", + "populace-us-2024-acs-local": "local_area", +} + + def publishes_to_build_folder(release_id: str) -> bool: """Whether builds of ``release_id`` publish into their own build folders. This is the one place that says which releases use the build-folder layout: the UK national, dense and local-area releases. Every US release keeps the tagged layout and ``latest.json`` until the stable releases US - builds publish under are agreed with the US data builder; this function - then names them too, and their builders write the same manifests. + builds publish under (:data:`PROPOSED_US_RELEASES`) are agreed with the + US data builder; this function then names them too, and their builders + write the same manifests. """ return ( release_id in {_UK_NATIONAL_RELEASE_ID, _UK_DENSE_RELEASE_ID} From 549544dab59f2b0369d29d1d2183fcea70cf2016 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:47:06 +0400 Subject: [PATCH 05/26] Keep the release role mappings immutable and export the new contract names `RELEASE_ROLES` and `PROPOSED_US_RELEASES` are read-only mappings, as the shared constants guidance asks, and the contract's `__all__` lists the build-folder names other modules import. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/data/contract.py | 33 ++++++++++++++----- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index 3c4e4a1a73..6ab39525b3 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -43,6 +43,7 @@ from collections.abc import Mapping from datetime import date from pathlib import Path +from types import MappingProxyType from packaging.specifiers import InvalidSpecifier, SpecifierSet from packaging.version import InvalidVersion, Version @@ -73,15 +74,25 @@ ) __all__ = [ + "BUILD_MANIFEST_FILE_ROLE", + "CALIBRATION_DIAGNOSTICS_FILE_ROLE", + "CALIBRATION_WEIGHTS_FILE_ROLE", + "CHECKSUMS_FILE", + "CHECKSUMS_FILE_ROLE", "COMPATIBILITY_CLAIM_DECLARER_MAX_CHARS", + "DATASET_FILE_ROLE", "EVIDENCE_RELEASE_ID_SEGMENT", "EVIDENCE_RELEASE_MANIFEST_SCHEMA_VERSION", "LOCAL_AREA_REQUIRED_RELEASE_FILES", "NATIONAL_DEFAULT_DATASET_ROLE", "NON_DEFAULT_LOCAL_AREA_DATASET_ROLE", + "PROPOSED_US_RELEASES", "PUBLISHER_CLAIM_BASIS", + "RELEASE_MANIFEST_FILE_ROLE", "RELEASE_MANIFEST_SCHEMA_VERSION", + "RELEASE_ROLES", "REQUIRED_RELEASE_FILES", + "RETIRED_BUILD_FIELDS", "US_FISCAL_STORED_INPUTS_STAGE", "US_LOCAL_AREA_SPM_MEASUREMENT_STAGE", "US_LOCAL_AREA_STORED_INPUTS_STAGE", @@ -94,6 +105,8 @@ "ReleaseContractError", "compatibility_claim_declarer_error", "line_for_release_id", + "publishes_to_build_folder", + "release_artifact_role", "release_dataset_role", "required_release_files", "stored_input_evidence_manifest_block", @@ -173,10 +186,12 @@ def compatibility_claim_declarer_error(declared_by: object) -> str | None: #: Each release's role in ``releases.json``, from its manifest's #: ``dataset_role``. A release keeps the role it was first published with. -RELEASE_ROLES: Mapping[str, str] = { - NATIONAL_DEFAULT_DATASET_ROLE: "national", - NON_DEFAULT_LOCAL_AREA_DATASET_ROLE: "local_area", -} +RELEASE_ROLES: Mapping[str, str] = MappingProxyType( + { + NATIONAL_DEFAULT_DATASET_ROLE: "national", + NON_DEFAULT_LOCAL_AREA_DATASET_ROLE: "local_area", + } +) #: The roles of a build folder's own files. The emitter interface names the #: same strings (``microcosm_emitter_interface.publication`` and ``.bundles``); #: this package supports Python versions the interface does not, so it @@ -206,10 +221,12 @@ def compatibility_claim_declarer_error(declared_by: object) -> str | None: #: no US release, and every US release keeps tags and ``latest.json``. Once #: they are agreed, that function names them, the US builders write the #: build-folder manifests under them and the registry's US entries name them. -PROPOSED_US_RELEASES: Mapping[str, str] = { - "populace-us-2024-national": "national", - "populace-us-2024-acs-local": "local_area", -} +PROPOSED_US_RELEASES: Mapping[str, str] = MappingProxyType( + { + "populace-us-2024-national": "national", + "populace-us-2024-acs-local": "local_area", + } +) def publishes_to_build_folder(release_id: str) -> bool: From bba22e76faed742237a4945522e269fbff45efd8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:47:45 +0400 Subject: [PATCH 06/26] Test that the proposed US local-area release is populace-us-2024-local The proposal now names one national and one local-area release in the one `populace-us` repository: `populace-us-2024-national` and `populace-us-2024-local`, still awaiting the agreement with the US data builder. Co-Authored-By: Claude Opus 5.5 --- .../microcosm-data/tests/engine_free/shared/test_contract.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_contract.py index 6c10ad4262..b196b4d7fc 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_contract.py @@ -2524,7 +2524,7 @@ def test_the_proposed_us_releases_are_recorded_but_not_used() -> None: US release publishes into build folders until they are agreed.""" assert contract.PROPOSED_US_RELEASES == { "populace-us-2024-national": "national", - "populace-us-2024-acs-local": "local_area", + "populace-us-2024-local": "local_area", } assert set(contract.PROPOSED_US_RELEASES.values()) <= set( contract.RELEASE_ROLES.values() From ca252a470daf1abe55343aae9382a89704fee636 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:48:23 +0400 Subject: [PATCH 07/26] Name the proposed US local-area release populace-us-2024-local `PROPOSED_US_RELEASES` follows the adjusted proposal: one `policyengine/populace-us` repository with `populace-us-2024-national` (role `national`) and `populace-us-2024-local` (role `local_area`). Build IDs and the `populace_us_2024_acs_local.h5` file name are unchanged, and nothing reads the names until the US data builder agrees them. Co-Authored-By: Claude Opus 5.5 --- .../1504-h2c-release-builds-in-folders.changed.md | 2 +- .../microcosm-data/src/microcosm/data/contract.py | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/changelog.d/1504-h2c-release-builds-in-folders.changed.md b/changelog.d/1504-h2c-release-builds-in-folders.changed.md index 14d0a0edbe..16b20528bd 100644 --- a/changelog.d/1504-h2c-release-builds-in-folders.changed.md +++ b/changelog.d/1504-h2c-release-builds-in-folders.changed.md @@ -1 +1 @@ -UK release builds publish into their own folders through the emitter. The UK national, dense and local-area releases (`microcosm.data.contract.publishes_to_build_folder`) hand each build to the separately installed `microcosm-emitter` with the interface's `publish_release` call, and its release writer puts the build in `releases///` and records it in the repository's `releases.json` in one commit; Microcosm no longer commits, tags or writes `latest*.json` pointer files for them. The new `microcosm-publish-release-build` command (`microcosm.build.release_publication`, in `microcosm-build`) checks the build with the release contract, hands every file over with its role and SHA-256, publishes with or without `--make-current`, makes a published build current with `--promote`, and succeeds only when the emitter's receipt is `published` and, when current was asked for, names the build as `current`. The build is the calibration attempt ID: both manifests name `release` and `build` as strings, the release manifest records `built_at`, `built_with_model_package` and `built_with_core_package` at its top level and a `role` on each artifact (`dataset`, `calibration_weights`, `calibration_diagnostics`, otherwise the artifact's key), and no artifact pins a `revision`. The fields `build_id`, `attempt_id` and `cut_tag` are gone from UK manifests, and the assemblers' `--cut-tag` option with them. Each release's role in `releases.json` is `national` or `local_area`, from its `dataset_role`. The UK national assembler prints a publication command and a separate promotion command; the dense assembler's command makes each new dense build current. The release contract checks this layout for UK releases and refuses the tagged one. `microcosm.data.load` reads a UK release's current build from `releases.json` (or the listed build `build=` names, a withdrawn one with a warning), then its manifest and dataset from the build's folder; `unverified_root=True` is refused for such a release, and the loader no longer follows `latest-.json` pointers. `microcosm-publish-release` and `tools/publish_release.sh` keep publishing US releases with tags and `latest.json`, refuse UK releases, and lose `--promote-line`. UK publications send no Slack alert. The stable releases proposed for US builds, `populace-us-2024-national` (`national`, the default) and `populace-us-2024-acs-local` (`local_area`), are recorded in `microcosm.data.contract.PROPOSED_US_RELEASES` but not used until they are agreed with the US data builder. +UK release builds publish into their own folders through the emitter. The UK national, dense and local-area releases (`microcosm.data.contract.publishes_to_build_folder`) hand each build to the separately installed `microcosm-emitter` with the interface's `publish_release` call, and its release writer puts the build in `releases///` and records it in the repository's `releases.json` in one commit; Microcosm no longer commits, tags or writes `latest*.json` pointer files for them. The new `microcosm-publish-release-build` command (`microcosm.build.release_publication`, in `microcosm-build`) checks the build with the release contract, hands every file over with its role and SHA-256, publishes with or without `--make-current`, makes a published build current with `--promote`, and succeeds only when the emitter's receipt is `published` and, when current was asked for, names the build as `current`. The build is the calibration attempt ID: both manifests name `release` and `build` as strings, the release manifest records `built_at`, `built_with_model_package` and `built_with_core_package` at its top level and a `role` on each artifact (`dataset`, `calibration_weights`, `calibration_diagnostics`, otherwise the artifact's key), and no artifact pins a `revision`. The fields `build_id`, `attempt_id` and `cut_tag` are gone from UK manifests, and the assemblers' `--cut-tag` option with them. Each release's role in `releases.json` is `national` or `local_area`, from its `dataset_role`. The UK national assembler prints a publication command and a separate promotion command; the dense assembler's command makes each new dense build current. The release contract checks this layout for UK releases and refuses the tagged one. `microcosm.data.load` reads a UK release's current build from `releases.json` (or the listed build `build=` names, a withdrawn one with a warning), then its manifest and dataset from the build's folder; `unverified_root=True` is refused for such a release, and the loader no longer follows `latest-.json` pointers. `microcosm-publish-release` and `tools/publish_release.sh` keep publishing US releases with tags and `latest.json`, refuse UK releases, and lose `--promote-line`. UK publications send no Slack alert. The stable releases proposed for US builds, `populace-us-2024-national` (`national`, the default) and `populace-us-2024-local` (`local_area`), are recorded in `microcosm.data.contract.PROPOSED_US_RELEASES` but not used until they are agreed with the US data builder. diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index 6ab39525b3..7b7ac4c8a3 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -215,16 +215,18 @@ def compatibility_claim_declarer_error(declared_by: object) -> str | None: #: The stable releases proposed for US builds, with each one's role in -#: ``releases.json``: the national release (the repository's default) and the -#: ACS local-area release. They are proposals the US data builder has not -#: agreed yet, so nothing reads them: :func:`publishes_to_build_folder` names -#: no US release, and every US release keeps tags and ``latest.json``. Once -#: they are agreed, that function names them, the US builders write the +#: ``releases.json``: in the one ``policyengine/populace-us`` repository, the +#: national release (the repository's default) and the local-area release, +#: whose builds keep their IDs and the file name +#: ``populace_us_2024_acs_local.h5``. They are proposals the US data builder +#: has not agreed yet, so nothing reads them: :func:`publishes_to_build_folder` +#: names no US release, and every US release keeps tags and ``latest.json``. +#: Once they are agreed, that function names them, the US builders write the #: build-folder manifests under them and the registry's US entries name them. PROPOSED_US_RELEASES: Mapping[str, str] = MappingProxyType( { "populace-us-2024-national": "national", - "populace-us-2024-acs-local": "local_area", + "populace-us-2024-local": "local_area", } ) From 30b3694e154c498de3f651715b267b5432a01731 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:06:03 +0400 Subject: [PATCH 08/26] Test that the dense contract keeps the local-area package checks CI's engine-free jobs failed `test_assembler_stages_a_graph_built_dense_candidate`: the synthetic graph records engine versions as `unavailable`, and the build-folder layout's new compatibility-list check refused the dense release's `==unavailable` specifiers, which the local-area contract never checked. This test holds the local-area contract to its old scope. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_dense_release_contract.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py b/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py index c0a9eeb971..c80606616e 100644 --- a/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py +++ b/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py @@ -925,6 +925,23 @@ def test_a_release_manifest_naming_another_build_is_rejected(tmp_path: Path) -> assert "name different builds" in text +def test_a_dense_release_keeps_the_local_area_package_checks(tmp_path: Path) -> None: + """The build details moved to the top level, but the local-area contract + still checks only that they are there, as it did inside ``build``: a + build run where the engines were not installed, whose versions read + ``unavailable``, validates as before.""" + release_dir = write_dense_bundle(tmp_path) + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + for field in ("built_with_core_package", "built_with_model_package"): + manifest[field]["version"] = "unavailable" + for field in ("compatible_core_packages", "compatible_model_packages"): + manifest[field][0]["specifier"] = "==unavailable" + (release_dir / "release_manifest.json").write_text(json.dumps(manifest, indent=1)) + _refresh_packaging_checksums(release_dir) + + validate_release_dir(release_dir) + + @pytest.mark.parametrize( "field", ["built_at", "built_with_core_package", "built_with_model_package"] ) From 225665acaea8fe6d8076eb3f20d0f747cf660804 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:06:40 +0400 Subject: [PATCH 09/26] Keep the local-area contract's package checks to their old scope The build-folder layout moved `built_at` and the built-with packages to the release manifest's top level. The national contract still requires the compatibility lists to include the built-with versions; the local-area contract, as before, checks only that the built-with packages are there, so a graph-built dense candidate whose engines read `unavailable` assembles again. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/data/contract.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index 7b7ac4c8a3..99d82f3e3c 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -1368,9 +1368,18 @@ def _is_bare_file_name(path: str) -> bool: def _check_build_folder_release_details( - manifest: Mapping, release_id: str, failures: list[str] + manifest: Mapping, + release_id: str, + failures: list[str], + *, + compatible_packages: bool = True, ) -> None: - """``built_at`` and the built-with packages, at the manifest's top level.""" + """``built_at`` and the built-with packages, at the manifest's top level. + + With ``compatible_packages`` the compatibility lists must also include + the built-with versions, as the national contract has always required. + The local-area contract never checked them, and still does not. + """ built_at = manifest.get("built_at") if not isinstance(built_at, str) or not built_at: failures.append( @@ -1391,6 +1400,8 @@ def _check_build_folder_release_details( expected_name=model_package, failures=failures, ) + if not compatible_packages: + return _check_compatible_package_entries( manifest.get("compatible_core_packages"), field="compatible_core_packages", @@ -5663,7 +5674,9 @@ def _check_local_area_release_manifest( _check_build_folder_identity( manifest, release_id, filename="release_manifest.json", failures=failures ) - _check_build_folder_release_details(manifest, release_id, failures) + _check_build_folder_release_details( + manifest, release_id, failures, compatible_packages=False + ) elif not isinstance(build, Mapping) or not build.get("build_id"): failures.append("release_manifest.json is missing 'build.build_id'.") elif build["build_id"] != release_id: From 325c0e278e1b5bea355f0c4cb848b985b92171c2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:55:55 +0400 Subject: [PATCH 10/26] Test the publication command's up-front checks and its advice before the pointer files go Review round 1 of the build-folder publication. These tests fail on assertions until the fix: - the dense assembler prints a publication without --make-current and a separate --promote command, since the emitter refuses every change to a current build while the latest*.json pointer files exist; - a --promote refused for those pointer files says to promote again once they are deleted, not to publish without --make-current; - with HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE set, the command refuses before starting an emitter; - the command runs the emitter's write-access check and hands nothing over when the credential is missing or read-only. They also add command tests for the pending, refused and unavailable receipts, and a test that publishes an assembled UK national directory with the release contract itself; those pin behaviour that already holds. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_dense_release_assembler.py | 14 +- .../uk/test_uk_release_assembler.py | 44 ++++ .../uk/test_uk_release_publication.py | 213 ++++++++++++++++++ 3 files changed, 269 insertions(+), 2 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py index c30f1aa1e9..86b63bedbf 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py @@ -616,7 +616,9 @@ def test_assembler_stages_a_contract_valid_dense_release( shipped["reviewed_exclusions_stood_on"] == coverage["signed_deferrals"]["reviewed_exclusions"] ) - # Each new dense build becomes current when it is published. + # While the repository keeps its latest*.json pointer files, the emitter + # refuses any change to a current build, so the printed publication lists + # the build and the promotion makes it current once those files are gone. assert shlex.split(summary["publish_command"]) == [ "uv", "run", @@ -626,7 +628,15 @@ def test_assembler_stages_a_contract_valid_dense_release( "policyengine/populace-uk-private", "--artifact-root", str(candidate), - "--make-current", + ] + assert shlex.split(summary.get("promote_command", "")) == [ + "uv", + "run", + "microcosm-publish-release-build", + str(release_dir), + "--repo-id", + "policyengine/populace-uk-private", + "--promote", ] published = candidate / "microcosm_uk_2024_25_dense.h5" assert ( diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py index a0c2925c67..b48ce46c88 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py @@ -484,6 +484,50 @@ def test_assemble_green_release_dir(assembler_inputs, capsys) -> None: ] +def test_an_assembled_national_build_publishes_through_the_emitter( + assembler_inputs, capsys +) -> None: + """The publication checks the assembled directory with the release + contract itself, not a replaced one, and hands every file over.""" + from microcosm.build import release_publication + from microcosm.data.contract import ( + BUILD_MANIFEST_FILE_ROLE, + RELEASE_MANIFEST_FILE_ROLE, + ) + from test_support.microcosm_build.emitter import FakeEmitterClient + + driver = _load_driver_module() + assert driver.main(assembler_inputs["argv"]) == 0 + capsys.readouterr() + release_dir = assembler_inputs["out_dir"] / UK_NATIONAL_RELEASE_ID + client = FakeEmitterClient() + + outcome = release_publication.publish_release_build( + release_dir, + artifact_root=assembler_inputs["candidate"].parent, + client=client, + ) + + assert outcome.published and outcome.succeeded and not outcome.current + (request,) = client.release_requests + assert (request.release, request.build, request.release_role) == ( + UK_NATIONAL_RELEASE_ID, + _ATTEMPT_ID, + "national", + ) + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + assert {item.name: item.role for item in request.files} == { + "release_manifest.json": RELEASE_MANIFEST_FILE_ROLE, + "build_manifest.json": BUILD_MANIFEST_FILE_ROLE, + **{entry["path"]: entry["role"] for entry in manifest["artifacts"].values()}, + } + folder = f"releases/{UK_NATIONAL_RELEASE_ID}/{_ATTEMPT_ID}" + published_dataset = client.hub_files[ + ("policyengine/populace-uk-private", f"{folder}/{driver._DATASET_FILENAME}") + ] + assert published_dataset == assembler_inputs["candidate"].read_bytes() + + def test_assemble_preserves_successful_version_2_delivery( assembler_inputs, capsys ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py index 04d1f813b6..d8f0dae0ea 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py @@ -29,6 +29,36 @@ UK_REPO_ID = "policyengine/populace-uk-private" UK_NATIONAL_RELEASE_ID = "microcosm-uk-2024-25-national" UK_EARLIER_BUILD = "uk-frs-calibration-attempt-20260901T000000Z-0badcafe" +#: The variables ``huggingface_hub`` reads to refuse every Hub request. +OFFLINE_VARIABLES = ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE") +#: What ``check_write_access`` answers when the emitter finds no credential. +NO_CREDENTIAL = { + "status": "checked", + "credential": "missing", + "reachable": None, + "can_write": None, + "error_type": None, +} +#: What it answers for a credential that can read but not write. +READ_ONLY_CREDENTIAL = { + "status": "checked", + "credential": "present", + "reachable": True, + "can_write": False, + "error_type": None, +} + + +@pytest.fixture(autouse=True) +def _hub_online(monkeypatch) -> None: + """Run each test as on a build machine that can reach the Hub. + + Local test runs set ``HF_HUB_OFFLINE``, and the command refuses to start + an emitter with it set. Every emitter here is the in-memory client, and + the repository's root fixture refuses to start a real one. + """ + for name in OFFLINE_VARIABLES: + monkeypatch.delenv(name, raising=False) @pytest.fixture @@ -295,12 +325,195 @@ def start() -> FakeEmitterClient: assert all(emitter.closed for emitter in emitters) +def _start_emitters( + monkeypatch, *options: dict +) -> tuple[list[FakeEmitterClient], dict]: + """Each command run starts the next emitter; all write to one repository. + + ``options`` are the keyword arguments of each emitter in the order the + commands start them; later emitters take none. + """ + repository: dict = {} + started: list[FakeEmitterClient] = [] + remaining = list(options) + + def start() -> FakeEmitterClient: + settings = remaining.pop(0) if remaining else {} + started.append(FakeEmitterClient(hub_files=repository, **settings)) + return started[-1] + + monkeypatch.setattr(release_publication, "_start_release_emitter", start) + return started, repository + + +@pytest.mark.parametrize( + ("receipt", "explanations"), + [ + ( + {"status": "pending", "error_code": "REPOSITORY_UNAVAILABLE"}, + ( + "still trying (REPOSITORY_UNAVAILABLE)", + "Run the same command again later", + ), + ), + ( + { + "status": "refused", + "error_code": "BUILD_FOLDER_EXISTS", + "message": "the build's folder already exists.", + }, + ( + "refused it (BUILD_FOLDER_EXISTS): the build's folder already exists.", + "never changed after publishing", + ), + ), + ({"status": "unavailable"}, ("did not answer",)), + ], + ids=["pending", "refused", "unavailable"], +) +def test_the_command_fails_and_explains_a_change_that_did_not_land( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, + receipt: dict, + explanations: tuple[str, ...], +) -> None: + client = FakeEmitterClient(release_receipts=[receipt]) + monkeypatch.setattr(release_publication, "_start_release_emitter", lambda: client) + + code, output, error = _run( + [str(national), "--artifact-root", str(artifact_root)], capsys + ) + + assert code == 1 + assert output["status"] == receipt["status"] + assert output["error_code"] == receipt.get("error_code") + assert output["current"] is False + for explanation in explanations: + assert explanation in error + assert client.closed is True + + +def test_a_promotion_refused_for_pointer_files_says_to_promote_again_later( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, +) -> None: + """The build is published already, so publishing it again cannot help.""" + _, repository = _start_emitters(monkeypatch) + repository[(UK_REPO_ID, "latest-national.json")] = b"{}" + assert _run([str(national), "--artifact-root", str(artifact_root)], capsys)[0] == 0 + + code, output, error = _run([str(national), "--promote"], capsys) + + assert code == 1 + assert (output["status"], output["error_code"]) == ( + "refused", + "POINTER_FILES_PRESENT", + ) + assert "without --make-current" not in error + assert "stays published but is not current" in error + assert "Run this --promote command again once the pointer files" in error + record = json.loads(repository[(UK_REPO_ID, "releases.json")]) + assert record["releases"][UK_NATIONAL_RELEASE_ID]["current"] is None + + +@pytest.mark.parametrize("variable", OFFLINE_VARIABLES) +@pytest.mark.parametrize("promote", [False, True], ids=["publish", "promote"]) +def test_the_command_refuses_offline_mode_before_starting_an_emitter( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, + variable: str, + promote: bool, +) -> None: + """The emitter inherits the variable and could never reach the Hub, so the + change would wait out the emitter's hour as pending.""" + started, _ = _start_emitters(monkeypatch) + monkeypatch.setenv(variable, "1") + argv = ( + [str(national), "--promote"] + if promote + else [str(national), "--artifact-root", str(artifact_root)] + ) + + code, output, error = _run(argv, capsys) + + assert code == 1 + assert started == [] + assert output is None + assert "refusing to publish" in error and variable in error + + +@pytest.mark.parametrize( + ("access", "reason"), + [ + ( + NO_CREDENTIAL, + "needs a Hugging Face write credential (HF_TOKEN or `hf auth login`)", + ), + (READ_ONLY_CREDENTIAL, "read-only"), + ], + ids=["no-credential", "read-only"], +) +def test_the_command_checks_write_access_before_publishing( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, + access: dict, + reason: str, +) -> None: + started, repository = _start_emitters(monkeypatch, {"write_access": access}) + + code, output, error = _run( + [str(national), "--artifact-root", str(artifact_root)], capsys + ) + + (emitter,) = started + assert code == 1 + assert "check_write_access" in emitter.calls + assert emitter.release_requests == [] + assert output["status"] == "unavailable" + assert f"the release change to {UK_REPO_ID}" in error and reason in error + assert (UK_REPO_ID, "releases.json") not in repository + assert emitter.closed is True + + +def test_the_command_checks_write_access_before_promoting( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, +) -> None: + started, repository = _start_emitters( + monkeypatch, {}, {"write_access": NO_CREDENTIAL} + ) + assert _run([str(national), "--artifact-root", str(artifact_root)], capsys)[0] == 0 + + code, output, error = _run([str(national), "--promote"], capsys) + + promoter = started[1] + assert code == 1 + assert "check_write_access" in promoter.calls + assert promoter.release_requests == [] + assert output["status"] == "unavailable" + assert "needs a Hugging Face write credential" in error + record = json.loads(repository[(UK_REPO_ID, "releases.json")]) + assert record["releases"][UK_NATIONAL_RELEASE_ID]["current"] is None + + def test_preflight_checks_the_build_without_an_emitter( national: Path, artifact_root: Path, # noqa: F811 monkeypatch, capsys, ) -> None: + # A preflight reads only local files, so offline mode does not refuse it. + monkeypatch.setenv("HF_HUB_OFFLINE", "1") monkeypatch.setattr( release_publication, "_start_release_emitter", From 857e7cdded246c73f69647b5c2b63e05690f93d1 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:03:18 +0400 Subject: [PATCH 11/26] Check offline mode and write access before a release change, and print a dense promotion The publication command now makes the two checks the staged-bundle hand-over makes before it hands anything to the emitter: - with HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE set it refuses before starting an emitter (staging_dataset.hub_offline), since the emitter inherits the variable and the change would stay pending until it expired an hour later; - it runs the emitter's write-access check (staging_dataset's write_access_problem, which now takes the wording of the change it checks for) and hands nothing over when the emitter is missing or outdated, or the credential is missing, read-only or cannot reach the repository. While the repository keeps its latest*.json pointer files the emitter refuses every change to a current build, so the dense assembler prints a publication without --make-current and a separate --promote command, as the national assembler does. A promotion refused for those files says the build stays published and to promote it again once they are deleted, instead of advising a publication without --make-current. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/release_publication.py | 103 ++++++++++++++---- .../src/microcosm/build/staging_dataset.py | 29 +++-- tools/assemble_uk_dense_release_dir.py | 28 ++++- 3 files changed, 125 insertions(+), 35 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/release_publication.py b/packages/microcosm-build/src/microcosm/build/release_publication.py index 766c0fbd9e..8c303b8d5c 100644 --- a/packages/microcosm-build/src/microcosm/build/release_publication.py +++ b/packages/microcosm-build/src/microcosm/build/release_publication.py @@ -1,7 +1,8 @@ """Publish a release build into its own folder through the emitter. -A release whose builds publish into their own folders (every UK release: -``microcosm.data.contract.publishes_to_build_folder``) is handed to the +A release whose builds publish into their own folders (the UK national, +dense and local-area releases, which +``microcosm.data.contract.publishes_to_build_folder`` names) is handed to the separately installed emitter with the interface's ``publish_release`` call. Microcosm decides what the build contains and checks it with the release contract; the emitter's release writer puts the files in @@ -18,8 +19,13 @@ The emitter finds its Hugging Face credential the way a build's emitter does: it is this command's child process and inherits its environment (``HF_TOKEN``, then ``HUGGINGFACE_TOKEN``, then the token saved by -``hf auth login``). Publication sends no Slack alert; announcing release -changes from ``releases.json`` is the dashboard's job. +``hf auth login``). It inherits ``HF_HUB_OFFLINE`` and +``TRANSFORMERS_OFFLINE`` too, so with either set the command refuses before +it starts one, and it hands nothing over until the emitter's write-access +check passes, as the staged-bundle hand-over does: otherwise the change +would wait, pending, until the emitter dropped it an hour later. +Publication sends no Slack alert. The dashboard is to announce release +changes from ``releases.json``; until it does, these publications raise none. """ from __future__ import annotations @@ -38,7 +44,8 @@ unavailable_release_receipt, ) -from microcosm.build.telemetry_emitter import emitter_problem, start_bundle_emitter +from microcosm.build.staging_dataset import hub_offline, write_access_problem +from microcosm.build.telemetry_emitter import start_bundle_emitter from microcosm.data.contract import publishes_to_build_folder from microcosm.data.publish_cli import publication_refusal from microcosm.data.release import ( @@ -49,6 +56,7 @@ if TYPE_CHECKING: from microcosm_emitter_interface import EmitterStartupError, RequestFailure + from microcosm_emitter_interface.bundles import WriteAccess __all__ = [ "PROMOTION_WAIT_SECONDS", @@ -69,13 +77,17 @@ #: How long the command waits for a promotion, which changes only #: ``releases.json``. PROMOTION_WAIT_SECONDS = 300.0 +_POINTER_FILES = ( + "The repository still has latest*.json pointer files, and the emitter " + "changes no release's current build while any exists, so that they and " + "releases.json cannot disagree." +) #: What the emitter's refusal codes mean for the operator, where its own -#: message does not say what to do next. +#: message does not say what to do next: for a publication, and for a +#: promotion of a build already published. _REFUSAL_ADVICE = { "POINTER_FILES_PRESENT": ( - "The repository still has latest*.json pointer files, and the emitter " - "changes no release's current build while any exists, so that they " - "and releases.json cannot disagree. Publish the build without " + f"{_POINTER_FILES} Nothing was published: publish the build without " "--make-current, and make it current with --promote once the pointer " "files are deleted." ), @@ -93,6 +105,21 @@ "the emitter dropped it; run the command again." ), } +_PROMOTION_REFUSAL_ADVICE = { + **_REFUSAL_ADVICE, + "POINTER_FILES_PRESENT": ( + f"{_POINTER_FILES} The build stays published but is not current. Run " + "this --promote command again once the pointer files are deleted." + ), +} +#: Why the command refuses with ``HF_HUB_OFFLINE`` or ``TRANSFORMERS_OFFLINE`` +#: set: the emitter it starts inherits the variable. +_OFFLINE_REFUSAL = ( + "HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE is set, so the emitter this command " + "starts could not reach the Hugging Face Hub, and the change would stay " + "pending until the emitter dropped it an hour later; unset it and run the " + "command again" +) class ReleaseEmitter(Protocol): @@ -107,6 +134,8 @@ def available(self) -> bool: ... @property def modules(self) -> frozenset[str]: ... + def check_write_access(self, repository: str) -> WriteAccess: ... + def publish_release( self, request: PublishRelease, *, wait_seconds: float = 300.0 ) -> ReleaseReceipt: ... @@ -128,8 +157,10 @@ class ReleasePublication: """What became of one release change: the emitter's receipt, read. ``wanted_current`` says whether the change asked for the build to become - current: a promotion, or a publication with ``make_current``. ``problem`` - says why no emitter could take the change, when none could. + current: a promotion, or a publication with ``make_current``. + ``promotion`` says whether it was a promotion. ``problem`` says why + nothing was handed over, when the emitter could not take the change or + its write-access check refused it. """ repository: str @@ -138,6 +169,7 @@ class ReleasePublication: wanted_current: bool receipt: ReleaseReceipt problem: str | None = None + promotion: bool = False @property def published(self) -> bool: @@ -158,7 +190,7 @@ def explanation(self) -> str: """A sentence or two on the outcome, for the operator.""" status, code = self.receipt["status"], self.receipt.get("error_code") if self.problem is not None: - return f"No emitter took the change: {self.problem}." + return f"Nothing was handed over: {self.problem}." if status == "unavailable": return "The emitter did not answer; nothing was handed over." if status == "pending": @@ -168,7 +200,9 @@ def explanation(self) -> str: "again later to see whether it landed." ) if status == "refused": - advice = _REFUSAL_ADVICE.get(str(code)) + advice = ( + _PROMOTION_REFUSAL_ADVICE if self.promotion else _REFUSAL_ADVICE + ).get(str(code)) reason = self.receipt.get("message") or code return f"The emitter refused it ({code}): {reason}" + ( f" {advice}" if advice else "" @@ -210,7 +244,15 @@ def _hand_over( owned = client is None emitter: ReleaseEmitter = _start_release_emitter() if owned else client try: - problem = emitter_problem(emitter) + # The staged-bundle hand-over's check: the emitter is running with its + # Hugging Face module, and its credential can write the repository. + problem = write_access_problem( + emitter, + change.repository, + action="the release change", + emitter_task="the emitter, which commits it", + proof="the change itself", + ) if problem is not None: receipt = unavailable_release_receipt(change) elif isinstance(change, PublishRelease): @@ -227,9 +269,16 @@ def _hand_over( wanted_current=wanted_current, receipt=receipt, problem=problem, + promotion=isinstance(change, PromoteBuild), ) +def _refuse_offline() -> None: + """Refuse before an emitter starts when it could not reach the Hub.""" + if hub_offline(): + raise ValueError(_OFFLINE_REFUSAL) + + def publication_request( prepared: BuildFolderRelease, *, make_current: bool ) -> PublishRelease: @@ -268,8 +317,13 @@ def publish_release_build( build that breaks its release contract is never handed over. Without a ``client``, a short-lived emitter is started and closed afterwards; its queue is the one builds on this machine share, so a change still pending - when it closes is retried by the next emitter started here. + when it closes is retried by the next emitter started here. It refuses + (``ValueError``) before anything else when ``HF_HUB_OFFLINE`` or + ``TRANSFORMERS_OFFLINE`` is set, and hands nothing over unless the + emitter's write-access check passes. """ + if client is None: + _refuse_offline() prepared = prepare_build_folder_release( release_dir, artifact_root=artifact_root, repository=repository ) @@ -288,7 +342,12 @@ def promote_release_build( client: ReleaseEmitter | None = None, wait_seconds: float = PROMOTION_WAIT_SECONDS, ) -> ReleasePublication: - """Make a published build, named by its local manifest, the current build.""" + """Make a published build, named by its local manifest, the current build. + + It refuses and checks write access as :func:`publish_release_build` does. + """ + if client is None: + _refuse_offline() named_repository, release, build = build_folder_identity(release_dir) if repository is not None and repository != named_repository: raise ValueError( @@ -308,9 +367,11 @@ def _parser() -> argparse.ArgumentParser: prog="microcosm-publish-release-build", description=( "Publish a build of a release whose builds publish into their own " - "folders (every UK release) through the emitter, or make a " - "published build current. Releases that publish with tags and " - "latest.json use tools/publish_release.sh." + "folders (the UK national, dense and local-area releases) through " + "the emitter, or make a published build current. Releases that " + "publish with tags and latest.json (every US release, the June " + "2023 UK release and populace-uk---k releases) use " + "tools/publish_release.sh." ), ) parser.add_argument("release_dir", type=Path, help="The local release directory.") @@ -367,7 +428,9 @@ def main(argv: list[str] | None = None) -> int: A build that fails its checks (the release contract, a file whose bytes differ, another repository) is refused with the reason and status 1, - before any emitter starts. + before any emitter starts, and so is any change while ``HF_HUB_OFFLINE`` + or ``TRANSFORMERS_OFFLINE`` is set. A change the emitter's write-access + check refuses is handed nothing and exits 1 with the reason. """ parser = _parser() args = parser.parse_args(argv) diff --git a/packages/microcosm-build/src/microcosm/build/staging_dataset.py b/packages/microcosm-build/src/microcosm/build/staging_dataset.py index 64388d33a5..acd79d2654 100644 --- a/packages/microcosm-build/src/microcosm/build/staging_dataset.py +++ b/packages/microcosm-build/src/microcosm/build/staging_dataset.py @@ -723,7 +723,14 @@ def hub_offline(environment: Mapping[str, str] | None = None) -> bool: return str(value or "").upper() in _TRUE_VALUES -def write_access_problem(emitter: BundleEmitter | None, repository: str) -> str | None: +def write_access_problem( + emitter: BundleEmitter | None, + repository: str, + *, + action: str = "remote dataset staging", + emitter_task: str = "the build's emitter, which uploads the bundle", + proof: str = "the upload at the end of the run", +) -> str | None: """Why a remote stage to ``repository`` could not complete, or None. ``emitter`` is the build's emitter client, running or not. The refusal @@ -733,19 +740,21 @@ def write_access_problem(emitter: BundleEmitter | None, repository: str) -> str check, or the emitter's own check of the credential, the repository and the credential's write scope (``check_write_access``). A scope the Hub does not describe is a warning: only the upload itself proves it. + + Another hand-over to the Hub, such as a release change, names itself in + the messages: ``action`` is what needs the access, ``emitter_task`` the + emitter and what it does for it, and ``proof`` what proves an unread + write scope. """ try: repository_identifier(repository) except ValueError: return ( - "remote dataset staging needs a Hugging Face repository identifier of " + f"{action} needs a Hugging Face repository identifier of " f"the form owner/name; got {repository!r}" ) - needs = ( - f"remote dataset staging to {repository} needs the build's emitter, " - "which uploads the bundle, but" - ) + needs = f"{action} to {repository} needs {emitter_task}, but" problem = emitter_problem(emitter) if problem is not None: return f"{needs} {problem}" @@ -766,17 +775,17 @@ def write_access_problem(emitter: BundleEmitter | None, repository: str) -> str ) if access.get("credential") != "present": return ( - f"remote dataset staging to {repository} needs a Hugging Face write " + f"{action} to {repository} needs a Hugging Face write " "credential (HF_TOKEN or `hf auth login`)" ) if access.get("reachable") is False: error_type = access.get("error_type") reason = error_type if isinstance(error_type, str) else "no answer" - return f"remote dataset staging cannot reach {repository} ({reason})" + return f"{action} cannot reach {repository} ({reason})" can_write = access.get("can_write") if can_write is False: return ( - f"remote dataset staging to {repository} needs a write credential: " + f"{action} to {repository} needs a write credential: " "the ambient Hugging Face token is read-only or is not scoped to this " "repository or its owner (a fine-grained token needs repo.write on " f"{repository} or on {repository.split('/', 1)[0]})" @@ -784,7 +793,7 @@ def write_access_problem(emitter: BundleEmitter | None, repository: str) -> str if can_write is None: _warn( "the Hugging Face credential's write scope could not be read; " - "the upload at the end of the run will prove it." + f"{proof} will prove it." ) return None diff --git a/tools/assemble_uk_dense_release_dir.py b/tools/assemble_uk_dense_release_dir.py index 8909419c48..1275da70f7 100644 --- a/tools/assemble_uk_dense_release_dir.py +++ b/tools/assemble_uk_dense_release_dir.py @@ -12,9 +12,12 @@ filename; nothing is uploaded. The release publishes each build into its own folder through the emitter: the build is the run's attempt ID, both manifests name the release and the build, and nothing is tagged. The summary prints the -exact ``microcosm-publish-release-build`` command for the human step, which -makes the build the release's current build when it is published (private -repository). +exact ``microcosm-publish-release-build`` commands for the human step +(private repository): ``publish_command`` lists the build, and +``promote_command`` makes it the release's current build. Each new dense +build becomes current; while the repository still has its ``latest*.json`` +pointer files, the emitter refuses every change to a current build, so the +promotion waits until those files are deleted. The rotated holdout and the incumbent comparison are opt-in diagnostics (microcosm#1301). The manifest's reviewed limitations say what the release @@ -1100,7 +1103,11 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: for contract_warning in contract_warnings: print(f"warning: {contract_warning}", file=sys.stderr) release_dir.rename(destination) - # Each new dense build becomes current when it is published. + # Each new dense build becomes current. While the repository keeps its + # latest*.json pointer files the emitter refuses any change to a current + # build, a publication with --make-current included (after the upload's + # hashing), so the build is listed first and promoted once those files are + # deleted. Without them, --make-current publishes it as current at once. publish_command = shlex.join( [ "uv", @@ -1111,7 +1118,17 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: _REPO_ID, "--artifact-root", str(artifact_root), - "--make-current", + ] + ) + promote_command = shlex.join( + [ + "uv", + "run", + "microcosm-publish-release-build", + str(destination), + "--repo-id", + _REPO_ID, + "--promote", ] ) return { @@ -1125,6 +1142,7 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: }, "evidence": {name: _sha256(destination / name) for name in evidence_files}, "publish_command": publish_command, + "promote_command": promote_command, "warnings": contract_warnings, } From 4b3f1b36cb8523e9ada1ea4353e396204f16fa92 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:03:18 +0400 Subject: [PATCH 12/26] Name the three UK releases that publish into build folders, and when their alerts return Only the UK national, dense and local-area releases publish into build folders. The June 2023 UK release and populace-uk---k releases still publish with tags, latest.json and their Slack alert, so the README, the agent guide, the data package's README and docstrings, tools/publish_release.sh and the changelog fragment now say so, and the wrapper and tools/release.env.example keep SLACK_WEBHOOK_POPULACE_UK for them. Publications into build folders send no alert until the dashboard posts one from releases.json. The runbooks describe the up-front refusals, the unavailable receipt and, for the dense release, listing each build first and promoting it once the pointer files are deleted. Co-Authored-By: Claude Opus 5.5 --- README.md | 37 +++++++----- ...4-h2c-release-builds-in-folders.changed.md | 2 +- docs/agent-guide.md | 6 +- docs/uk-dense-release-assembly-runbook-762.md | 56 +++++++++++++------ ...k-national-release-assembly-runbook-806.md | 13 ++++- packages/microcosm-data/README.md | 14 +++-- .../src/microcosm/data/contract.py | 2 +- .../src/microcosm/data/loader.py | 27 ++++----- .../src/microcosm/data/publish_cli.py | 6 +- .../src/microcosm/data/release.py | 24 ++++---- tools/publish_release.sh | 16 +++--- tools/release.env.example | 12 ++-- 12 files changed, 136 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index 45b20f5314..9d68ec9114 100644 --- a/README.md +++ b/README.md @@ -427,8 +427,8 @@ see the [package README](packages/microcosm-diagnostics/README.md). Publication runs on the build machine (it needs the freshly built H5), so it isn't a CI step. Releases use one of two layouts. -**UK releases publish each build into its own folder.** The national, dense -and local-area releases (`microcosm.data.contract.publishes_to_build_folder`) +**The UK national, dense and local-area releases publish each build into its +own folder.** These releases (`microcosm.data.contract.publishes_to_build_folder`) hand each build to the separately installed emitter, whose release writer puts it in `releases///` and records it in the repository's `releases.json`, the only record of each release's builds and which one is @@ -449,27 +449,34 @@ The first command publishes a build, and makes it current with `--make-current`; the second makes a published build current. A build counts as current only when the emitter's receipt is `published` and names it as `current`. While the older `latest*.json` pointer files exist, the emitter -refuses every change to a release's current build. These publications send -no Slack alert; announcing release changes from `releases.json` is the -dashboard's job. The UK assemblers print the exact commands, and the +refuses every change to a release's current build, so until they are deleted +a build is published without `--make-current` and promoted afterwards. The +command refuses before it starts an emitter when `HF_HUB_OFFLINE` or +`TRANSFORMERS_OFFLINE` is set, and hands nothing over unless the emitter's +write-access check passes. These publications send no Slack alert: release +alerts for them stop until the dashboard posts them from `releases.json`. +The UK assemblers print the exact commands, and the [national](docs/uk-national-release-assembly-runbook-806.md) and [dense](docs/uk-dense-release-assembly-runbook-762.md) runbooks describe them. `microcosm.data.load` reads the current build of such a release from `releases.json`, or the listed build `build=` names. -**US releases keep tags and `latest.json`** until the stable releases US -builds publish under are agreed with the US data builder. Publication uploads -the locally built `releases//` artifacts to the Hugging Face dataset, -tags the release, and updates `latest.json`: +**Every other release keeps tags and `latest.json`:** every US release, +until the stable releases US builds publish under are agreed with the US data +builder, and the UK releases outside those three, namely the June 2023 release +and `populace-uk---k` releases. Publication uploads the locally +built `releases//` artifacts to the Hugging Face dataset, tags the release, +and updates `latest.json`: ```bash tools/publish_release.sh releases/ --repo-id policyengine/populace-us ``` `tools/publish_release.sh` is a thin wrapper around `microcosm-publish-release` -(all arguments pass straight through), which refuses a UK release. The moment -`latest.json` goes live, the publish CLI posts a release alert to -`#populace-us`. +(all arguments pass straight through), which refuses the releases that +publish into build folders. The moment `latest.json` goes live, the publish +CLI posts a release alert to the country's channel: `#populace-us`, or +`#populace-uk` for a UK release published this way. The publisher uploads only the contract files, the release manifest's artifacts and any `--extra-file`. The US fiscal-refresh tool therefore binds @@ -588,8 +595,10 @@ cp tools/release.env.example tools/release.env # then paste the webhook URLs ``` `tools/release.env` is gitignored; the wrapper loads it (or you can just export -`SLACK_WEBHOOK_POPULACE_US` in your shell) and warns if it is not set. After -that, every US release publishes with an automatic Slack alert. +`SLACK_WEBHOOK_POPULACE_US` / `SLACK_WEBHOOK_POPULACE_UK` in your shell) and +warns if neither is set. After that, every release published with tags and +`latest.json` publishes with an automatic Slack alert. The releases that +publish into build folders read neither variable. Canonical UK exact-k builds also require a stable, base64-encoded 32-byte release key. Source `tools/release.env` before the national build as well as diff --git a/changelog.d/1504-h2c-release-builds-in-folders.changed.md b/changelog.d/1504-h2c-release-builds-in-folders.changed.md index 16b20528bd..9721c3fe20 100644 --- a/changelog.d/1504-h2c-release-builds-in-folders.changed.md +++ b/changelog.d/1504-h2c-release-builds-in-folders.changed.md @@ -1 +1 @@ -UK release builds publish into their own folders through the emitter. The UK national, dense and local-area releases (`microcosm.data.contract.publishes_to_build_folder`) hand each build to the separately installed `microcosm-emitter` with the interface's `publish_release` call, and its release writer puts the build in `releases///` and records it in the repository's `releases.json` in one commit; Microcosm no longer commits, tags or writes `latest*.json` pointer files for them. The new `microcosm-publish-release-build` command (`microcosm.build.release_publication`, in `microcosm-build`) checks the build with the release contract, hands every file over with its role and SHA-256, publishes with or without `--make-current`, makes a published build current with `--promote`, and succeeds only when the emitter's receipt is `published` and, when current was asked for, names the build as `current`. The build is the calibration attempt ID: both manifests name `release` and `build` as strings, the release manifest records `built_at`, `built_with_model_package` and `built_with_core_package` at its top level and a `role` on each artifact (`dataset`, `calibration_weights`, `calibration_diagnostics`, otherwise the artifact's key), and no artifact pins a `revision`. The fields `build_id`, `attempt_id` and `cut_tag` are gone from UK manifests, and the assemblers' `--cut-tag` option with them. Each release's role in `releases.json` is `national` or `local_area`, from its `dataset_role`. The UK national assembler prints a publication command and a separate promotion command; the dense assembler's command makes each new dense build current. The release contract checks this layout for UK releases and refuses the tagged one. `microcosm.data.load` reads a UK release's current build from `releases.json` (or the listed build `build=` names, a withdrawn one with a warning), then its manifest and dataset from the build's folder; `unverified_root=True` is refused for such a release, and the loader no longer follows `latest-.json` pointers. `microcosm-publish-release` and `tools/publish_release.sh` keep publishing US releases with tags and `latest.json`, refuse UK releases, and lose `--promote-line`. UK publications send no Slack alert. The stable releases proposed for US builds, `populace-us-2024-national` (`national`, the default) and `populace-us-2024-local` (`local_area`), are recorded in `microcosm.data.contract.PROPOSED_US_RELEASES` but not used until they are agreed with the US data builder. +Builds of the UK national, dense and local-area releases publish into their own folders through the emitter. These releases (`microcosm.data.contract.publishes_to_build_folder`) hand each build to the separately installed `microcosm-emitter` with the interface's `publish_release` call, and its release writer puts the build in `releases///` and records it in the repository's `releases.json` in one commit; Microcosm no longer commits, tags or writes `latest*.json` pointer files for them. The new `microcosm-publish-release-build` command (`microcosm.build.release_publication`, in `microcosm-build`) checks the build with the release contract, hands every file over with its role and SHA-256, refuses before it starts an emitter when `HF_HUB_OFFLINE` or `TRANSFORMERS_OFFLINE` is set, hands nothing over unless the emitter's write-access check passes, publishes with or without `--make-current`, makes a published build current with `--promote`, and succeeds only when the emitter's receipt is `published` and, when current was asked for, names the build as `current`. The build is the calibration attempt ID: both manifests name `release` and `build` as strings, the release manifest records `built_at`, `built_with_model_package` and `built_with_core_package` at its top level and a `role` on each artifact (`dataset`, `calibration_weights`, `calibration_diagnostics`, otherwise the artifact's key), and no artifact pins a `revision`. The fields `build_id`, `attempt_id` and `cut_tag` are gone from their manifests, and the assemblers' `--cut-tag` option with them. Each release's role in `releases.json` is `national` or `local_area`, from its `dataset_role`. Both UK assemblers print a publication command and a separate promotion command: while the repository still has its `latest*.json` pointer files the emitter refuses every change to a current build, so each new dense build is promoted once those files are deleted, and can be published with `--make-current` after that. The release contract checks this layout for those releases and refuses the tagged one. `microcosm.data.load` reads the current build of the UK 2025 national and dense releases from `releases.json` (or the listed build `build=` names, a withdrawn one with a warning), then its manifest and dataset from the build's folder; `unverified_root=True` is refused for such a release, and the loader no longer follows `latest-.json` pointers. `microcosm-publish-release` and `tools/publish_release.sh` keep publishing every US release, the June 2023 UK release and `populace-uk---k` releases with tags, `latest.json` and their Slack alerts, refuse the build-folder releases, and lose `--promote-line`. Publications into build folders send no Slack alert until the dashboard posts release alerts from `releases.json`. The stable releases proposed for US builds, `populace-us-2024-national` (`national`, the default) and `populace-us-2024-local` (`local_area`), are recorded in `microcosm.data.contract.PROPOSED_US_RELEASES` but not used until they are agreed with the US data builder. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 7db7e4fdf7..b0905b1425 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -266,8 +266,10 @@ Builds, calibrations, and releases run outside PR CI, need gated Hugging Face data and credentials, and cannot run from forks. Release publication is a deliberate human step. A US release publishes with tags and `latest.json` (`tools/publish_release.sh` → `microcosm-publish-release`), checked by -`tools/preflight_us_release_gates.py`. A UK release publishes each build into -its own folder through the emitter (`microcosm-publish-release-build`, from +`tools/preflight_us_release_gates.py`; so do the June 2023 UK release and +`populace-uk---k` releases. The UK national, dense and +local-area releases publish each build into its own folder through the +emitter (`microcosm-publish-release-build`, from `microcosm.build.release_publication`), which records it in the repository's `releases.json`; making a published build current is a separate deliberate call to the same command with `--promote`. The emitter refuses that while the diff --git a/docs/uk-dense-release-assembly-runbook-762.md b/docs/uk-dense-release-assembly-runbook-762.md index 12cb202f75..215253fb21 100644 --- a/docs/uk-dense-release-assembly-runbook-762.md +++ b/docs/uk-dense-release-assembly-runbook-762.md @@ -9,9 +9,10 @@ as its own release, never the default one: a constant release id, `dataset_role: non_default_local_area` (the role `local_area` in `releases.json`) and an empty `default_datasets` map. Each build is published once into its own folder, `releases/microcosm-uk-2024-25-dense//`, -through the emitter, and becomes the dense release's current build when it is -published; `releases.json` keeps the national release as the repository's -default. It is registered as `("uk", 2025, "dense")` in the private repo +through the emitter, and becomes the dense release's current build: by a +promotion once the older `latest*.json` pointer files are deleted, and when it +is published after that (see [§5](#5-publish-human-step)); `releases.json` +keeps the national release as the repository's default. It is registered as `("uk", 2025, "dense")` in the private repo `policyengine/populace-uk-private`. Publication is a separate human step. Since microcosm#1124 (ruling of 2026-10-13, amended for microcosm#1301) the line may ship the 150,000-household exact-k selection from that pool instead @@ -591,27 +592,50 @@ existing approvals have not been widened or renewed. ## 5. Publish (human step) -Run the printed command. Its shape is: +The assembler prints two commands. Run its `publish_command` first. Its shape +is: ```bash uv run microcosm-publish-release-build releases/microcosm-uk-2024-25-dense \ - --repo-id policyengine/populace-uk-private --artifact-root \ - --make-current + --repo-id policyengine/populace-uk-private --artifact-root ``` -It checks the build against the release contract again and hands every file -to the separately installed emitter with its role and SHA-256. The emitter -writes the build's folder and `releases.json` in one commit. The command -succeeds only when the receipt is `published` and names this build as -`current`; a change to the dense release's current build requested after -this one can land first and leave another build current. Running the same -command again is safe: an already published build with the same release -manifest is reported `published`. +It refuses at once, before it starts an emitter, when `HF_HUB_OFFLINE` or +`TRANSFORMERS_OFFLINE` is set, since the emitter inherits them and could not +reach the Hub. It checks the build against the release contract again, starts +the emitter, and hands nothing over unless the emitter's write-access check +finds a credential that can write the repository. It then hands every file to +the emitter with its role and SHA-256. The emitter writes the build's folder +and `releases.json` in one commit, listing the build without making it +current. The command prints the receipt: `status` is `published`, `pending` +(the emitter is still trying, and keeps the change queued for an hour), +`refused` with an `error_code`, or `unavailable` (no emitter answered). It +succeeds only on `published`. Running the same command again is safe: an +already published build with the same release manifest is reported +`published`. + +Each new dense build then becomes the dense release's current build with the +assembler's `promote_command`: + +```bash +uv run microcosm-publish-release-build releases/microcosm-uk-2024-25-dense \ + --repo-id policyengine/populace-uk-private --promote +``` While the repository still holds the older `latest*.json` pointer files, the emitter refuses every change to a release's current build -(`POINTER_FILES_PRESENT`). Until those files are deleted, publish without -`--make-current`, and make the build current later with `--promote`. +(`POINTER_FILES_PRESENT`), so that the pointer files and `releases.json` +cannot disagree. Until they are deleted, the promotion is refused at once, +changes nothing and says to run it again; the published build stays listed. +Run `promote_command` once they are deleted. The promotion succeeds only when +the receipt is `published` and names this build as `current`; a change to the +dense release's current build requested after this one can land first and +leave another build current. + +Once the pointer files are deleted, a new dense build can instead be published +as current in one commit by adding `--make-current` to `publish_command`. Do +not add it before then: the emitter refuses the whole publication, after the +dataset is hashed on both sides, and nothing is published. A contract warning reaches the command's stderr, and `--preflight-only` adds it to its verdict under `contract_warnings`. Neither refuses on one. No dense diff --git a/docs/uk-national-release-assembly-runbook-806.md b/docs/uk-national-release-assembly-runbook-806.md index df1cc500f9..1aff4f24a9 100644 --- a/docs/uk-national-release-assembly-runbook-806.md +++ b/docs/uk-national-release-assembly-runbook-806.md @@ -177,12 +177,17 @@ uv run microcosm-publish-release-build \ --artifact-root ``` -It checks the build against the release contract again, then hands every +It refuses at once, before it starts an emitter, when `HF_HUB_OFFLINE` or +`TRANSFORMERS_OFFLINE` is set, since the emitter inherits them and could not +reach the Hub. It checks the build against the release contract again, +starts the emitter, and hands nothing over unless the emitter's write-access +check finds a credential that can write the repository. It then hands every file to the emitter with its role and SHA-256. The emitter writes the build's folder and `releases.json` in one commit, listing the build without making it current. The command waits for the emitter's answer and prints its receipt: `status` is `published`, `pending` (the emitter is still trying, and -keeps the change queued for an hour) or `refused` with an `error_code`. +keeps the change queued for an hour), `refused` with an `error_code`, or +`unavailable` (no emitter answered). Running the same command again is safe: a build already published with the same release manifest is reported `published`, and one published with a different manifest is refused (`BUILD_FOLDER_EXISTS`), since a build is never @@ -225,7 +230,9 @@ While the repository still holds the older `latest*.json` pointer files, the emitter refuses every change to a release's current build (`POINTER_FILES_PRESENT`), so that the pointer files and `releases.json` cannot disagree. Until those files are deleted, a build can be published but -not made current. +not made current: the promotion is refused at once, changes nothing and says +to run it again, and the published build stays listed. Run `promote_command` +again once they are deleted. The 2025 national release is the default UK load (microcosm#823): `microcosm.data.load("uk")` and `microcosm.data.load("uk", 2025)` read its diff --git a/packages/microcosm-data/README.md b/packages/microcosm-data/README.md index a0f9cd105d..1f9db0d4bd 100644 --- a/packages/microcosm-data/README.md +++ b/packages/microcosm-data/README.md @@ -24,11 +24,12 @@ sim.calculate("household_net_income", 2024).sum() tag, verifies the artifact SHA-256, and refuses model or Core versions outside the release's certified compatibility specifiers. -A UK release publishes each build into its own folder, -`releases///`, and the repository's `releases.json` records -which build of each release is current. `load("uk")` reads that record, then +The UK national, dense and local-area releases publish each build into its +own folder, `releases///`, and the repository's +`releases.json` records which build of each release is current. `load("uk")` +(the 2025 national release) and the 2025 dense variant read that record, then the current build's `release_manifest.json`, then the dataset it names, all -from the build's folder, and checks the SHA-256 and engine versions the same +from the build's folder, and check the SHA-256 and engine versions the same way. `load("uk", build="")` loads a listed build instead (a withdrawn one with a warning). `available()` lists the default-variant `(country, year)` pairs (the ones a bare ``load(country, year)`` @@ -77,8 +78,9 @@ benchmark comparisons live outside this package. ## Release contract -Published US releases live under `releases//` in the Hub dataset -repo, and UK release builds under `releases///`. +Published US releases, and the UK releases that keep tags, live under +`releases//` in the Hub dataset repo, and builds of the UK +national, dense and local-area releases under `releases///`. Each release must include `build_manifest.json` and `release_manifest.json`; US releases must also include `us_source_coverage.json`. A current release manifest contains a typed `calibration_diagnostics` status. `available` binds a diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index 99d82f3e3c..16b68f1156 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -851,7 +851,7 @@ def line_for_release_id(release_id: str) -> str | None: """Return the ```` name of the ``latest-.json`` pointer file. Each such pointer file named the current build of one UK release before - UK releases published into build folders: ``national`` for the national + those releases published into build folders: ``national`` for the national release and ``local-k`` for a local-area one. Only the pointer reader still needs it. """ diff --git a/packages/microcosm-data/src/microcosm/data/loader.py b/packages/microcosm-data/src/microcosm/data/loader.py index 0e1fd7379c..8639b73d59 100644 --- a/packages/microcosm-data/src/microcosm/data/loader.py +++ b/packages/microcosm-data/src/microcosm/data/loader.py @@ -1,18 +1,19 @@ """Resolve, verify, download, and load a certified microcosm release. -A release whose builds publish into their own folders (every UK release in -the registry) is read through the repository's ``releases.json``: the record -names the release's current build (or ``build=`` pins a listed one), the -loader reads ``releases///release_manifest.json``, downloads -the dataset that manifest names from the same folder, verifies its SHA-256, -and enforces the certified model/Core versions before constructing the engine -dataset. Build folders never change after publishing, so every file is read -at ``main``. - -A release that keeps the tagged layout (every US release) follows the -repository's release certificate: resolve the registry-selected pointer, read -that release's manifest at the pointer's immutable revision, download the -manifest-selected dataset at the same revision and check it the same way. +A release whose builds publish into their own folders (the registry's UK +2025 national and dense entries) is read through the repository's +``releases.json``: the record names the release's current build (or +``build=`` pins a listed one), the loader reads +``releases///release_manifest.json``, downloads the dataset +that manifest names from the same folder, verifies its SHA-256, and enforces +the certified model/Core versions before constructing the engine dataset. +Build folders never change after publishing, so every file is read at +``main``. + +A release that keeps the tagged layout (every US entry, and UK 2023) follows +the repository's release certificate: resolve the registry-selected pointer, +read that release's manifest at the pointer's immutable revision, download +the manifest-selected dataset at the same revision and check it the same way. Its mutable root artifacts are available only through the explicitly unsafe ``load(..., unverified_root=True)`` escape hatch; a build-folder release has no root file. diff --git a/packages/microcosm-data/src/microcosm/data/publish_cli.py b/packages/microcosm-data/src/microcosm/data/publish_cli.py index 4ed74a81ec..be507a4ffa 100644 --- a/packages/microcosm-data/src/microcosm/data/publish_cli.py +++ b/packages/microcosm-data/src/microcosm/data/publish_cli.py @@ -1,8 +1,10 @@ """CLI for contract-checked Microcosm release publication. It publishes releases that keep the tagged layout and ``latest.json``: every -US release. A UK release publishes each build into its own folder through the -emitter (``microcosm-publish-release-build``), and this command refuses it. +US release, the June 2023 UK release and ``populace-uk---k`` +releases. The UK national, dense and local-area releases publish each build +into its own folder through the emitter (``microcosm-publish-release-build``), +and this command refuses them. """ from __future__ import annotations diff --git a/packages/microcosm-data/src/microcosm/data/release.py b/packages/microcosm-data/src/microcosm/data/release.py index 288189f2c8..a10ebbc30c 100644 --- a/packages/microcosm-data/src/microcosm/data/release.py +++ b/packages/microcosm-data/src/microcosm/data/release.py @@ -1,14 +1,16 @@ """Publish a release and move its approved repository pointer. -**UK releases no longer publish here.** The UK national, dense and -local-area releases publish each build into its own folder, +**The UK national, dense and local-area releases no longer publish +here.** They publish each build into its own folder, ``releases///``, through the emitter's ``publish_release`` call (``microcosm-publish-release-build``, in ``microcosm-build``), and the repository's ``releases.json`` records which build is current. :func:`prepare_build_folder_release` checks such a build and lists its files with their roles; :func:`prepare_release` and :func:`publish_release` refuse -it. Everything below describes the tagged layout the US releases keep until -the stable releases US builds publish under are agreed. +it. Everything below describes the tagged layout the other releases keep: +every US release, until the stable releases US builds publish under are +agreed, and the June 2023 UK release and ``populace-uk---k`` +releases. The Hub repo publishes builds under ``releases//``, but nothing identified which release is *current*: a consumer had to list the tree and @@ -29,10 +31,11 @@ returns the typed pointer, the one-call answer to "which release is current?" for dashboards and scorers. -UK releases were made current through pointer files named -``latest-.json``. Those schema-1 pointers add the fields ``line`` and -``revision``, so each could name an immutable per-build tag without changing -the frozen repository-global ``latest.json``. Nothing writes them any more; +The UK national and local-area releases were made current through pointer +files named ``latest-.json``. Those schema-1 pointers add the fields +``line`` and ``revision``, so each could name an immutable per-build tag +without changing the frozen repository-global ``latest.json``. Nothing +writes them any more; :func:`latest_line_release` still reads them until they are deleted. The EVIDENCE tier (microcosm#506) publishes through the same producer with @@ -756,8 +759,9 @@ def publish_release( ) -> dict: """Publish a release directory and optionally point ``latest.json`` at it. - A release that publishes into build folders (every UK release) is - refused before any check or Hub call; see the module docstring. + A release that publishes into build folders (the UK national, dense + and local-area releases) is refused before any check or Hub call; see + the module docstring. The order is the guarantee: the release contract is validated first (an invalid release never reaches the Hub), then an immutable branch commit is diff --git a/tools/publish_release.sh b/tools/publish_release.sh index 665c6e4881..098a4441f6 100755 --- a/tools/publish_release.sh +++ b/tools/publish_release.sh @@ -1,11 +1,13 @@ #!/usr/bin/env bash # # Publish a Microcosm release that keeps tags and latest.json (every US -# release) and fire its Slack alert, in one tracked path. +# release, the June 2023 UK release and populace-uk---k +# releases) and fire its Slack alert, in one tracked path. # -# UK releases publish each build into its own folder through the emitter -# with `microcosm-publish-release-build` instead; `microcosm-publish-release` -# refuses them, and they send no Slack alert. +# The UK national, dense and local-area releases publish each build into its +# own folder through the emitter with `microcosm-publish-release-build` +# instead; `microcosm-publish-release` refuses them, and they send no Slack +# alert until the dashboard posts one from releases.json. # # Thin wrapper around `microcosm-publish-release` so that every ship goes # through the same command and the release alert is guaranteed to be wired. @@ -19,7 +21,7 @@ # # One-time setup on the build machine (see README "Releasing & alerts"): # cp tools/release.env.example tools/release.env # then fill in the URLs -# or just export SLACK_WEBHOOK_POPULACE_US in your shell. +# or just export SLACK_WEBHOOK_POPULACE_US / _UK in your shell. set -euo pipefail @@ -31,8 +33,8 @@ if [[ -f "$ENV_FILE" ]]; then set +a fi -if [[ -z "${SLACK_WEBHOOK_POPULACE_US:-}" ]]; then - echo "warning: no SLACK_WEBHOOK_POPULACE_US set — this release will" >&2 +if [[ -z "${SLACK_WEBHOOK_POPULACE_US:-}" && -z "${SLACK_WEBHOOK_POPULACE_UK:-}" ]]; then + echo "warning: no SLACK_WEBHOOK_POPULACE_US/_UK set — this release will" >&2 echo " publish WITHOUT a Slack alert. Set them in your shell or in" >&2 echo " $ENV_FILE (see README 'Releasing & alerts')." >&2 fi diff --git a/tools/release.env.example b/tools/release.env.example index 072843a849..49d319df6e 100644 --- a/tools/release.env.example +++ b/tools/release.env.example @@ -1,16 +1,20 @@ # Release alert configuration for tools/publish_release.sh. # # Copy this file to tools/release.env (gitignored) on the build machine and -# paste the Slack *incoming webhook* URL for #populace-us. Once set, every -# `tools/publish_release.sh …` (and any direct `microcosm-publish-release`) -# posts a release alert there. UK releases publish into build folders through +# paste the Slack *incoming webhook* URLs for #populace-us and #populace-uk. +# Once set, every `tools/publish_release.sh …` (and any direct +# `microcosm-publish-release`) posts a release alert to the matching channel. +# Those are the releases that keep tags and latest.json: every US release, the +# June 2023 UK release and populace-uk---k releases. The UK +# national, dense and local-area releases publish into build folders through # the emitter and send no alert from here. # # cp tools/release.env.example tools/release.env # -# Leave it blank to skip the alerts. +# Leave a line blank to skip alerts for that country. export SLACK_WEBHOOK_POPULACE_US= +export SLACK_WEBHOOK_POPULACE_UK= # Canonical UK exact-k terminal reports are authenticated with a stable # 32-byte release key encoded as base64. Generate and store this once on the From 666dfbd9036703fb14a344545fd65871013678fe Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:36:30 +0400 Subject: [PATCH 13/26] Test that the UK contract accepts the tagged layout until the switch UK releases keep publishing through the tagged publisher and the pointer files until their repository switches to releases.json, so the contract must accept the national, dense and local-area releases in the tagged layout again. These are main's tests for that layout, beside the build-folder tests, which now build their fixtures in that layout explicitly. The test that a UK release refuses the tagged layout moves to the switch. Part of the split for the switch: reverting this commit and the next one re-applies the contract's build-folder-only rule for UK releases. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_gate_battery_contract_pins.py | 7 +- .../tests/engine_free/shared/test_contract.py | 115 +++++++++++++----- .../shared/test_local_area_contract.py | 24 ++-- .../uk/test_uk_dense_release_contract.py | 55 ++++++--- 4 files changed, 142 insertions(+), 59 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py b/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py index 90e0711609..e2661ef8ff 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_gate_battery_contract_pins.py @@ -385,9 +385,10 @@ def test_release_id_mirrors_the_build_shard(self) -> None: from microcosm.build.uk_runtime.release_identity import UK_DENSE_RELEASE_ID assert data_contract._UK_DENSE_RELEASE_ID == UK_DENSE_RELEASE_ID - # Its builds publish into their own folders, with no tag to match. - assert data_contract.publishes_to_build_folder(UK_DENSE_RELEASE_ID) - assert not hasattr(data_contract, "_UK_DENSE_CUT_TAG_RE") + assert data_contract._UK_DENSE_CUT_TAG_RE.fullmatch( + f"{UK_DENSE_RELEASE_ID}-20260903T105422Z-ca611e43" + ) + assert data_contract._UK_DENSE_CUT_TAG_RE.fullmatch(UK_DENSE_RELEASE_ID) is None def test_dataset_filename_mirrors_the_assembler(self) -> None: import importlib.util diff --git a/packages/microcosm-data/tests/engine_free/shared/test_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_contract.py index b196b4d7fc..2cd9d8e39e 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_contract.py @@ -54,6 +54,7 @@ UK_RELEASE_ID = "populace-uk-2023-dd68c73-4aa4b14-20260619T023711Z" UK_EXACT_K_RELEASE_ID = "populace-uk-2023-frs-k535080" UK_NATIONAL_RELEASE_ID = "microcosm-uk-2024-25-national" +UK_NATIONAL_CUT_TAG = f"{UK_NATIONAL_RELEASE_ID}-20260828T101112Z-1a2b3c4d" UK_RECORD_COUNT = 535_080 UK_TERMINAL_GATE_REPORT_FILE = "terminal_gates.json" UK_TERMINAL_GATE_PRODUCER = ( @@ -1771,18 +1772,22 @@ def _copy_real_uk_june_release(tmp_path: Path) -> Path: def _write_uk_national_release_dir(tmp_path: Path) -> Path: - """Build the national fixture from the green exact-k shape. - - The national release publishes each build into its own folder, so the - fixture's manifests name the release and the build in that layout. - """ + """Build the constant-id national fixture from the green exact-k shape.""" directory = _write_uk_release_dir(tmp_path, UK_EXACT_K_RELEASE_ID, tier="frs") national = directory.with_name(UK_NATIONAL_RELEASE_ID) directory.replace(national) + build_path = national / "build_manifest.json" + build = json.loads(build_path.read_text()) + build["build_id"] = UK_NATIONAL_RELEASE_ID + build_path.write_text(json.dumps(build)) + release_path = national / "release_manifest.json" release = json.loads(release_path.read_text()) + release["build"]["build_id"] = UK_NATIONAL_RELEASE_ID + for artifact in release["artifacts"].values(): + artifact["revision"] = UK_NATIONAL_CUT_TAG # The certification signs the evidence copies' actual bytes: the seam # report already sits in the directory (terminal_gates.json from the @@ -1812,11 +1817,11 @@ def _write_uk_national_release_dir(tmp_path: Path) -> Path: "kind": "diagnostics", "path": "release_certification.json", "repo_id": "policyengine/populace-uk-private", - "revision": UK_EXACT_K_RELEASE_ID, + "revision": UK_NATIONAL_CUT_TAG, "sha256": _sha256(certification_path), } release_path.write_text(json.dumps(release)) - return to_build_folder_layout(national, build=UK_NATIONAL_BUILD) + return national def _rewrite_exact_k_fixture_to_two_records(directory: Path) -> None: @@ -2486,7 +2491,7 @@ def test_uk_national_release_requires_policyengine_uk_model_pin( directory = _write_uk_national_release_dir(tmp_path) release_path = directory / "release_manifest.json" release = json.loads(release_path.read_text()) - release["built_with_model_package"]["name"] = "policyengine-us" + release["build"]["built_with_model_package"]["name"] = "policyengine-us" release_path.write_text(json.dumps(release)) with pytest.raises( @@ -2496,6 +2501,66 @@ def test_uk_national_release_requires_policyengine_uk_model_pin( validate_release_dir(directory) +@pytest.mark.parametrize( + "revision", + [ + "main", + UK_NATIONAL_RELEASE_ID + "-", + # Prefixed but outside the attempt-derived cut-tag grammar: the + # contract validates the same - shape the + # assembler mints, so a hand-edited suffix cannot claim a cut. + UK_NATIONAL_RELEASE_ID + "-hotfix", + UK_NATIONAL_RELEASE_ID + "-20260828t101112Z-1a2b3c4d", + UK_NATIONAL_RELEASE_ID + "-20260828T101112Z-1A2B3C4D", + # Present but non-string: must fail loudly rather than vanish from + # the publish layer's string-only revision collection. + 123, + ], +) +def test_uk_national_release_rejects_invalid_artifact_revisions( + tmp_path: Path, + revision: str, +) -> None: + directory = _write_uk_national_release_dir(tmp_path) + release_path = directory / "release_manifest.json" + release = json.loads(release_path.read_text()) + for artifact in release["artifacts"].values(): + artifact["revision"] = revision + release_path.write_text(json.dumps(release)) + + with pytest.raises(ReleaseContractError, match="revision"): + validate_release_dir(directory) + + +def test_uk_national_release_rejects_mixed_cut_revisions(tmp_path: Path) -> None: + # Two individually grammar-valid cut tags are still two cuts: the + # contract refuses the mixture, not just publish. + directory = _write_uk_national_release_dir(tmp_path) + release_path = directory / "release_manifest.json" + release = json.loads(release_path.read_text()) + first_key = next(iter(release["artifacts"])) + release["artifacts"][first_key]["revision"] = ( + UK_NATIONAL_RELEASE_ID + "-20260901T000000Z-deadbeef" + ) + release_path.write_text(json.dumps(release)) + + with pytest.raises(ReleaseContractError, match="more than one revision"): + validate_release_dir(directory) + + +def _write_uk_national_build_folder_release_dir(tmp_path: Path) -> Path: + """The national fixture in the build-folder layout. + + Until the repository switches to releases.json the national release is + assembled with tags; the contract also checks the build-folder layout + the emitter's publication uses, whose manifests name the release and the + build. + """ + return to_build_folder_layout( + _write_uk_national_release_dir(tmp_path), build=UK_NATIONAL_BUILD + ) + + @pytest.mark.parametrize( ("release_id", "publishes"), [ @@ -2571,7 +2636,7 @@ def _uk_national_failures(directory: Path) -> str: def test_uk_national_build_folder_manifests_name_the_release_and_the_build( tmp_path: Path, ) -> None: - directory = _write_uk_national_release_dir(tmp_path) + directory = _write_uk_national_build_folder_release_dir(tmp_path) release = json.loads((directory / "release_manifest.json").read_text()) build = json.loads((directory / "build_manifest.json").read_text()) @@ -2586,27 +2651,11 @@ def test_uk_national_build_folder_manifests_name_the_release_and_the_build( validate_release_dir(directory) -def test_uk_national_build_folder_refuses_the_tagged_manifest_shape( - tmp_path: Path, -) -> None: - directory = _write_uk_national_release_dir(tmp_path) - - def tagged(release: dict) -> None: - release["build"] = { - "build_id": UK_NATIONAL_RELEASE_ID, - "cut_tag": f"{UK_NATIONAL_RELEASE_ID}-20260920T120000Z-deadbeef", - } - - _rewrite_document(directory / "release_manifest.json", tagged) - - assert "'build' must be the build's name" in _uk_national_failures(directory) - - @pytest.mark.parametrize("field", ["build_id", "attempt_id", "cut_tag"]) def test_uk_national_build_folder_refuses_the_retired_build_fields( tmp_path: Path, field: str ) -> None: - directory = _write_uk_national_release_dir(tmp_path) + directory = _write_uk_national_build_folder_release_dir(tmp_path) _rewrite_document( directory / "build_manifest.json", lambda build: build.update({field: UK_NATIONAL_RELEASE_ID}), @@ -2619,7 +2668,7 @@ def test_uk_national_build_folder_refuses_the_retired_build_fields( def test_uk_national_build_folder_release_must_be_the_directory( tmp_path: Path, manifest: str ) -> None: - directory = _write_uk_national_release_dir(tmp_path) + directory = _write_uk_national_build_folder_release_dir(tmp_path) _rewrite_document( directory / manifest, lambda document: document.update(release="microcosm-uk-2024-25-dense"), @@ -2634,7 +2683,7 @@ def test_uk_national_build_folder_release_must_be_the_directory( def test_uk_national_build_folder_build_must_be_a_safe_name( tmp_path: Path, build: object ) -> None: - directory = _write_uk_national_release_dir(tmp_path) + directory = _write_uk_national_build_folder_release_dir(tmp_path) for manifest in ("build_manifest.json", "release_manifest.json"): _rewrite_document( directory / manifest, lambda document: document.update(build=build) @@ -2646,7 +2695,7 @@ def test_uk_national_build_folder_build_must_be_a_safe_name( def test_uk_national_build_folder_manifests_must_name_the_same_build( tmp_path: Path, ) -> None: - directory = _write_uk_national_release_dir(tmp_path) + directory = _write_uk_national_build_folder_release_dir(tmp_path) _rewrite_document( directory / "build_manifest.json", lambda build: build.update( @@ -2665,7 +2714,7 @@ def test_uk_national_build_folder_manifests_must_name_the_same_build( def test_uk_national_build_folder_records_build_details_at_the_top_level( tmp_path: Path, field: str ) -> None: - directory = _write_uk_national_release_dir(tmp_path) + directory = _write_uk_national_build_folder_release_dir(tmp_path) _rewrite_document( directory / "release_manifest.json", lambda release: release.pop(field) ) @@ -2676,7 +2725,7 @@ def test_uk_national_build_folder_records_build_details_at_the_top_level( def test_uk_national_build_folder_refuses_an_artifact_revision( tmp_path: Path, ) -> None: - directory = _write_uk_national_release_dir(tmp_path) + directory = _write_uk_national_build_folder_release_dir(tmp_path) def pin(release: dict) -> None: release["artifacts"]["calibration_diagnostics"]["revision"] = "main" @@ -2698,7 +2747,7 @@ def pin(release: dict) -> None: def test_uk_national_build_folder_names_each_artifact_role( tmp_path: Path, role: str | None, message: str ) -> None: - directory = _write_uk_national_release_dir(tmp_path) + directory = _write_uk_national_build_folder_release_dir(tmp_path) def set_role(release: dict) -> None: artifact = release["artifacts"]["calibration_diagnostics"] @@ -2718,7 +2767,7 @@ def set_role(release: dict) -> None: def test_uk_national_build_folder_artifact_paths_are_bare_file_names( tmp_path: Path, path: str ) -> None: - directory = _write_uk_national_release_dir(tmp_path) + directory = _write_uk_national_build_folder_release_dir(tmp_path) def move(release: dict) -> None: release["artifacts"]["release_certification"]["path"] = path diff --git a/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py b/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py index c7bb873f2e..cf6584af27 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_local_area_contract.py @@ -109,16 +109,18 @@ def _write_local_bundle( extra_gates: dict | None = None, spm_measurement_gate: object = _DEFAULT, build_manifest_spm_measurement_gate: object = _DEFAULT, + build_folder: bool = False, ) -> Path: """A local-area release directory the contract accepts by default. A US id gets the package stage's stored-input and SPM measurement gates in ``gate_summary.json`` and ``build_manifest.json`` and the built-with engine they name; a UK id gets none of them, as the UK lanes write none. - ``None`` omits a piece, and a value replaces it. A UK local-area release - publishes each build into its own folder, so its manifests name the - release and the build (``UK_LOCAL_BUILD``) and record its UK built-with - packages at the top level. + ``None`` omits a piece, and a value replaces it. With ``build_folder``, + a UK local-area bundle is written in the build-folder layout the + emitter's publication uses: its manifests name the release and the build + (``UK_LOCAL_BUILD``) and record its UK built-with packages at the top + level. """ release_dir = root / "releases" / release_id release_dir.mkdir(parents=True) @@ -252,7 +254,7 @@ def _write_local_bundle( }, "reviewed_limitations": [{"id": "cd_population_marginal_vintage_2020"}], } - if release_id.startswith("microcosm-uk-2024-25-"): + if build_folder: manifest = _as_uk_build_folder(manifest, release_id=release_id) payloads["build_manifest.json"] = json.dumps( build_folder_build_manifest( @@ -296,7 +298,9 @@ def _as_uk_build_folder(manifest: dict, *, release_id: str) -> dict: def test_uk_local_area_bundle_publishes_in_the_build_folder_layout( tmp_path: Path, ) -> None: - release_dir = _write_local_bundle(tmp_path, release_id=UK_LOCAL_RELEASE_ID) + release_dir = _write_local_bundle( + tmp_path, release_id=UK_LOCAL_RELEASE_ID, build_folder=True + ) manifest = json.loads((release_dir / "release_manifest.json").read_text()) build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) @@ -311,8 +315,12 @@ def test_uk_local_area_bundle_publishes_in_the_build_folder_layout( validate_release_dir(release_dir) -def test_uk_local_area_bundle_refuses_the_tagged_layout(tmp_path: Path) -> None: - release_dir = _write_local_bundle(tmp_path, release_id=UK_LOCAL_RELEASE_ID) +def test_uk_local_area_build_folder_refuses_a_retired_build_field( + tmp_path: Path, +) -> None: + release_dir = _write_local_bundle( + tmp_path, release_id=UK_LOCAL_RELEASE_ID, build_folder=True + ) build_manifest_path = release_dir / "build_manifest.json" build_manifest = json.loads(build_manifest_path.read_text()) build_manifest["build_id"] = UK_LOCAL_RELEASE_ID diff --git a/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py b/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py index c80606616e..37e9cec18b 100644 --- a/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py +++ b/packages/microcosm-data/tests/engine_free/uk/test_uk_dense_release_contract.py @@ -19,6 +19,7 @@ ) DENSE_ID = "microcosm-uk-2024-25-dense" +CUT_TAG = f"{DENSE_ID}-20260903T105422Z-ca611e43" #: The calibration attempt the signed report is bound to: the dense build. DENSE_BUILD = "uk-local-candidate-f100-s42-20260903T105422Z-ca611e43" KEY = base64.b64encode(b"\x07" * 32).decode() @@ -129,6 +130,7 @@ def write_dense_bundle( holdout: str = "skipped", sized: bool = False, national_exclusions: tuple[str, ...] = (), + build_folder: bool = False, ) -> Path: """A synthetic dense release directory. @@ -143,13 +145,14 @@ def write_dense_bundle( the candidate manifest records the target-fit and input-mass names under ``reviewed_exclusions_stood_on``, as the build does. - A release in the build-folder layout (the dense release) names its - ``build``, the signed report's attempt unless ``build`` says otherwise, in - both manifests, and pins no artifact ``revision`` unless ``revision`` asks - for one. Any other release ID gets the tagged layout, pinned to - ``revision`` or the release ID. + By default it is in the tagged layout the dense assembler writes until + the repository switches to releases.json: the build manifest names the + signed report's attempt (``build`` names another) as ``attempt_id``, and + each artifact is pinned to ``revision`` or the per-build tag. With + ``build_folder`` it is in the layout the emitter's publication uses: both + manifests name the release and the build, and no artifact pins a + ``revision`` unless ``revision`` asks for one. """ - build_folder = release_id.startswith("microcosm-uk-2024-25-") release_dir = root / "releases" / release_id release_dir.mkdir(parents=True) report = report or _signed_report() @@ -398,7 +401,7 @@ def write_dense_bundle( h5_bytes = b"dense-h5-stand-in" (root / "microcosm_uk_2024_25_dense.h5").write_bytes(h5_bytes) - pinned = revision if revision is not None or build_folder else release_id + pinned = revision if revision is not None or build_folder else CUT_TAG def artifact(kind, path, sha, role): entry = { @@ -792,10 +795,14 @@ def test_dense_bundle_rejects_stale_ledger_identity_key(tmp_path: Path) -> None: assert "identity.targets.chronicle" in _failures(release_dir) +def test_dense_bundle_accepts_the_release_id_as_revision(tmp_path: Path) -> None: + validate_release_dir(write_dense_bundle(tmp_path, revision=DENSE_ID)) + + def test_dense_bundle_names_its_release_and_build_in_both_manifests( tmp_path: Path, ) -> None: - release_dir = write_dense_bundle(tmp_path) + release_dir = write_dense_bundle(tmp_path, build_folder=True) for name in ("build_manifest.json", "release_manifest.json"): manifest = json.loads((release_dir / name).read_text()) assert (manifest["release"], manifest["build"]) == (DENSE_ID, DENSE_BUILD) @@ -808,9 +815,13 @@ def _failures(release_dir: Path) -> str: return str(excinfo.value) +def test_unpinned_revision_is_rejected(tmp_path: Path) -> None: + assert "not pinned" in _failures(write_dense_bundle(tmp_path, revision="main")) + + @pytest.mark.parametrize("revision", ["main", DENSE_ID]) def test_a_pinned_revision_is_rejected(tmp_path: Path, revision: str) -> None: - text = _failures(write_dense_bundle(tmp_path, revision=revision)) + text = _failures(write_dense_bundle(tmp_path, revision=revision, build_folder=True)) assert f"pins revision {revision!r}" in text @@ -880,7 +891,11 @@ def test_missing_key_env_names_the_hole(tmp_path: Path, monkeypatch) -> None: def test_other_local_area_ids_keep_the_generic_contract(tmp_path: Path) -> None: # A non-dense local-area id never reaches the dense validator. - release_dir = write_dense_bundle(tmp_path, release_id="populace-uk-2025-frs-k9") + release_dir = write_dense_bundle( + tmp_path, + release_id="populace-uk-2025-frs-k9", + revision="populace-uk-2025-frs-k9", + ) text = _failures(release_dir) assert "us_source_coverage.json" in text @@ -892,9 +907,19 @@ def test_report_from_another_attempt_is_rejected(tmp_path: Path) -> None: assert "does not belong to this run" in _failures(release_dir) -def test_build_manifest_without_its_build_is_rejected(tmp_path: Path) -> None: +def test_build_manifest_without_attempt_id_is_rejected(tmp_path: Path) -> None: release_dir = write_dense_bundle(tmp_path) build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) + del build_manifest["attempt_id"] + (release_dir / "build_manifest.json").write_text( + json.dumps(build_manifest, indent=1) + ) + assert "must carry the calibration 'attempt_id'" in _failures(release_dir) + + +def test_build_manifest_without_its_build_is_rejected(tmp_path: Path) -> None: + release_dir = write_dense_bundle(tmp_path, build_folder=True) + build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) del build_manifest["build"] (release_dir / "build_manifest.json").write_text( json.dumps(build_manifest, indent=1) @@ -907,7 +932,7 @@ def test_build_manifest_without_its_build_is_rejected(tmp_path: Path) -> None: def test_a_build_manifest_with_a_retired_build_field_is_rejected( tmp_path: Path, field: str ) -> None: - release_dir = write_dense_bundle(tmp_path) + release_dir = write_dense_bundle(tmp_path, build_folder=True) build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) build_manifest[field] = DENSE_BUILD (release_dir / "build_manifest.json").write_text( @@ -917,7 +942,7 @@ def test_a_build_manifest_with_a_retired_build_field_is_rejected( def test_a_release_manifest_naming_another_build_is_rejected(tmp_path: Path) -> None: - release_dir = write_dense_bundle(tmp_path) + release_dir = write_dense_bundle(tmp_path, build_folder=True) manifest = json.loads((release_dir / "release_manifest.json").read_text()) manifest["build"] = "uk-local-candidate-f100-s42-20260101T000000Z-00000000" (release_dir / "release_manifest.json").write_text(json.dumps(manifest, indent=1)) @@ -930,7 +955,7 @@ def test_a_dense_release_keeps_the_local_area_package_checks(tmp_path: Path) -> still checks only that they are there, as it did inside ``build``: a build run where the engines were not installed, whose versions read ``unavailable``, validates as before.""" - release_dir = write_dense_bundle(tmp_path) + release_dir = write_dense_bundle(tmp_path, build_folder=True) manifest = json.loads((release_dir / "release_manifest.json").read_text()) for field in ("built_with_core_package", "built_with_model_package"): manifest[field]["version"] = "unavailable" @@ -948,7 +973,7 @@ def test_a_dense_release_keeps_the_local_area_package_checks(tmp_path: Path) -> def test_a_dense_release_records_its_build_details_at_the_top_level( tmp_path: Path, field: str ) -> None: - release_dir = write_dense_bundle(tmp_path) + release_dir = write_dense_bundle(tmp_path, build_folder=True) manifest = json.loads((release_dir / "release_manifest.json").read_text()) del manifest[field] (release_dir / "release_manifest.json").write_text(json.dumps(manifest, indent=1)) From 660873b3af8ae827312bc8343bcaede9ed09d626 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:39:10 +0400 Subject: [PATCH 14/26] Accept the tagged layout for UK releases until the switch The contract checks a UK national, dense or local-area release in the layout its release manifest uses: the tagged layout today's assemblers write, with its per-build tags and the dense release's attempt_id, or the build-folder layout the emitter's publication uses. Every other release stays tagged. dataset_role_for_line and the dense per-build tag pattern, which the tagged path reads, come back. Part of the split for the switch: reverting this commit and the one before re-applies the build-folder-only rule for UK releases. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/data/contract.py | 162 +++++++++++++++--- 1 file changed, 138 insertions(+), 24 deletions(-) diff --git a/packages/microcosm-data/src/microcosm/data/contract.py b/packages/microcosm-data/src/microcosm/data/contract.py index 16b68f1156..fa55ac9f53 100644 --- a/packages/microcosm-data/src/microcosm/data/contract.py +++ b/packages/microcosm-data/src/microcosm/data/contract.py @@ -40,7 +40,7 @@ import math import os import re -from collections.abc import Mapping +from collections.abc import Callable, Mapping from datetime import date from pathlib import Path from types import MappingProxyType @@ -247,6 +247,23 @@ def publishes_to_build_folder(release_id: str) -> bool: ) +def _build_folder_layout(release_id: str, release_manifest: object) -> bool: + """Whether a release directory is in the build-folder layout. + + Until its repository switches to ``releases.json``, a UK release is + assembled and published in the tagged layout, so the contract checks a + UK release in whichever layout its release manifest uses: a tagged + manifest describes the build in a ``build`` object, and a build-folder + one names it as a string there (anything else is checked, and refused, + as a build-folder manifest). Every other release is always tagged. + """ + return ( + publishes_to_build_folder(release_id) + and isinstance(release_manifest, Mapping) + and not isinstance(release_manifest.get("build"), Mapping) + ) + + def release_artifact_role(key: str, kind: object) -> str: """The role a build folder's manifest records for one artifact. @@ -863,12 +880,32 @@ def line_for_release_id(release_id: str) -> str | None: return None +def dataset_role_for_line(line: str) -> str: + """The one dataset role a publication line may carry. + + The national line publishes national-default releases; every local-area + line publishes non-default local-area releases. The publisher refuses a + line promotion whose manifest declares another role, and the loader + refuses a manifest that reached a line pointer with the wrong role, so a + local-area release can never ride the national pointer (or the reverse) + on the strength of its release id alone. + """ + if line == "national": + return NATIONAL_DEFAULT_DATASET_ROLE + if re.fullmatch(r"local-k[1-9][0-9]*", line): + return NON_DEFAULT_LOCAL_AREA_DATASET_ROLE + raise ValueError(f"{line!r} is not a publication line.") + + # The dense joint national + local line (microcosm#762 A18, ruling # 2026-09-03): the same constant-id approach, published on the inspect lane # under the non-default local-area role. Mirrored from # microcosm.build.uk_runtime.release_identity.UK_DENSE_RELEASE_ID; lockstep- # tested in test_gate_battery_contract_pins.py. _UK_DENSE_RELEASE_ID = "microcosm-uk-2024-25-dense" +_UK_DENSE_CUT_TAG_RE = re.compile( + re.escape(_UK_DENSE_RELEASE_ID) + r"-[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}" +) #: The dense line's published microdata filename; mirrors #: ``tools/assemble_uk_dense_release_dir.py::_DATASET_FILENAME`` (lockstep test #: in the build shard's contract-pin suite). @@ -1466,10 +1503,14 @@ def _check_build_folder_artifacts(artifacts: Mapping, failures: list[str]) -> No def _check_build_manifest( - manifest: Mapping, release_id: str, failures: list[str] + manifest: Mapping, + release_id: str, + failures: list[str], + *, + build_folder: bool = False, ) -> None: _check_base_pool_not_denied(manifest, failures) - if publishes_to_build_folder(release_id): + if build_folder: _check_build_folder_identity( manifest, release_id, filename="build_manifest.json", failures=failures ) @@ -1679,7 +1720,7 @@ def _check_release_manifest( f"this library publishes version " f"{expected_schema_version!r}." ) - build_folder = publishes_to_build_folder(release_id) + build_folder = _build_folder_layout(release_id, manifest) build = manifest.get("build") if build_folder: _check_build_folder_identity( @@ -1751,6 +1792,7 @@ def _check_release_manifest( _check_build_folder_artifacts(artifacts, failures) _check_default_dataset_artifact(default_datasets, artifacts, failures) else: + line_cut_tag_re = _uk_line_cut_tag_re(release_id) _check_calibration_diagnostics_declaration(manifest, artifacts, failures) for key, entry in artifacts.items(): if not isinstance(entry, Mapping): @@ -1764,8 +1806,14 @@ def _check_release_manifest( f"release_manifest.json artifact {key!r} is missing {field!r}." ) revision = entry.get("revision") - revision_matches_release = revision == release_id or ( - annual_revision is not None and revision == annual_revision + revision_matches_release = ( + revision == release_id + or (annual_revision is not None and revision == annual_revision) + or ( + line_cut_tag_re is not None + and isinstance(revision, str) + and line_cut_tag_re.fullmatch(revision) is not None + ) ) # A present-but-non-string revision must fail here rather than # slide past the isinstance guard: publish collects only string @@ -1774,9 +1822,15 @@ def _check_release_manifest( if revision and ( not isinstance(revision, str) or not revision_matches_release ): + expected = ( + f"the release id {release_id!r} or a " + f"'{release_id}--' per-cut tag" + if line_cut_tag_re is not None + else f"the release id {release_id!r}" + ) failures.append( f"release_manifest.json artifact {key!r} revision is " - f"{revision!r}, expected the release id {release_id!r}." + f"{revision!r}, expected {expected}." ) if isinstance(entry, Mapping): _check_sha256_field( @@ -4734,7 +4788,9 @@ def _validate_local_area_release_dir(release_dir: Path, release_id: str) -> None build_manifest_path = release_dir / "build_manifest.json" if build_manifest_path.is_file(): build_manifest = _load_json(build_manifest_path, failures) - if build_manifest is not None and publishes_to_build_folder(release_id): + if build_manifest is not None and _build_folder_layout( + release_id, release_manifest + ): _check_build_folder_identity( build_manifest, release_id, @@ -4869,8 +4925,17 @@ def _validate_uk_dense_release_dir(release_dir: Path, release_id: str) -> list[s incumbent_attached = _uk_dense_incumbent_attached( release_dir, release_manifest or {}, failures ) + build_folder = _build_folder_layout(release_id, release_manifest) if release_manifest is not None: - _check_local_area_release_manifest(release_manifest, release_id, failures) + _check_local_area_release_manifest( + release_manifest, + release_id, + failures, + revision_ok=lambda revision: ( + revision == release_id + or _UK_DENSE_CUT_TAG_RE.fullmatch(revision) is not None + ), + ) namespace = release_manifest.get("namespace") if namespace != _UK_DENSE_NAMESPACE: failures.append( @@ -4888,16 +4953,38 @@ def _validate_uk_dense_release_dir(release_dir: Path, release_id: str) -> list[s failures.append( "build_manifest.json code.git_dirty must be false for release." ) - _check_build_folder_identity( - build_manifest, - release_id, - filename="build_manifest.json", - failures=failures, + if build_folder: + _check_build_folder_identity( + build_manifest, + release_id, + filename="build_manifest.json", + failures=failures, + ) + _check_build_folder_builds_agree( + build_manifest, release_manifest, failures + ) + build = build_manifest.get("build") + if isinstance(build, str) and build: + attempt_id = build + else: + candidate_attempt = build_manifest.get("attempt_id") + if isinstance(candidate_attempt, str) and candidate_attempt: + attempt_id = candidate_attempt + else: + failures.append( + "build_manifest.json must carry the calibration " + "'attempt_id' the signed gate report is bound to." + ) + if ( + not build_folder + and build_manifest is not None + and build_manifest.get("build_id") != release_id + ): + failures.append( + "build_manifest.json 'build_id' is " + f"{build_manifest.get('build_id')!r} but the release directory " + f"is named {release_id!r}." ) - _check_build_folder_builds_agree(build_manifest, release_manifest, failures) - build = build_manifest.get("build") - if isinstance(build, str) and build: - attempt_id = build gate_path = release_dir / "gate_summary.json" if gate_path.is_file(): gate_summary = _load_json(gate_path, failures) @@ -5661,6 +5748,8 @@ def _check_local_area_release_manifest( manifest: Mapping, release_id: str, failures: list[str], + *, + revision_ok: Callable[[str], bool] | None = None, ) -> None: schema_version = manifest.get("schema_version") if schema_version != RELEASE_MANIFEST_SCHEMA_VERSION: @@ -5668,7 +5757,7 @@ def _check_local_area_release_manifest( f"release_manifest.json 'schema_version' is {schema_version!r}; " f"this library publishes version {RELEASE_MANIFEST_SCHEMA_VERSION}." ) - build_folder = publishes_to_build_folder(release_id) + build_folder = _build_folder_layout(release_id, manifest) build = manifest.get("build") if build_folder: _check_build_folder_identity( @@ -5752,7 +5841,11 @@ def _check_local_area_release_manifest( f"release_manifest.json artifact {name!r} is missing {field!r}." ) revision = entry.get("revision") - pinned = revision == release_id + pinned = ( + revision == release_id + if revision_ok is None + else bool(revision_ok(str(revision))) + ) if revision is not None and not pinned: failures.append( f"release_manifest.json artifact {name!r} revision " @@ -7079,7 +7172,12 @@ def validate_release_dir( manifest = _load_json(build_manifest_path, failures) if manifest is not None: build_manifest = manifest - _check_build_manifest(manifest, release_id, failures) + _check_build_manifest( + manifest, + release_id, + failures, + build_folder=_build_folder_layout(release_id, manifest_probe), + ) release_manifest_path = release_dir / "release_manifest.json" if release_manifest_path.is_file(): @@ -7210,7 +7308,7 @@ def validate_release_dir( failures, ) - if publishes_to_build_folder(release_id): + if _build_folder_layout(release_id, release_manifest): _check_build_folder_builds_agree(build_manifest, release_manifest, failures) _check_cross_manifest_consistency( build_manifest, @@ -7578,7 +7676,12 @@ def validate_evidence_release_dir(release_dir: Path | str) -> None: manifest = _load_json(build_manifest_path, failures) if manifest is not None: build_manifest = manifest - _check_build_manifest(manifest, release_id, failures) + _check_build_manifest( + manifest, + release_id, + failures, + build_folder=_build_folder_layout(release_id, manifest_probe), + ) release_manifest_path = release_dir / "release_manifest.json" if release_manifest_path.is_file(): @@ -8266,7 +8369,18 @@ def _check_uk_dense_surface_files( "calibration_diagnostics.json changed original evaluated " "diagnostic values." ) - if build and report and report.get("release_id") != build.get("build"): + # A build-folder manifest names the attempt as its build; a tagged + # one, as its attempt_id. + if ( + build + and report + and report.get("release_id") + != ( + build.get("build") + if isinstance(build.get("build"), str) + else build.get("attempt_id") + ) + ): failures.append( "the signed gate report is not bound to the released attempt." ) From fc324c8a8869bf2ee0dc388b1a2e696e935302f9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:40:39 +0400 Subject: [PATCH 15/26] Test that UK releases keep publishing and promoting through the pointer files Until the switch, the tagged publisher publishes the UK national, dense and local-area releases again, and promotes them through latest-.json with line= and --promote-line, sending the release alert. These are main's tests for that path, beside the build-folder preparation tests. Part of the split for the switch: reverting this commit and the next one re-applies the removal of the old UK path. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_publish_guard.py | 80 +++++ .../tests/engine_free/shared/test_release.py | 316 +++++++++++++----- test_support/microcosm_data/release.py | 39 +++ 3 files changed, 343 insertions(+), 92 deletions(-) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py b/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py index 4540f4c1db..a61890267d 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_publish_guard.py @@ -428,3 +428,83 @@ def test_publish_cli_defaults_to_the_certified_tier(tmp_path, monkeypatch): rc = main([str(tmp_path)]) assert rc == 0 assert calls[0][2]["evidence"] is False + + +def test_publish_cli_forwards_line_promotion_and_cut_tag(tmp_path, monkeypatch): + cut_tag = "microcosm-uk-2024-25-national-20260920T120000Z-deadbeef" + calls = _capture_publish(monkeypatch) + + rc = main( + [ + str(tmp_path), + "--promote-line", + "national", + "--tag-name", + cut_tag, + ] + ) + + assert rc == 0 + assert len(calls) == 1 + assert calls[0][2]["line"] == "national" + assert calls[0][2]["tag_name"] == cut_tag + assert calls[0][2]["update_latest"] is True + + +@pytest.mark.parametrize( + ("arguments", "message"), + [ + ( + [ + "--promote-line", + "national", + "--tag-name", + "cut-tag", + "--no-latest", + ], + "--promote-line cannot be combined with --no-latest", + ), + ( + [ + "--promote-line", + "national", + "--tag-name", + "cut-tag", + "--tag-only", + ], + "--promote-line cannot be combined with --tag-only", + ), + ( + [ + "--promote-line", + "national", + "--tag-name", + "cut-tag", + "--evidence", + ], + "--promote-line cannot be combined with --evidence", + ), + ( + ["--promote-line", "national"], + "--promote-line requires --tag-name", + ), + ], +) +def test_publish_cli_refuses_incompatible_line_promotion_modes( + tmp_path, capsys, monkeypatch, arguments, message +): + import microcosm.data.publish_cli as cli + + called = False + + def unexpected_publish(*args, **kwargs): + nonlocal called + called = True + + monkeypatch.setattr(cli, "publish_release", unexpected_publish) + + with pytest.raises(SystemExit, match="2"): + cli.main([str(tmp_path), *arguments]) + + assert message in capsys.readouterr().err + assert called is False diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release.py b/packages/microcosm-data/tests/engine_free/shared/test_release.py index da9bb54935..7e497e85cf 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release.py @@ -158,68 +158,129 @@ def test_line_pointer_payload_refuses_a_line_id_mismatch() -> None: ) -def _write_uk_build_folder_release( - release_id: str, release_dir: Path, tmp_path: Path -) -> Path: - """One build-folder release of each kind: national, dense or local-area.""" - if release_id == UK_NATIONAL_RELEASE_ID: - return _as_uk_national_build_folder_release(release_dir) - from .test_local_area_contract import _write_local_bundle +@pytest.mark.parametrize( + ("options", "message"), + [ + ({"update_latest": False}, "requires update_latest=True"), + ({"tag_only": True}, "cannot use tag_only=True"), + ({"evidence": True}, "cannot publish at the evidence tier"), + ], +) +def test_prepare_release_refuses_incompatible_line_modes( + release_dir: Path, monkeypatch, options: dict, message: str +) -> None: + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) + monkeypatch.setattr( + release_module, + "validate_evidence_release_dir", + lambda _path, **_kwargs: None, + ) - if release_id == UK_LOCAL_RELEASE_ID: - return _write_local_bundle(tmp_path / "local", release_id=release_id) - from test_support.microcosm_data.build_folders import UK_DENSE_BUILD + with pytest.raises(ValueError, match=message): + release_module.prepare_release(release_dir, line="national", **options) - dense = _write_local_bundle(tmp_path / "dense", release_id=UK_LOCAL_RELEASE_ID) - dense = dense.rename(dense.with_name(release_id)) - for name in ("build_manifest.json", "release_manifest.json"): - manifest = json.loads((dense / name).read_text()) - manifest.update(release=release_id, build=UK_DENSE_BUILD) - (dense / name).write_text(json.dumps(manifest)) - return dense +def test_prepare_release_refuses_a_line_id_mismatch( + release_dir: Path, monkeypatch +) -> None: + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) -@pytest.mark.parametrize( - "release_id", - [UK_NATIONAL_RELEASE_ID, "microcosm-uk-2024-25-dense", UK_LOCAL_RELEASE_ID], -) -def test_the_tagged_publisher_refuses_every_build_folder_release( - release_dir: Path, artifact_root: Path, tmp_path: Path, release_id: str + with pytest.raises(ValueError, match="belongs to line None"): + release_module.prepare_release(release_dir, line="national") + + +def test_national_cut_promotes_only_its_line_pointer( + release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch ) -> None: - """A UK build publishes into its own folder through the emitter; this - publisher, which commits, tags and writes pointer files, refuses it - before any check or Hub call, on every path.""" - uk_dir = _write_uk_build_folder_release(release_id, release_dir, tmp_path) + national = _as_uk_national_line_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) + alerts: list = [] + monkeypatch.setattr( + release_module, + "notify_release", + lambda repo_id, release_id, updated_at, **kwargs: alerts.append( + (repo_id, release_id, updated_at, kwargs) + ), + ) uk_hub = FakeHub("policyengine/populace-uk-private") uk_hub._download_dir = tmp_path / "uk-hub-cache" - message = "microcosm-publish-release-build" + june_pointer = latest_pointer_payload( + JUNE_UK_RELEASE_ID, updated_at="2026-06-19T02:38:00+00:00" + ) + june_pointer_bytes = json.dumps(june_pointer, indent=1).encode() + uk_hub.seed_main_file(LATEST_POINTER_PATH, june_pointer_bytes) - with pytest.raises(ValueError, match=message): - release_module.prepare_release(uk_dir, artifact_root=artifact_root) - with pytest.raises(ValueError, match=message): - publish_release( - uk_dir, + published = publish_release( + national, + "policyengine/populace-uk-private", + api=uk_hub, + artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", + updated_at="2026-09-20T12:00:00+00:00", + ) + + pointer_path = line_pointer_path("national") + main_files = uk_hub._commits[uk_hub._refs["main"]] + assert main_files[LATEST_POINTER_PATH] == june_pointer_bytes + assert { + path + for path in main_files + if path.startswith("latest") and path.endswith(".json") + } == {LATEST_POINTER_PATH, pointer_path} + assert uk_hub.events[-1][1]["paths"][-1] == pointer_path + assert uk_hub.uploads[-1][0] == pointer_path + assert uk_hub.tags == [{"tag": UK_NATIONAL_CUT_TAG, "revision": "commit-1"}] + assert published["revision"] == UK_NATIONAL_CUT_TAG + assert published["line"] == "national" + assert ( + latest_line_release( + "policyengine/populace-uk-private", line="national", api=uk_hub + ).revision + == UK_NATIONAL_CUT_TAG + ) + assert alerts == [ + ( "policyengine/populace-uk-private", - api=uk_hub, - artifact_root=artifact_root, - update_latest=False, + UK_NATIONAL_RELEASE_ID, + "2026-09-20T12:00:00+00:00", + { + "warn_if_unset": True, + "line": "national", + "revision": UK_NATIONAL_CUT_TAG, + }, ) - with pytest.raises(ValueError, match=message): - publish_cli.main([str(uk_dir), "--preflight-only", "--no-latest"]) + ] - assert uk_hub.events == [] - assert uk_hub.uploads == [] +def test_local_k_role_moves_only_its_own_line_pointer(tmp_path: Path) -> None: + from .test_local_area_contract import _write_local_bundle + + release_dir = _write_local_bundle(tmp_path, release_id=UK_LOCAL_RELEASE_ID) + uk_hub = FakeHub("policyengine/populace-uk-private") + uk_hub._download_dir = tmp_path / "uk-local-hub-cache" -def test_the_tagged_publisher_has_no_pointer_promotion_option() -> None: - """Only UK releases were made current through latest-.json pointer - files, and they no longer publish here.""" - import inspect + published = publish_release( + release_dir, + "policyengine/populace-uk-private", + api=uk_hub, + artifact_root=tmp_path, + line="local-k55000", + notify=False, + ) - assert "line" not in inspect.signature(publish_release).parameters - assert "line" not in inspect.signature(release_module.prepare_release).parameters - with pytest.raises(SystemExit): - publish_cli.main(["releases/x", "--promote-line", "national"]) + pointer_path = line_pointer_path("local-k55000") + assert published["revision"] == UK_LOCAL_RELEASE_ID + assert uk_hub.tags == [{"tag": UK_LOCAL_RELEASE_ID, "revision": "commit-1"}] + assert uk_hub.events[-1][1]["paths"][-1] == pointer_path + assert all(path != LATEST_POINTER_PATH for path, _ in uk_hub.uploads) + assert all(path != LATEST_EVIDENCE_POINTER_PATH for path, _ in uk_hub.uploads) def test_prepare_build_folder_release_lists_each_file_with_its_role( @@ -264,7 +325,9 @@ def test_prepare_build_folder_release_publishes_the_checksum_ledger( ) -> None: from .test_local_area_contract import _write_local_bundle - release_dir = _write_local_bundle(tmp_path, release_id=UK_LOCAL_RELEASE_ID) + release_dir = _write_local_bundle( + tmp_path, release_id=UK_LOCAL_RELEASE_ID, build_folder=True + ) prepared = release_module.prepare_build_folder_release( release_dir, artifact_root=tmp_path @@ -1823,94 +1886,132 @@ def no_hub(*args, **kwargs): assert hub.uploads == [] -def test_publish_then_promote_reuses_the_immutable_tag( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch +def test_inspect_then_promote_reuses_the_immutable_tag( + release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch ) -> None: - """Publishing without the pointer, then with it: the second call - recognises the existing tag that describes this release, writes no second - immutable revision and only the main commit carrying the pointer.""" + """The documented two-step sequence: publish for inspection under the cut + tag, then promote the same cut. The second call recognises the existing + tag that describes this release, writes no second immutable revision + and only the main commit carrying the pointer (review of #966).""" + national = _as_uk_national_line_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) + hub = _uk_hub(tmp_path) + june_pointer_bytes = hub._commits[hub._refs["main"]][LATEST_POINTER_PATH] publish_release( - release_dir, - "policyengine/populace-us", + national, + "policyengine/populace-uk-private", api=hub, artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, update_latest=False, ) - assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] + assert line_pointer_path("national") not in hub._commits[hub._refs["main"]] events_after_inspect = len(hub.events) promoted = publish_release( - release_dir, - "policyengine/populace-us", + national, + "policyengine/populace-uk-private", api=hub, artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", updated_at="2026-09-23T12:00:00+00:00", ) kinds = [event for event, _ in hub.events[events_after_inspect:]] assert kinds == ["create_commit"], kinds - assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] - assert promoted["release_id"] == RELEASE_ID - assert latest_release("policyengine/populace-us", api=hub).release_id == ( - RELEASE_ID + assert hub.tags == [{"tag": UK_NATIONAL_CUT_TAG, "revision": "commit-1"}] + main_files = hub._commits[hub._refs["main"]] + assert main_files[LATEST_POINTER_PATH] == june_pointer_bytes + assert json.loads(main_files[line_pointer_path("national")])["revision"] == ( + UK_NATIONAL_CUT_TAG + ) + assert promoted["revision"] == UK_NATIONAL_CUT_TAG + assert ( + latest_line_release( + "policyengine/populace-uk-private", line="national", api=hub + ).revision + == UK_NATIONAL_CUT_TAG ) def test_retry_after_a_failed_pointer_commit_reuses_the_tag( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch + release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch ) -> None: """A failure between tag creation and the pointer commit leaves the tag; the retry stands on it instead of dying on create_tag.""" + national = _as_uk_national_line_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) + hub = _uk_hub(tmp_path) hub.fail_main_commit = True with pytest.raises(RuntimeError, match="injected main commit failure"): publish_release( - release_dir, - "policyengine/populace-us", + national, + "policyengine/populace-uk-private", api=hub, artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", ) - assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] - assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] + assert hub.tags == [{"tag": UK_NATIONAL_CUT_TAG, "revision": "commit-1"}] + assert line_pointer_path("national") not in hub._commits[hub._refs["main"]] hub.fail_main_commit = False publish_release( - release_dir, - "policyengine/populace-us", + national, + "policyengine/populace-uk-private", api=hub, artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", ) - assert hub.tags == [{"tag": RELEASE_ID, "revision": "commit-1"}] - assert LATEST_POINTER_PATH in hub._commits[hub._refs["main"]] + assert hub.tags == [{"tag": UK_NATIONAL_CUT_TAG, "revision": "commit-1"}] + assert line_pointer_path("national") in hub._commits[hub._refs["main"]] -def test_publication_refuses_a_tag_that_describes_another_release( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch +def test_promotion_refuses_a_tag_that_describes_another_release( + release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch ) -> None: + national = _as_uk_national_line_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) + hub = _uk_hub(tmp_path) # A tag already pointing at a revision with no manifest for this release. - hub._refs[RELEASE_ID] = hub._refs["main"] + hub._refs[UK_NATIONAL_CUT_TAG] = hub._refs["main"] with pytest.raises(ValueError, match="does not describe this release"): publish_release( - release_dir, - "policyengine/populace-us", + national, + "policyengine/populace-uk-private", api=hub, artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", ) - # A tag whose manifest is another release's. - hub._commits["other"] = {f"releases/{RELEASE_ID}/release_manifest.json": b"{}"} - hub._refs[RELEASE_ID] = "other" + # A tag whose manifest is another cut's. + hub._commits["other"] = { + f"releases/{UK_NATIONAL_RELEASE_ID}/release_manifest.json": b"{}" + } + hub._refs[UK_NATIONAL_CUT_TAG] = "other" with pytest.raises(ValueError, match="describes another release"): publish_release( - release_dir, - "policyengine/populace-us", + national, + "policyengine/populace-uk-private", api=hub, artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", ) - assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] + assert line_pointer_path("national") not in hub._commits[hub._refs["main"]] def test_line_pointer_path_refuses_the_evidence_line() -> None: @@ -1918,17 +2019,44 @@ def test_line_pointer_path_refuses_the_evidence_line() -> None: line_pointer_path("evidence") +def test_line_promotion_refuses_a_release_whose_role_is_not_the_lines( + release_dir: Path, artifact_root: Path, monkeypatch +) -> None: + """The national line carries national-default releases only; a + local-area manifest cannot ride the national pointer on its id.""" + national = _as_uk_national_line_release(release_dir) + manifest_path = national / "release_manifest.json" + manifest = json.loads(manifest_path.read_text()) + manifest["dataset_role"] = "non_default_local_area" + manifest_path.write_text(json.dumps(manifest)) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) + with pytest.raises(ValueError, match="publishes only 'national_default'"): + release_module.prepare_release( + national, + artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", + ) + + def test_transient_errors_while_checking_an_existing_tag_propagate( - hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch + release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch ) -> None: """Only "absent" answers are swallowed: a transient failure looking up - the tag or its manifest propagates, so a good tag is never orphaned + the tag or its manifest propagates, so a good cut is never orphaned and the create path is never re-entered with the tag in place.""" + national = _as_uk_national_line_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) + hub = _uk_hub(tmp_path) original_repo_info = hub.repo_info def flaky_repo_info(*, repo_id, repo_type, revision=None): - if revision == RELEASE_ID: + if revision == UK_NATIONAL_CUT_TAG: raise RuntimeError("injected transient Hub failure") return original_repo_info( repo_id=repo_id, repo_type=repo_type, revision=revision @@ -1937,16 +2065,18 @@ def flaky_repo_info(*, repo_id, repo_type, revision=None): monkeypatch.setattr(hub, "repo_info", flaky_repo_info) with pytest.raises(RuntimeError, match="injected transient Hub failure"): publish_release( - release_dir, - "policyengine/populace-us", + national, + "policyengine/populace-uk-private", api=hub, artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", ) assert hub.tags == [] assert not [event for event, _ in hub.events if event == "create_branch"] monkeypatch.setattr(hub, "repo_info", original_repo_info) - hub._refs[RELEASE_ID] = hub._refs["main"] + hub._refs[UK_NATIONAL_CUT_TAG] = hub._refs["main"] def flaky_download(*, repo_id, filename, repo_type, revision=None): raise RuntimeError("injected transient download failure") @@ -1954,9 +2084,11 @@ def flaky_download(*, repo_id, filename, repo_type, revision=None): monkeypatch.setattr(hub, "hf_hub_download", flaky_download) with pytest.raises(RuntimeError, match="injected transient download failure"): publish_release( - release_dir, - "policyengine/populace-us", + national, + "policyengine/populace-uk-private", api=hub, artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", ) - assert LATEST_POINTER_PATH not in hub._commits[hub._refs["main"]] + assert line_pointer_path("national") not in hub._commits[hub._refs["main"]] diff --git a/test_support/microcosm_data/release.py b/test_support/microcosm_data/release.py index 4a32607278..6632efe46a 100644 --- a/test_support/microcosm_data/release.py +++ b/test_support/microcosm_data/release.py @@ -753,6 +753,35 @@ def artifact_root(tmp_path: Path) -> Path: return directory +def _as_uk_national_line_release(release_dir: Path) -> Path: + """Retarget the publisher fixture to the constant UK national line id.""" + national = release_dir.with_name(UK_NATIONAL_RELEASE_ID) + release_dir.rename(national) + + build_path = national / "build_manifest.json" + build = json.loads(build_path.read_text()) + build["build_id"] = UK_NATIONAL_RELEASE_ID + build_path.write_text(json.dumps(build)) + + certification_path = national / "release_certification.json" + certification_path.write_text("{}") + manifest_path = national / "release_manifest.json" + manifest = json.loads(manifest_path.read_text()) + manifest["build"]["build_id"] = UK_NATIONAL_RELEASE_ID + for artifact in manifest["artifacts"].values(): + artifact["repo_id"] = "policyengine/populace-uk-private" + artifact["revision"] = UK_NATIONAL_CUT_TAG + manifest["artifacts"]["release_certification"] = { + "kind": "diagnostics", + "path": certification_path.name, + "repo_id": "policyengine/populace-uk-private", + "revision": UK_NATIONAL_CUT_TAG, + "sha256": _sha256(certification_path), + } + manifest_path.write_text(json.dumps(manifest)) + return national + + def _as_uk_national_build_folder_release(release_dir: Path) -> Path: """Retarget the publisher fixture to the UK national release. @@ -874,4 +903,14 @@ def _declare_root_artifact(release_dir: Path, *, key: str, path: str) -> None: manifest_path.write_text(json.dumps(manifest)) +def _uk_hub(tmp_path: Path) -> FakeHub: + hub = FakeHub("policyengine/populace-uk-private") + hub._download_dir = tmp_path / "uk-hub-cache" + june_pointer = latest_pointer_payload( + JUNE_UK_RELEASE_ID, updated_at="2026-06-19T02:38:00+00:00" + ) + hub.seed_main_file(LATEST_POINTER_PATH, json.dumps(june_pointer, indent=1).encode()) + return hub + + __all__ = [name for name in globals() if not name.startswith("__")] From 900a927a25c67d406a77c3b661f1e3a21739b239 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:41:57 +0400 Subject: [PATCH 16/26] Keep publishing and promoting UK releases through the pointer files The tagged publisher accepts the UK national, dense and local-area releases again, and line= / --promote-line promote them through latest-.json with the release alert, so UK Slack alerts keep being sent. tools/publish_release.sh and tools/release.env.example are main's again, with SLACK_WEBHOOK_POPULACE_UK. The build-folder preparation (prepare_build_folder_release) and the shared publication refusals stay. Part of the split for the switch: reverting this commit and the one before re-applies the removal of the old UK path and its alerts. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/data/publish_cli.py | 27 ++-- .../src/microcosm/data/release.py | 121 ++++++++++-------- tools/publish_release.sh | 9 +- tools/release.env.example | 4 - 4 files changed, 88 insertions(+), 73 deletions(-) diff --git a/packages/microcosm-data/src/microcosm/data/publish_cli.py b/packages/microcosm-data/src/microcosm/data/publish_cli.py index be507a4ffa..63c47288c1 100644 --- a/packages/microcosm-data/src/microcosm/data/publish_cli.py +++ b/packages/microcosm-data/src/microcosm/data/publish_cli.py @@ -1,11 +1,4 @@ -"""CLI for contract-checked Microcosm release publication. - -It publishes releases that keep the tagged layout and ``latest.json``: every -US release, the June 2023 UK release and ``populace-uk---k`` -releases. The UK national, dense and local-area releases publish each build -into its own folder through the emitter (``microcosm-publish-release-build``), -and this command refuses them. -""" +"""CLI for contract-gated Microcosm release publication.""" from __future__ import annotations @@ -244,6 +237,14 @@ def main(argv: list[str] | None = None) -> int: "--tag-name", help="Optional tag name override; defaults to the release id.", ) + parser.add_argument( + "--promote-line", + metavar="LINE", + help=( + "Promote the release through latest-.json. Requires " + "--tag-name and never writes latest.json." + ), + ) parser.add_argument( "--extra-file", action="append", @@ -304,6 +305,15 @@ def main(argv: list[str] | None = None) -> int: ) args = parser.parse_args(argv) + if args.promote_line is not None: + if args.no_latest: + parser.error("--promote-line cannot be combined with --no-latest.") + if args.tag_only: + parser.error("--promote-line cannot be combined with --tag-only.") + if args.evidence: + parser.error("--promote-line cannot be combined with --evidence.") + if not args.tag_name: + parser.error("--promote-line requires --tag-name.") if args.tag_only and not args.no_latest: parser.error("--tag-only requires --no-latest.") if args.tag_only and not args.create_tag: @@ -328,6 +338,7 @@ def main(argv: list[str] | None = None) -> int: update_latest=not args.no_latest, tag_only=args.tag_only, evidence=args.evidence, + line=args.promote_line, ) from microcosm.data.source_enrichment import ( recorded_claim_measurement, diff --git a/packages/microcosm-data/src/microcosm/data/release.py b/packages/microcosm-data/src/microcosm/data/release.py index a10ebbc30c..43a2d79969 100644 --- a/packages/microcosm-data/src/microcosm/data/release.py +++ b/packages/microcosm-data/src/microcosm/data/release.py @@ -1,16 +1,11 @@ """Publish a release and move its approved repository pointer. -**The UK national, dense and local-area releases no longer publish -here.** They publish each build into its own folder, -``releases///``, through the emitter's ``publish_release`` -call (``microcosm-publish-release-build``, in ``microcosm-build``), and the -repository's ``releases.json`` records which build is current. -:func:`prepare_build_folder_release` checks such a build and lists its files -with their roles; :func:`prepare_release` and :func:`publish_release` refuse -it. Everything below describes the tagged layout the other releases keep: -every US release, until the stable releases US builds publish under are -agreed, and the June 2023 UK release and ``populace-uk---k`` -releases. +It also checks a build of a release that can publish into its own +folder, ``releases///``, and lists its files with their +roles (:func:`prepare_build_folder_release`), for +``microcosm-publish-release-build``, which hands it to the emitter. UK +releases still publish here, with tags and pointer files, until their +repository switches to ``releases.json``. The Hub repo publishes builds under ``releases//``, but nothing identified which release is *current*: a consumer had to list the tree and @@ -31,12 +26,9 @@ returns the typed pointer, the one-call answer to "which release is current?" for dashboards and scorers. -The UK national and local-area releases were made current through pointer -files named ``latest-.json``. Those schema-1 pointers add the fields -``line`` and ``revision``, so each could name an immutable per-build tag -without changing the frozen repository-global ``latest.json``. Nothing -writes them any more; -:func:`latest_line_release` still reads them until they are deleted. +Approved UK lines coexist through ``latest-.json``. Those schema-1 +pointers add ``line`` and ``revision`` so a line can name an immutable cut tag +without changing the frozen repository-global ``latest.json``. The EVIDENCE tier (microcosm#506) publishes through the same producer with ``evidence=True``: identical immutable-tag mechanics, but the pointer that @@ -70,6 +62,7 @@ RELEASE_MANIFEST_FILE_ROLE, RELEASE_ROLES, _uk_line_cut_tag_re, + dataset_role_for_line, line_for_release_id, publishes_to_build_folder, release_dataset_role, @@ -80,7 +73,6 @@ from microcosm.data.slack import notify_release __all__ = [ - "BUILD_FOLDER_PUBLICATION_COMMAND", "BuildFolderFile", "BuildFolderRelease", "LATEST_EVIDENCE_POINTER_PATH", @@ -296,26 +288,12 @@ class PreparedRelease: tag: str filenames: list[str] root_artifacts: dict[str, str] + line: str | None pointer_path: str calibration_diagnostics_available: bool contract_warnings: tuple[str, ...] = () -#: Where a build-folder release publishes from: the workspace command that -#: hands each build to the emitter (``microcosm.build.release_publication``). -BUILD_FOLDER_PUBLICATION_COMMAND = "microcosm-publish-release-build" - - -def _refuse_build_folder_release(release_id: str) -> None: - if publishes_to_build_folder(release_id): - raise ValueError( - f"release {release_id!r} publishes each build into its own folder " - "through the emitter, which also records it in releases.json; " - f"publish it with `{BUILD_FOLDER_PUBLICATION_COMMAND}`. This " - "publisher commits, tags and writes latest*.json pointer files." - ) - - @dataclass(frozen=True) class BuildFolderFile: """One file of a build folder: its bare name, role, local path and digest.""" @@ -493,6 +471,7 @@ def prepare_release( update_latest: bool = True, tag_only: bool = False, evidence: bool = False, + line: str | None = None, ) -> PreparedRelease: """Run every local publisher guard and collect the files to upload. @@ -501,10 +480,8 @@ def prepare_release( replays any required source-enrichment compatibility checks. No Hub client is constructed, no Hub activity occurs, and no release alert is sent. Publication must prepare again so preflight cannot authorize stale inputs. - A release that publishes into build folders is refused first. """ release_dir = Path(release_dir) - _refuse_build_folder_release(release_dir.name) if parent_h5 is not None or compatibility_wheels: from microcosm.data.compatibility_recertification import ( RECERTIFICATION_RELEASE_TYPE, @@ -547,8 +524,29 @@ def prepare_release( warnings.warn(f"release contract: {contract_warning}", stacklevel=2) release_id = release_dir.name role = release_dataset_role(release_dir) - pointer_path = LATEST_EVIDENCE_POINTER_PATH if evidence else LATEST_POINTER_PATH - if role != NATIONAL_DEFAULT_DATASET_ROLE and update_latest: + if line is not None: + pointer_path = line_pointer_path(line) + if evidence: + raise ValueError("line promotion cannot publish at the evidence tier.") + if not update_latest: + raise ValueError("line promotion requires update_latest=True.") + if tag_only: + raise ValueError("line promotion cannot use tag_only=True.") + expected_line = line_for_release_id(release_id) + if line != expected_line: + raise ValueError( + f"release {release_id!r} belongs to line {expected_line!r}, " + f"not {line!r}." + ) + expected_role = dataset_role_for_line(line) + if role != expected_role: + raise ValueError( + f"release {release_id!r} declares dataset_role {role!r}; line " + f"{line!r} publishes only {expected_role!r} releases." + ) + else: + pointer_path = LATEST_EVIDENCE_POINTER_PATH if evidence else LATEST_POINTER_PATH + if role != NATIONAL_DEFAULT_DATASET_ROLE and update_latest and line is None: # microcosm#398 defense in depth beyond --no-latest: a non-default # release can never move the global default pointer, even if a # caller asks. @@ -700,12 +698,13 @@ def prepare_release( "match the release id or uniform per-cut artifact revision." ) # The repository-global pointer may only name a release whose immutable tag - # IS the release id. - if update_latest and tag != release_id: + # IS the release id. Approved line pointers have their own reader contract + # and may follow a per-cut tag; latest.json still may not. + if update_latest and tag != release_id and line is None: raise ValueError( f"latest.json may not name per-cut tag {tag!r} for release " - f"{release_id!r}; a tag other than the release id publishes " - "inspect-only. Pass update_latest=False (--no-latest)." + f"{release_id!r}; without an approved line pointer, per-cut tags " + "publish inspect-only. Pass update_latest=False (--no-latest)." ) if root_artifacts and artifact_root is None: raise ValueError( @@ -734,6 +733,7 @@ def prepare_release( tag=tag, filenames=filenames, root_artifacts=root_artifacts, + line=line, pointer_path=pointer_path, calibration_diagnostics_available=calibration_diagnostics_available, contract_warnings=tuple(contract_warnings), @@ -756,13 +756,10 @@ def publish_release( tag_only: bool = False, notify: bool = True, evidence: bool = False, + line: str | None = None, ) -> dict: """Publish a release directory and optionally point ``latest.json`` at it. - A release that publishes into build folders (the UK national, dense - and local-area releases) is refused before any check or Hub call; see - the module docstring. - The order is the guarantee: the release contract is validated first (an invalid release never reaches the Hub), then an immutable branch commit is created with every release file and artifact and tagged. A tag-only publish @@ -823,17 +820,20 @@ def publish_release( the certified default or feed pe.py certification. Tag and upload mechanics are otherwise identical. ``update_latest`` then governs the evidence pointer. - - A release published earlier without the pointer (``update_latest=False`` - under the same tag) is pointed to by a later call: the publisher - recognises the existing tag that already describes this release, creates - no second immutable revision, and writes only the main commit carrying - the pointer. The same recognition makes a retry after a failure between - tag creation and the pointer commit safe. + line: Promote an approved release line through ``latest-.json``. + Line promotion requires ``update_latest=True``, a matching line + release id, the line's dataset role, and artifact revisions + pinned to the selected tag. A cut published for inspection + earlier (``update_latest=False`` under the same tag) is promoted + by the same call: the publisher recognises the existing tag that + already describes this release, creates no second immutable + revision, and writes only the main commit carrying the pointer. + The same recognition makes a retry after a failure between tag + creation and the pointer commit safe. Returns: The release's pointer payload (``latest.json`` shape, plus ``tier`` at - the evidence tier). + the evidence tier or ``line`` and ``revision`` for a line promotion). It is uploaded only when ``update_latest=True``. When the release contract warned, the returned payload also lists the warnings under ``contract_warnings``; the uploaded pointer never carries them, and @@ -856,6 +856,7 @@ def publish_release( update_latest=update_latest, tag_only=tag_only, evidence=evidence, + line=line, ) release_id = prepared.release_id @@ -885,6 +886,17 @@ def publish_release( ), ) pointer_label = "evidence release" + elif prepared.line is not None: + payload = line_pointer_payload( + release_id, + line=prepared.line, + revision=prepared.tag, + updated_at=updated_at, + calibration_diagnostics_available=( + prepared.calibration_diagnostics_available + ), + ) + pointer_label = f"{prepared.line} line" else: payload = latest_pointer_payload( release_id, @@ -941,6 +953,9 @@ def publish_release( if evidence: # The alert must never read as a certified release announcement. notify_kwargs["tier"] = RELEASE_TIER_EVIDENCE + if prepared.line is not None: + notify_kwargs["line"] = prepared.line + notify_kwargs["revision"] = prepared.tag notify_release(repo_id, release_id, payload.get("updated_at"), **notify_kwargs) if prepared.contract_warnings: return {**payload, "contract_warnings": list(prepared.contract_warnings)} diff --git a/tools/publish_release.sh b/tools/publish_release.sh index 098a4441f6..e760f2c440 100755 --- a/tools/publish_release.sh +++ b/tools/publish_release.sh @@ -1,13 +1,6 @@ #!/usr/bin/env bash # -# Publish a Microcosm release that keeps tags and latest.json (every US -# release, the June 2023 UK release and populace-uk---k -# releases) and fire its Slack alert, in one tracked path. -# -# The UK national, dense and local-area releases publish each build into its -# own folder through the emitter with `microcosm-publish-release-build` -# instead; `microcosm-publish-release` refuses them, and they send no Slack -# alert until the dashboard posts one from releases.json. +# Publish a Microcosm release and fire its Slack alert, in one tracked path. # # Thin wrapper around `microcosm-publish-release` so that every ship goes # through the same command and the release alert is guaranteed to be wired. diff --git a/tools/release.env.example b/tools/release.env.example index 49d319df6e..02c5e5b1af 100644 --- a/tools/release.env.example +++ b/tools/release.env.example @@ -4,10 +4,6 @@ # paste the Slack *incoming webhook* URLs for #populace-us and #populace-uk. # Once set, every `tools/publish_release.sh …` (and any direct # `microcosm-publish-release`) posts a release alert to the matching channel. -# Those are the releases that keep tags and latest.json: every US release, the -# June 2023 UK release and populace-uk---k releases. The UK -# national, dense and local-area releases publish into build folders through -# the emitter and send no alert from here. # # cp tools/release.env.example tools/release.env # From 42bb8577156d35e05cde9d7d538b1e6afcd163d2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:42:59 +0400 Subject: [PATCH 17/26] Test that the UK assemblers write today's tagged manifests and commands Until the switch the UK national and dense assemblers keep writing the tagged manifests (build_id, attempt_id, cut_tag and per-build revisions) and printing tools/publish_release.sh commands. These are main's assembler tests again; the build-folder assembler tests, and the test that publishes an assembled national build through the emitter, move to the switch. Part of the split for the switch: reverting this commit and the next one re-applies the assemblers' move to the emitter. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_dense_release_assembler.py | 52 ++----- .../uk/test_uk_release_assembler.py | 127 ++++++------------ 2 files changed, 49 insertions(+), 130 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py index 86b63bedbf..5d1d911f01 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_dense_release_assembler.py @@ -7,7 +7,6 @@ import hmac import importlib.util import json -import shlex from pathlib import Path import pytest @@ -569,8 +568,7 @@ def test_assembler_stages_a_contract_valid_dense_release( summary = json.loads(capsys.readouterr().out) release_dir = out / UK_DENSE_RELEASE_ID assert summary["release_id"] == UK_DENSE_RELEASE_ID - assert (summary["release"], summary["build"]) == (UK_DENSE_RELEASE_ID, ATTEMPT) - assert "cut_tag" not in summary + assert summary["cut_tag"] == f"{UK_DENSE_RELEASE_ID}-20260903T105422Z-ca611e43" assert release_dir.is_dir() for name in dc._UK_DENSE_REQUIRED_RELEASE_FILES: assert (release_dir / name).is_file(), name @@ -616,28 +614,7 @@ def test_assembler_stages_a_contract_valid_dense_release( shipped["reviewed_exclusions_stood_on"] == coverage["signed_deferrals"]["reviewed_exclusions"] ) - # While the repository keeps its latest*.json pointer files, the emitter - # refuses any change to a current build, so the printed publication lists - # the build and the promotion makes it current once those files are gone. - assert shlex.split(summary["publish_command"]) == [ - "uv", - "run", - "microcosm-publish-release-build", - str(release_dir), - "--repo-id", - "policyengine/populace-uk-private", - "--artifact-root", - str(candidate), - ] - assert shlex.split(summary.get("promote_command", "")) == [ - "uv", - "run", - "microcosm-publish-release-build", - str(release_dir), - "--repo-id", - "policyengine/populace-uk-private", - "--promote", - ] + assert "--tag-only" in summary["publish_command"] published = candidate / "microcosm_uk_2024_25_dense.h5" assert ( published.read_bytes() @@ -660,24 +637,10 @@ def test_assembler_stages_a_contract_valid_dense_release( ] is False ) - # The build publishes into its own folder: both manifests name the release - # and the build (the calibration attempt), and nothing names a tag. - build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) - for document in (build_manifest, manifest): - assert (document["release"], document["build"]) == ( - UK_DENSE_RELEASE_ID, - ATTEMPT, - ) - assert not {"build_id", "attempt_id", "cut_tag"} & set(document) - assert manifest["built_at"] == build_manifest["created_at"] - assert manifest["built_with_model_package"]["name"] == "policyengine-uk" - assert manifest["built_with_core_package"]["name"] == "policyengine-core" - assert not any("revision" in entry for entry in manifest["artifacts"].values()) - assert manifest["artifacts"]["microcosm_uk_2024_25_dense"]["role"] == "dataset" - assert manifest["artifacts"]["calibration_diagnostics"]["role"] == ( - "calibration_diagnostics" + assert ( + manifest["artifacts"]["microcosm_uk_2024_25_dense"]["revision"] + == summary["cut_tag"] ) - assert manifest["artifacts"]["uk_local_gates"]["role"] == "uk_local_gates" assert ( manifest["artifacts"]["microcosm_uk_2024_25_dense"]["repo_id"] == "policyengine/populace-uk-private" @@ -701,8 +664,13 @@ def test_assembler_stages_a_contract_valid_dense_release( assert set(gate_summary["diagnostic_gates"]) == set(UK_LOCAL_GATE_SCOPE) - set( dc._UK_DENSE_RELEASE_BLOCKING_IDS ) + assert ( + "--no-latest" in summary["publish_command"] + and "populace-uk-private" in summary["publish_command"] + ) # The national assembler's rule: the run's staging receipt rides into the # build manifest unchanged, where publication reads it. + build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) assert build_manifest["staging"] == _staging_delivery() # The contract re-validates the finished directory, and so does the pre-flight. dc.validate_release_dir(release_dir) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py index b48ce46c88..68f4fc644a 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_assembler.py @@ -58,6 +58,7 @@ def _load_fixture_module(): #: assembler rederives the SPI Public Use Tape marker from them. _SPINE_STAGES = tuple(stage.stage for stage in load_country_spec("uk").sources.stages) _ATTEMPT_ID = "uk-frs-calibration-attempt-20260828T101112Z-1a2b3c4d" +_CUT_TAG = f"{UK_NATIONAL_RELEASE_ID}-20260828T101112Z-1a2b3c4d" def _load_driver_module(): @@ -403,17 +404,8 @@ def test_assemble_green_release_dir(assembler_inputs, capsys) -> None: "last_error_code": None, "opt_out_reason": "test fixture deliberately disables staging", } - # The build publishes into its own folder: both manifests name the release - # and the build (the calibration attempt), and nothing names a tag. - for manifest in (build_manifest, release_manifest): - assert (manifest["release"], manifest["build"]) == ( - UK_NATIONAL_RELEASE_ID, - _ATTEMPT_ID, - ) - assert not {"build_id", "attempt_id", "cut_tag"} & set(manifest) - assert release_manifest["built_at"] == build_manifest["created_at"] - assert release_manifest["built_with_core_package"]["name"] == "policyengine-core" - assert release_manifest["built_with_model_package"]["name"] == "policyengine-uk" + assert build_manifest["attempt_id"] == _ATTEMPT_ID + assert build_manifest["cut_tag"] == _CUT_TAG assert release_manifest["default_datasets"] == {"national": driver._DATASET_KEY} assert release_manifest["artifacts"][driver._DATASET_KEY]["path"] == ( driver._DATASET_FILENAME @@ -422,20 +414,8 @@ def test_assemble_green_release_dir(assembler_inputs, capsys) -> None: release_manifest["artifacts"][f"{driver._DATASET_KEY}_calibration"]["path"] == f"{driver._DATASET_KEY}_calibration.npz" ) - assert not any( - "revision" in entry for entry in release_manifest["artifacts"].values() - ) - assert { - key: entry["role"] for key, entry in release_manifest["artifacts"].items() - } == { - driver._DATASET_KEY: "dataset", - f"{driver._DATASET_KEY}_calibration": "calibration_weights", - "calibration_diagnostics": "calibration_diagnostics", - "release_certification": "release_certification", - "terminal_gates": "terminal_gates", - "release_cut_gates": "release_cut_gates", - "spine_gates": "spine_gates", - "score_vs_enhanced_frs": "score_vs_enhanced_frs", + assert {entry["revision"] for entry in release_manifest["artifacts"].values()} == { + _CUT_TAG } assert "dataset_role" not in release_manifest # The spine ran the SPI stages, so the release says it rests on the tape, @@ -454,78 +434,43 @@ def test_assemble_green_release_dir(assembler_inputs, capsys) -> None: assert ( release_dir / "release_certification.json" ).read_bytes() == assembler_inputs["certification"].read_bytes() - assert (summary["release"], summary["build"]) == ( - UK_NATIONAL_RELEASE_ID, - _ATTEMPT_ID, - ) - assert "cut_tag" not in summary + assert summary["cut_tag"] == _CUT_TAG assert summary["release_dir"] == str(release_dir) - # The commands are rendered shell-safe; parse them back rather than - # comparing one quoting. The publication lists the build without making - # it current; the reviewed promotion is the separate second command. + # The command is rendered shell-safe; parse it back rather than comparing + # one quoting of it. assert shlex.split(summary["publish_command"]) == [ "uv", "run", - "microcosm-publish-release-build", + "python", + "-m", + "microcosm.data.publish_cli", str(release_dir), "--repo-id", "policyengine/populace-uk-private", "--artifact-root", str(assembler_inputs["candidate"].parent), + "--no-latest", + "--tag-name", + _CUT_TAG, ] - assert shlex.split(summary["promote_command"]) == [ + promote_command = shlex.split(summary["promote_command"]) + assert promote_command == [ "uv", "run", - "microcosm-publish-release-build", + "python", + "-m", + "microcosm.data.publish_cli", str(release_dir), "--repo-id", "policyengine/populace-uk-private", - "--promote", - ] - - -def test_an_assembled_national_build_publishes_through_the_emitter( - assembler_inputs, capsys -) -> None: - """The publication checks the assembled directory with the release - contract itself, not a replaced one, and hands every file over.""" - from microcosm.build import release_publication - from microcosm.data.contract import ( - BUILD_MANIFEST_FILE_ROLE, - RELEASE_MANIFEST_FILE_ROLE, - ) - from test_support.microcosm_build.emitter import FakeEmitterClient - - driver = _load_driver_module() - assert driver.main(assembler_inputs["argv"]) == 0 - capsys.readouterr() - release_dir = assembler_inputs["out_dir"] / UK_NATIONAL_RELEASE_ID - client = FakeEmitterClient() - - outcome = release_publication.publish_release_build( - release_dir, - artifact_root=assembler_inputs["candidate"].parent, - client=client, - ) - - assert outcome.published and outcome.succeeded and not outcome.current - (request,) = client.release_requests - assert (request.release, request.build, request.release_role) == ( - UK_NATIONAL_RELEASE_ID, - _ATTEMPT_ID, + "--artifact-root", + str(assembler_inputs["candidate"].parent), + "--promote-line", "national", - ) - manifest = json.loads((release_dir / "release_manifest.json").read_text()) - assert {item.name: item.role for item in request.files} == { - "release_manifest.json": RELEASE_MANIFEST_FILE_ROLE, - "build_manifest.json": BUILD_MANIFEST_FILE_ROLE, - **{entry["path"]: entry["role"] for entry in manifest["artifacts"].values()}, - } - folder = f"releases/{UK_NATIONAL_RELEASE_ID}/{_ATTEMPT_ID}" - published_dataset = client.hub_files[ - ("policyengine/populace-uk-private", f"{folder}/{driver._DATASET_FILENAME}") + "--tag-name", + _CUT_TAG, ] - assert published_dataset == assembler_inputs["candidate"].read_bytes() + assert "--no-latest" not in promote_command def test_assemble_preserves_successful_version_2_delivery( @@ -652,15 +597,10 @@ def test_assemble_refuses_missing_score_receipt(assembler_inputs) -> None: _load_driver_module().main(assembler_inputs["argv"]) -def test_assemble_takes_no_cut_tag(assembler_inputs) -> None: - """A build in its own folder has no tag to name.""" - with pytest.raises(SystemExit): +def test_assemble_refuses_unprefixed_cut_tag(assembler_inputs) -> None: + with pytest.raises(SystemExit, match="--cut-tag must be"): _load_driver_module().main( - [ - *assembler_inputs["argv"], - "--cut-tag", - f"{UK_NATIONAL_RELEASE_ID}-20260828T101112Z-1a2b3c4d", - ] + [*assembler_inputs["argv"], "--cut-tag", "not-a-national-cut"] ) @@ -857,6 +797,17 @@ def _explode(_release_dir): assert not list(assembler_inputs["candidate"].parent.glob(".*.tmp.npz")) +def test_assemble_refuses_cut_tag_outside_the_grammar(assembler_inputs) -> None: + with pytest.raises(SystemExit, match="YYYYMMDDTHHMMSSZ"): + _load_driver_module().main( + [ + *assembler_inputs["argv"], + "--cut-tag", + f"{UK_NATIONAL_RELEASE_ID}-hotfix", + ] + ) + + def test_assemble_refuses_reserialized_diagnostics(assembler_inputs) -> None: diagnostics = json.loads(assembler_inputs["diagnostics"].read_text()) assembler_inputs["diagnostics"].write_text( From ea2310c13398faca3b451022d0de6729ab44f4c9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:43:38 +0400 Subject: [PATCH 18/26] Keep the UK assemblers on the tagged manifests until the switch The UK national and dense assemblers are main's again: they write the tagged manifests, take --cut-tag, and print tools/publish_release.sh commands, so a UK build is published and promoted through the pointer files as today. This also takes out the dense assembler's separate --promote command added in review round 1. Part of the split for the switch: reverting this commit and the one before re-applies the assemblers' move to the emitter. Co-Authored-By: Claude Opus 5.5 --- tools/assemble_uk_dense_release_dir.py | 126 ++++++++++++------------- tools/assemble_uk_release_dir.py | 117 ++++++++++++++--------- 2 files changed, 135 insertions(+), 108 deletions(-) diff --git a/tools/assemble_uk_dense_release_dir.py b/tools/assemble_uk_dense_release_dir.py index 1275da70f7..b8b52fb098 100644 --- a/tools/assemble_uk_dense_release_dir.py +++ b/tools/assemble_uk_dense_release_dir.py @@ -1,23 +1,16 @@ """Assemble the dense joint UK line's release directory (microcosm#762 A18). Mirrors ``assemble_uk_release_dir.py`` for the ``microcosm-uk-2024-25-dense`` -release: verify the complete hash join over a finished -``--release-candidate`` run of ``build_uk_rowwise_candidate.py`` (its -manifest, its signed ``local_gate_report`` and ``full_gate_report`` outputs -and its diagnostics, plus the spine, ladder and Ledger artifact it stood -on), run the release-candidate -pre-flight, stage the bundle under the non-default local-area role with UK -evidence, validate it with the release contract, and only then rename it -into place. The candidate H5 is cloned beside itself under the published -filename; nothing is uploaded. The release publishes each build into its own -folder through the emitter: the build is the run's attempt ID, both manifests -name the release and the build, and nothing is tagged. The summary prints the -exact ``microcosm-publish-release-build`` commands for the human step -(private repository): ``publish_command`` lists the build, and -``promote_command`` makes it the release's current build. Each new dense -build becomes current; while the repository still has its ``latest*.json`` -pointer files, the emitter refuses every change to a current build, so the -promotion waits until those files are deleted. +line: verify the complete hash join over a finished ``--release-candidate`` +run of ``build_uk_rowwise_candidate.py`` (its manifest, signed gate report, +full gate report and diagnostics, plus the spine, ladder and Ledger artifact +it stood on), run the release-candidate pre-flight, mint the per-cut tag from +the run's attempt id, stage the bundle under the non-default local-area role +with UK evidence, validate it with the release contract, and only then rename +it into place. The candidate H5 is cloned beside itself under the published +filename; nothing is uploaded — the summary prints the exact ``publish_cli`` +command for the human step (``--no-latest --tag-only``, per-cut tag, private +repo). The rotated holdout and the incumbent comparison are opt-in diagnostics (microcosm#1301). The manifest's reviewed limitations say what the release @@ -62,7 +55,6 @@ from microcosm.data.contract import ( _UK_DENSE_SIGNED_EXCLUSION_GATES, _check_uk_incumbent_surface_evaluation, - release_artifact_role, validate_release_dir, ) from microcosm.diagnostics import ( @@ -78,6 +70,7 @@ # pins the two. _DATASET_KEY = "microcosm_uk_2024_25_dense" _DATASET_FILENAME = f"{_DATASET_KEY}.h5" +_ATTEMPT_SUFFIX = re.compile(r"[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}") _RUNTIME_PACKAGES = ("policyengine-core", "policyengine-uk", "microcosm-data") _GIT_COMMIT = re.compile(r"^[0-9a-f]{40}$") #: The gates whose reviewed exclusions the manifest names, each with its @@ -195,6 +188,24 @@ def _preflight_module(): return module +def _cut_tag(attempt_id: str, override: str | None) -> str: + prefix = UK_DENSE_RELEASE_ID + "-" + if override is not None: + if not override.startswith(prefix) or not _ATTEMPT_SUFFIX.fullmatch( + override[len(prefix) :] + ): + raise SystemExit( + f"error: --cut-tag must be {prefix}-" + ) + return override + match = re.search(r"([0-9]{8}T[0-9]{6}Z-[0-9a-f]{8})$", attempt_id) + if match is None: + raise SystemExit( + "error: the run's build id must end with -" + ) + return f"{UK_DENSE_RELEASE_ID}-{match.group(1)}" + + def _holdout_limitation(fit: Mapping[str, object]) -> dict[str, object]: """What the release claims about fit on rows the solve never saw.""" @@ -732,6 +743,7 @@ def output_path(key: str) -> Path: raise SystemExit( "error: manifest.identity.code.git_commit must be a 40-hex commit" ) + cut_tag = _cut_tag(attempt_id, args.cut_tag) parameters = _mapping(manifest.get("parameters"), "manifest.parameters") if parameters.get("release_candidate") is not True: raise SystemExit("error: the run was not a --release-candidate run") @@ -764,6 +776,7 @@ def output_path(key: str) -> Path: incumbent=incumbent, measured=measured, attempt_id=attempt_id, + cut_tag=cut_tag, runtime=runtime, code_pin=code_pin, report_path=report_path, @@ -799,6 +812,7 @@ def _stage_and_finalize( incumbent: _IncumbentAttachment | None, measured: Mapping[str, str], attempt_id: str, + cut_tag: str, runtime: Mapping[str, str], code_pin: str, report_path: Path, @@ -959,11 +973,8 @@ def _stage_and_finalize( "git_dirty" ) git_dirty = recorded_dirty if isinstance(recorded_dirty, bool) else None - # The build is the calibration attempt: both manifests name it, and the - # release, so the emitter can publish it into its own folder. build_manifest = { - "release": UK_DENSE_RELEASE_ID, - "build": attempt_id, + "build_id": UK_DENSE_RELEASE_ID, "build_sha": code_pin[:7], "code": { "repository": "PolicyEngine/microcosm", @@ -990,18 +1001,20 @@ def _stage_and_finalize( for gate_id, entry in gates.items() if isinstance(entry, Mapping) }, + "attempt_id": attempt_id, + "cut_tag": cut_tag, "created_at": created_at, "staging": dict(staging_delivery), } _write_json(release_dir / "build_manifest.json", build_manifest) - def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: + def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: return { "kind": kind, "path": path, "repo_id": _REPO_ID, + "revision": cut_tag, "sha256": sha256, - "role": release_artifact_role(key, kind), } evidence_files = ( @@ -1038,16 +1051,19 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: "is_default": False, "default_datasets": {}, "namespace": _NAMESPACE, - "release": UK_DENSE_RELEASE_ID, - "build": attempt_id, - "built_at": created_at, - "built_with_core_package": { - "name": "policyengine-core", - "version": runtime["policyengine-core"], - }, - "built_with_model_package": { - "name": "policyengine-uk", - "version": runtime["policyengine-uk"], + "build": { + "build_id": UK_DENSE_RELEASE_ID, + "built_at": created_at, + "built_with_core_package": { + "name": "policyengine-core", + "version": runtime["policyengine-core"], + }, + "built_with_model_package": { + "name": "policyengine-uk", + "version": runtime["policyengine-uk"], + }, + "attempt_id": attempt_id, + "cut_tag": cut_tag, }, "compatible_core_packages": [ { @@ -1060,25 +1076,18 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: ], "artifacts": { _DATASET_KEY: { - **artifact( - _DATASET_KEY, "microdata", _DATASET_FILENAME, measured["candidate"] - ), + **artifact("microdata", _DATASET_FILENAME, measured["candidate"]), "spi_public_use_tape_dependent": bool(spi_marker["dependent"]), }, **{ - Path(name).stem: artifact( - Path(name).stem, "diagnostics", name, evidence_sha[name] - ) + Path(name).stem: artifact("diagnostics", name, evidence_sha[name]) for name in evidence_files if name != "build_manifest.json" }, }, "reviewed_limitations": gate_summary["reviewed_limitations"], "area_support": _area_support_block(solve), - "description": ( - "UK dense joint national + local release build assembled from " - f"attempt {attempt_id}; never the default release." - ), + "description": f"UK dense joint national + local line assembled from attempt {attempt_id} at immutable cut {cut_tag}; inspect lane, never the default slot.", "publisher_labels": { "obr": "Office for Budget Responsibility", "hmrc": "HM Revenue and Customs", @@ -1103,46 +1112,34 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: for contract_warning in contract_warnings: print(f"warning: {contract_warning}", file=sys.stderr) release_dir.rename(destination) - # Each new dense build becomes current. While the repository keeps its - # latest*.json pointer files the emitter refuses any change to a current - # build, a publication with --make-current included (after the upload's - # hashing), so the build is listed first and promoted once those files are - # deleted. Without them, --make-current publishes it as current at once. publish_command = shlex.join( [ "uv", "run", - "microcosm-publish-release-build", + "python", + "-m", + "microcosm.data.publish_cli", str(destination), "--repo-id", _REPO_ID, "--artifact-root", str(artifact_root), - ] - ) - promote_command = shlex.join( - [ - "uv", - "run", - "microcosm-publish-release-build", - str(destination), - "--repo-id", - _REPO_ID, - "--promote", + "--no-latest", + "--tag-only", + "--tag-name", + cut_tag, ] ) return { "release_id": UK_DENSE_RELEASE_ID, - "release": UK_DENSE_RELEASE_ID, - "build": attempt_id, "release_dir": str(destination), + "cut_tag": cut_tag, "dataset": { "path": str(artifact_root / _DATASET_FILENAME), "sha256": measured["candidate"], }, "evidence": {name: _sha256(destination / name) for name in evidence_files}, "publish_command": publish_command, - "promote_command": promote_command, "warnings": contract_warnings, } @@ -1173,6 +1170,7 @@ def _parse_args(argv: list[str] | None) -> argparse.Namespace: type=Path, help="where the published H5 is cloned (default: beside the candidate)", ) + parser.add_argument("--cut-tag") parser.add_argument( "--allow-missing-staging", action="store_true", diff --git a/tools/assemble_uk_release_dir.py b/tools/assemble_uk_release_dir.py index d4ab612d2c..decc753c08 100644 --- a/tools/assemble_uk_release_dir.py +++ b/tools/assemble_uk_release_dir.py @@ -1,16 +1,9 @@ -"""Assemble a certified UK national candidate into a publishable release build. +"""Assemble a certified UK national candidate into a publishable release. This derivative packaging step closes the certification/build-record identity join, mints the calibration weight bundle, writes the two release manifests, copies the signed evidence byte-for-byte, and validates the finished release -directory before printing its publication and promotion commands. - -The national release publishes each build into its own folder, -``releases/microcosm-uk-2024-25-national//``, through the emitter. -The build is the calibration attempt ID, and both manifests name the release -and the build; nothing is tagged. The publication command lists the build -without making it current; the promotion command, run after review, makes -it the release's current build. +directory before printing the inspect-lane publication command. """ from __future__ import annotations @@ -45,8 +38,10 @@ uk_spi_public_use_tape_marker_for_stage_names, ) from microcosm.build.uk_runtime.weight_year import uk_weights_are_at_dataset_year -from microcosm.data.contract import release_artifact_role, validate_release_dir +from microcosm.data.contract import validate_release_dir +_ATTEMPT_PREFIX = "uk-frs-calibration-attempt-" +_ATTEMPT_SUFFIX = re.compile(r"(?P\d{8}T\d{6}Z)-(?P[0-9a-f]{8})") _GIT_COMMIT = re.compile(r"[0-9a-f]{40}") _REPO_ID = "policyengine/populace-uk-private" _DATASET_KEY = "microcosm_uk_2024_25" @@ -261,6 +256,7 @@ def _assemble(args: argparse.Namespace) -> dict[str, object]: measured["spine H5"], signed_input_posture.get("sha256"), ) + cut_tag = _cut_tag(attempt_id, args.cut_tag) spi_marker = _spi_public_use_tape_marker(build_block) runtime = _runtime_versions(build_block, dict(args.runtime_version)) code_pin = _diagnostics_code_pin(diagnostics) @@ -352,6 +348,7 @@ def _assemble(args: argparse.Namespace) -> dict[str, object]: initial_household_weight=initial_household_weight, household_weight_year=household_weight_year, measured=measured, + cut_tag=cut_tag, attempt_id=attempt_id, runtime=runtime, code_pin=code_pin, @@ -381,6 +378,7 @@ def _stage_and_finalize( initial_household_weight: np.ndarray, household_weight_year: Mapping[str, object], measured: Mapping[str, str], + cut_tag: str, attempt_id: str, runtime: Mapping[str, str], code_pin: str, @@ -403,11 +401,8 @@ def _stage_and_finalize( created_at = datetime.now(UTC).isoformat() release_dir = staging_parent / UK_NATIONAL_RELEASE_ID release_dir.mkdir(parents=True) - # The build is the calibration attempt: both manifests name it, and the - # release, so the emitter can publish it into its own folder. build_manifest = { - "release": UK_NATIONAL_RELEASE_ID, - "build": attempt_id, + "build_id": UK_NATIONAL_RELEASE_ID, "code": { "repository": "PolicyEngine/microcosm", "git_commit": code_pin, @@ -443,6 +438,8 @@ def _stage_and_finalize( "calibration_seam": seam_part.get("statuses"), "release_cut": release_cut_part.get("statuses"), }, + "attempt_id": attempt_id, + "cut_tag": cut_tag, "created_at": created_at, "staging": dict(staging_delivery), } @@ -470,33 +467,36 @@ def _stage_and_finalize( ), } - def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: + def artifact(kind: str, path: str, sha256: str) -> dict[str, str]: return { "kind": kind, "path": path, "repo_id": _REPO_ID, + "revision": cut_tag, "sha256": sha256, - "role": release_artifact_role(key, kind), } release_manifest = { "schema_version": 1, - "release": UK_NATIONAL_RELEASE_ID, - "build": attempt_id, - "built_at": created_at, - "built_with_core_package": { - "name": "policyengine-core", - "version": runtime["policyengine-core"], - }, - "built_with_model_package": { - "name": "policyengine-uk", - "version": runtime["policyengine-uk"], - }, "data_package": { "name": "microcosm-data", "version": runtime["microcosm-data"], }, "default_datasets": {"national": _DATASET_KEY}, + "build": { + "build_id": UK_NATIONAL_RELEASE_ID, + "built_at": created_at, + "built_with_core_package": { + "name": "policyengine-core", + "version": runtime["policyengine-core"], + }, + "built_with_model_package": { + "name": "policyengine-uk", + "version": runtime["policyengine-uk"], + }, + "attempt_id": attempt_id, + "cut_tag": cut_tag, + }, "compatible_core_packages": [ { "name": "policyengine-core", @@ -513,19 +513,14 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: # The microdata's own entry says whether it rests on the SPI # Public Use Tape; licensed_data carries the tape's conditions. _DATASET_KEY: { - **artifact( - _DATASET_KEY, "microdata", _DATASET_FILENAME, measured["candidate"] - ), + **artifact("microdata", _DATASET_FILENAME, measured["candidate"]), "spi_public_use_tape_dependent": bool(spi_marker["dependent"]), }, f"{_DATASET_KEY}_calibration": artifact( - f"{_DATASET_KEY}_calibration", - "calibration", - calibration_filename, - calibration_sha, + "calibration", calibration_filename, calibration_sha ), **{ - key: artifact(key, "diagnostics", filename, measured[name]) + key: artifact("diagnostics", filename, measured[name]) for key, (_source, filename), name in ( ( "calibration_diagnostics", @@ -561,8 +556,8 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: }, }, "description": ( - "UK national calibration pipeline release build assembled from " - f"attempt {attempt_id}." + "UK national calibration pipeline release assembled from attempt " + f"{attempt_id} at immutable cut {cut_tag}." ), "publisher_labels": _uk_publisher_labels(), "licensed_data": {UK_SPI_PUBLIC_USE_TAPE_KEY: dict(spi_marker)}, @@ -595,36 +590,45 @@ def artifact(key: str, kind: str, path: str, sha256: str) -> dict[str, str]: npz_destination.unlink(missing_ok=True) raise - # Publication lists the build without making it current; the reviewed - # promotion is the second command. publish_command = shlex.join( [ "uv", "run", - "microcosm-publish-release-build", + "python", + "-m", + "microcosm.data.publish_cli", str(destination), "--repo-id", _REPO_ID, "--artifact-root", str(args.candidate_h5.parent), + "--no-latest", + "--tag-name", + cut_tag, ] ) promote_command = shlex.join( [ "uv", "run", - "microcosm-publish-release-build", + "python", + "-m", + "microcosm.data.publish_cli", str(destination), "--repo-id", _REPO_ID, - "--promote", + "--artifact-root", + str(args.candidate_h5.parent), + "--promote-line", + "national", + "--tag-name", + cut_tag, ] ) return { "release_id": UK_NATIONAL_RELEASE_ID, - "release": UK_NATIONAL_RELEASE_ID, - "build": attempt_id, "release_dir": str(destination), + "cut_tag": cut_tag, "dataset": { "path": str(args.candidate_h5), "sha256": measured["candidate"], @@ -658,6 +662,7 @@ def _parse_args(argv: list[str] | None) -> argparse.Namespace: parser.add_argument("--release-cut-gate-json", type=Path) parser.add_argument("--score-receipt", required=True, type=Path) parser.add_argument("--out-dir", type=Path, default=Path("releases")) + parser.add_argument("--cut-tag") parser.add_argument( "--runtime-version", action="append", @@ -769,6 +774,30 @@ def _diagnostics_code_pin(diagnostics: Mapping[str, object]) -> str: return code_pin +def _cut_tag(attempt_id: str, override: str | None) -> str: + prefix = UK_NATIONAL_RELEASE_ID + "-" + if override is not None: + # The override may re-tag a cut but never leave the grammar the + # contract validates: prefix plus an attempt-shaped suffix. + if not override.startswith(prefix) or not _ATTEMPT_SUFFIX.fullmatch( + override[len(prefix) :] + ): + raise SystemExit( + f"error: --cut-tag must be {prefix}-" + ) + return override + if not attempt_id.startswith(_ATTEMPT_PREFIX): + raise SystemExit( + f"error: build_record.build_id must start with {_ATTEMPT_PREFIX!r}" + ) + suffix = attempt_id.removeprefix(_ATTEMPT_PREFIX) + if not _ATTEMPT_SUFFIX.fullmatch(suffix): + raise SystemExit( + "error: build_record.build_id must end with -" + ) + return f"{UK_NATIONAL_RELEASE_ID}-{suffix}" + + def _load_json(path: Path, *, label: str) -> Mapping[str, object]: return _load_json_bytes(path.read_bytes(), label=label) From 392deaaea4e2ce624e76ea9d3c26cabb64473b3f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:43:55 +0400 Subject: [PATCH 19/26] Describe today's UK release flow in the docs again The README's release section, the agent guide, the UK national and dense runbooks and microcosm-data's README are main's again: UK builds are assembled with tags, published and promoted through latest*.json pointer files with tools/publish_release.sh, and announced in Slack, until their repository switches to releases.json. This also takes out review round 1's wording for that period, which a narrower plan replaces. Part of the split for the switch: reverting this commit re-applies the documentation of the UK flow through the emitter. Co-Authored-By: Claude Opus 5.5 --- README.md | 64 ++------- docs/agent-guide.md | 17 +-- docs/uk-dense-release-assembly-runbook-762.md | 83 ++++-------- ...k-national-release-assembly-runbook-806.md | 126 ++++++++---------- packages/microcosm-data/README.md | 16 +-- 5 files changed, 103 insertions(+), 203 deletions(-) diff --git a/README.md b/README.md index 9d68ec9114..cc0ac6a665 100644 --- a/README.md +++ b/README.md @@ -424,59 +424,24 @@ and `calibration_diagnostics.v8.schema.json` beside it, for consumers that check the file without importing them, such as the collector. Its description lists the model rules a JSON Schema cannot express; see the [package README](packages/microcosm-diagnostics/README.md). -Publication runs on the build machine (it needs the freshly built H5), so it -isn't a CI step. Releases use one of two layouts. - -**The UK national, dense and local-area releases publish each build into its -own folder.** These releases (`microcosm.data.contract.publishes_to_build_folder`) -hand each build to the separately installed emitter, whose release writer -puts it in `releases///` and records it in the repository's -`releases.json`, the only record of each release's builds and which one is -current, in one commit. The build is the calibration attempt id. Both -manifests name the release and the build as strings; the release manifest -records `built_at`, `built_with_model_package` and `built_with_core_package` -at its top level and each file's `role`, and pins no revision. Nothing is -tagged and no pointer file is written: - -```bash -uv run microcosm-publish-release-build releases/ \ - --repo-id policyengine/populace-uk-private --artifact-root \ - [--make-current] -uv run microcosm-publish-release-build releases/ --promote -``` - -The first command publishes a build, and makes it current with -`--make-current`; the second makes a published build current. A build counts -as current only when the emitter's receipt is `published` and names it as -`current`. While the older `latest*.json` pointer files exist, the emitter -refuses every change to a release's current build, so until they are deleted -a build is published without `--make-current` and promoted afterwards. The -command refuses before it starts an emitter when `HF_HUB_OFFLINE` or -`TRANSFORMERS_OFFLINE` is set, and hands nothing over unless the emitter's -write-access check passes. These publications send no Slack alert: release -alerts for them stop until the dashboard posts them from `releases.json`. -The UK assemblers print the exact commands, and the -[national](docs/uk-national-release-assembly-runbook-806.md) and -[dense](docs/uk-dense-release-assembly-runbook-762.md) runbooks describe them. -`microcosm.data.load` reads the current build of such a release from -`releases.json`, or the listed build `build=` names. - -**Every other release keeps tags and `latest.json`:** every US release, -until the stable releases US builds publish under are agreed with the US data -builder, and the UK releases outside those three, namely the June 2023 release -and `populace-uk---k` releases. Publication uploads the locally -built `releases//` artifacts to the Hugging Face dataset, tags the release, -and updates `latest.json`: +Standard publication uploads the locally built `releases//` artifacts to +the Hugging Face dataset, tags the release, and updates `latest.json`. It runs +on the build machine (it needs the freshly built H5), so it isn't a CI step: ```bash tools/publish_release.sh releases/ --repo-id policyengine/populace-us ``` `tools/publish_release.sh` is a thin wrapper around `microcosm-publish-release` -(all arguments pass straight through), which refuses the releases that -publish into build folders. The moment `latest.json` goes live, the publish -CLI posts a release alert to the country's channel: `#populace-us`, or -`#populace-uk` for a UK release published this way. +(all arguments pass straight through). The moment `latest.json` goes live, the +publish CLI posts a release alert to Slack — `#populace-us` or `#populace-uk`, +chosen from the repo id. + +Promotable UK release lines use pointers named `latest-.json`. Publish a +cut for inspection with `--no-latest --tag-name `, then promote the +reviewed cut with `--promote-line --tag-name `. Promotion moves +only that line pointer; the UK repository-global `latest.json` remains frozen +on the June 2023 release. Promotion reuses the immutable cut tag the inspect publication created (it checks the tagged manifest is byte-identical) and writes only the pointer commit, so the two-step sequence and a retry after a failed pointer commit both work. A line's registry entry is registered off the default variant until its first promotion; the default flips in a follow-up after the pointer exists. The publisher uploads only the contract files, the release manifest's artifacts and any `--extra-file`. The US fiscal-refresh tool therefore binds @@ -596,9 +561,8 @@ cp tools/release.env.example tools/release.env # then paste the webhook URLs `tools/release.env` is gitignored; the wrapper loads it (or you can just export `SLACK_WEBHOOK_POPULACE_US` / `SLACK_WEBHOOK_POPULACE_UK` in your shell) and -warns if neither is set. After that, every release published with tags and -`latest.json` publishes with an automatic Slack alert. The releases that -publish into build folders read neither variable. +warns if neither is set. After that, every release publishes with an automatic +Slack alert. Canonical UK exact-k builds also require a stable, base64-encoded 32-byte release key. Source `tools/release.env` before the national build as well as diff --git a/docs/agent-guide.md b/docs/agent-guide.md index b0905b1425..c21f982c5b 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -264,19 +264,10 @@ no secret. Green PR checks mean the code contracts hold — they do **not** certify data artifacts. Builds, calibrations, and releases run outside PR CI, need gated Hugging Face data and credentials, and cannot run from forks. Release publication is a -deliberate human step. A US release publishes with tags and `latest.json` -(`tools/publish_release.sh` → `microcosm-publish-release`), checked by -`tools/preflight_us_release_gates.py`; so do the June 2023 UK release and -`populace-uk---k` releases. The UK national, dense and -local-area releases publish each build into its own folder through the -emitter (`microcosm-publish-release-build`, from -`microcosm.build.release_publication`), which records it in the repository's -`releases.json`; making a published build current is a separate deliberate -call to the same command with `--promote`. The emitter refuses that while the -older `latest*.json` pointer files exist. Tests hand release changes to the -in-memory client (`client.release_requests`), which applies them to -`hub_files` with the interface's shared `releases.json` checks. See README -"Releasing & alerts". Before launching a US +deliberate human step (`tools/publish_release.sh` → +`microcosm-publish-release`), gated by `tools/preflight_us_release_gates.py`; +reviewed line promotion is a separate deliberate call to the same CLI with +`--promote-line`. See README "Releasing & alerts". Before launching a US release, dry-run it with `tools/dry_run_us_release_gates.py` (or the release tool's `--dry-run-gates-report`). It replays the release's own input stages and grades every waiver register on the staged frame before the solve; see README diff --git a/docs/uk-dense-release-assembly-runbook-762.md b/docs/uk-dense-release-assembly-runbook-762.md index 215253fb21..8eaf2185e6 100644 --- a/docs/uk-dense-release-assembly-runbook-762.md +++ b/docs/uk-dense-release-assembly-runbook-762.md @@ -5,14 +5,10 @@ through the atomic output-area assignment and calibrated to the national and loc target surfaces in one solve (`microcosm-build-uk --release-role dense`, the graph driver `tools/build_uk_full.py`; `tools/build_uk_rowwise_candidate.py` is a stub over it). It ships -as its own release, never the default one: a constant release id, -`dataset_role: non_default_local_area` (the role `local_area` in -`releases.json`) and an empty `default_datasets` map. Each build is published -once into its own folder, `releases/microcosm-uk-2024-25-dense//`, -through the emitter, and becomes the dense release's current build: by a -promotion once the older `latest*.json` pointer files are deleted, and when it -is published after that (see [§5](#5-publish-human-step)); `releases.json` -keeps the national release as the repository's default. It is registered as `("uk", 2025, "dense")` in the private repo +on the **inspect lane only**: a constant release id, an immutable per-cut tag, +`dataset_role: non_default_local_area`, an empty `default_datasets` map, and +`--no-latest` at publication, so it can never displace the default artifact. +It is registered as `("uk", 2025, "dense")` in the private repo `policyengine/populace-uk-private`. Publication is a separate human step. Since microcosm#1124 (ruling of 2026-10-13, amended for microcosm#1301) the line may ship the 150,000-household exact-k selection from that pool instead @@ -531,11 +527,9 @@ id, and the full gate report `outputs.full_gate_report` against its digest), requires the manifest's `staging_delivery` receipt (the run's version 2 staging telemetry evidence, copied into `build_manifest.json` as `staging` so publication can apply its undelivered-staging refusal, as on the national -lane), re-runs the candidate pre-flight, names the build after the run's -attempt id in both manifests (`release` and `build`; the release manifest -also records `built_at` and the built-with packages at its top level and each -file's `role`, and no artifact pins a revision), clones the H5 beside itself -as `microcosm_uk_2024_25_dense.h5`, stages +lane), re-runs the candidate pre-flight, mints the cut tag +`microcosm-uk-2024-25-dense--` from the run's attempt +id, clones the H5 beside itself as `microcosm_uk_2024_25_dense.h5`, stages `build_manifest.json`, `release_manifest.json`, `calibration_diagnostics.json`, `gate_summary.json`, `uk_source_coverage.json`, the signed `uk_local_gates.json`, the original `rowwise_candidate_manifest.json`, @@ -590,59 +584,30 @@ repeats its warnings. Separate support and binding adjudications keep their own policies. The gate thresholds and existing approvals have not been widened or renewed. -## 5. Publish (human step) +## 5. Publish for inspection (human step) -The assembler prints two commands. Run its `publish_command` first. Its shape -is: +Run the printed command. Its shape is: ```bash -uv run microcosm-publish-release-build releases/microcosm-uk-2024-25-dense \ - --repo-id policyengine/populace-uk-private --artifact-root +uv run python -m microcosm.data.publish_cli releases/microcosm-uk-2024-25-dense \ + --repo-id policyengine/populace-uk-private --artifact-root \ + --no-latest --tag-only --tag-name microcosm-uk-2024-25-dense-- ``` -It refuses at once, before it starts an emitter, when `HF_HUB_OFFLINE` or -`TRANSFORMERS_OFFLINE` is set, since the emitter inherits them and could not -reach the Hub. It checks the build against the release contract again, starts -the emitter, and hands nothing over unless the emitter's write-access check -finds a credential that can write the repository. It then hands every file to -the emitter with its role and SHA-256. The emitter writes the build's folder -and `releases.json` in one commit, listing the build without making it -current. The command prints the receipt: `status` is `published`, `pending` -(the emitter is still trying, and keeps the change queued for an hour), -`refused` with an `error_code`, or `unavailable` (no emitter answered). It -succeeds only on `published`. Running the same command again is safe: an -already published build with the same release manifest is reported -`published`. - -Each new dense build then becomes the dense release's current build with the -assembler's `promote_command`: +`--no-latest` is mandatory and enforced: publication refuses to move +`latest.json` for a non-default role. `--tag-only` publishes the immutable tag +revision without a main-branch commit. The artifact is reachable by its tag and +by the registry key `("uk", 2025, "dense")` only. -```bash -uv run microcosm-publish-release-build releases/microcosm-uk-2024-25-dense \ - --repo-id policyengine/populace-uk-private --promote -``` - -While the repository still holds the older `latest*.json` pointer files, the -emitter refuses every change to a release's current build -(`POINTER_FILES_PRESENT`), so that the pointer files and `releases.json` -cannot disagree. Until they are deleted, the promotion is refused at once, -changes nothing and says to run it again; the published build stays listed. -Run `promote_command` once they are deleted. The promotion succeeds only when -the receipt is `published` and names this build as `current`; a change to the -dense release's current build requested after this one can land first and -leave another build current. - -Once the pointer files are deleted, a new dense build can instead be published -as current in one commit by adding `--make-current` to `publish_command`. Do -not add it before then: the emitter refuses the whole publication, after the -dataset is hashed on both sides, and nothing is published. - -A contract warning reaches the command's stderr, and `--preflight-only` adds -it to its verdict under `contract_warnings`. Neither refuses on one. No dense +A contract warning reaches the publisher's JSON output as well as stderr: +`--preflight-only` adds it to its verdict under `contract_warnings`, and +publication lists it the same way beside the pointer it prints. Neither +refuses on one. The immutable tag's message records that the release was +published past them and how many there were, never what they say. No dense release raises any since the disclosure walk was dropped. ## Promotion is a separate change -Making the dense release (or a sparse successor via the L0 penalty, #762 I10) -the default dataset is a registry and contract change with its own review; -nothing in this runbook changes the repository's default release. +Making the dense line (or a sparse successor via the L0 penalty, #762 I10) a +default dataset is a registry and contract change with its own review; nothing +in this runbook promotes anything. diff --git a/docs/uk-national-release-assembly-runbook-806.md b/docs/uk-national-release-assembly-runbook-806.md index 1aff4f24a9..38a19e3e6c 100644 --- a/docs/uk-national-release-assembly-runbook-806.md +++ b/docs/uk-national-release-assembly-runbook-806.md @@ -1,12 +1,9 @@ # UK national release assembly runbook (#806) -This runbook turns a green UK national calibration candidate into a -published build of the national release, `microcosm-uk-2024-25-national`, -and then, after review, makes it the release's current build. Each build is -published once into its own folder, -`releases/microcosm-uk-2024-25-national//`, through the emitter, and -the repository's `releases.json` records which build is current. The build is -the calibration attempt id; nothing is tagged. +This runbook turns a green UK national calibration candidate into an +inspectable release without promoting it to `latest.json`. The release id is +constant across cuts (`microcosm-uk-2024-25-national`); each cut gets an +immutable tag derived from the calibration attempt id. Do not run this sequence in PR CI. Calibration, certification, assembly, and publication consume licensed data and operator credentials. @@ -18,14 +15,11 @@ Before starting, export: - `MICROCOSM_UK_TERMINAL_GATE_SIGNING_KEY`, containing the stable release key as base64-encoded 32 bytes. Certification signs with it and assembly uses it to re-verify the copied certification. -- `HF_TOKEN` (or `HUGGINGFACE_TOKEN`, or a token saved by `hf auth login`), - with write access to `policyengine/populace-uk-private`. The publication - command starts the separately installed `microcosm-emitter` (0.11.9 or - later) as its child process, and the emitter uses the token it inherits. - -Publication sends no Slack alert. Alerts for new and current builds will come -from the dashboard, which compares `releases.json` before and after each -change; until that is in place, announce a build by hand. +- `HF_TOKEN`, authenticated for write access to + `policyengine/populace-uk-private`. +- `SLACK_WEBHOOK_POPULACE_UK`, for the eventual promoted-release alert. The + inspect publication below uses `--no-latest`, so it does not announce a new + latest release. Keep the spine H5, its sibling `.build.json` and `.spine_gates.json`, the Ledger consumer artifact and manifest digest, and the licensed input-mass @@ -71,8 +65,8 @@ no overrides. It writes `microcosm_uk_2024_25.h5`, surface takes its band edges from) and `rowwise_candidate_manifest.json` into ``. The build record's id has the form -`uk-frs-calibration-attempt--`; it is the build's -name in both release manifests and in its folder on the Hub. +`uk-frs-calibration-attempt--`; assembly derives the +per-cut tag from that suffix. ## 2. Score and certify the cut @@ -150,13 +144,11 @@ uv run --no-sync python tools/assemble_uk_release_dir.py \ ``` The output is -`releases/microcosm-uk-2024-25-national/`. Both manifests name the release -and the build (`release` and `build`), the release manifest records -`built_at`, `built_with_model_package` and `built_with_core_package` at its -top level and each file's `role` (`dataset`, `calibration_weights`, -`calibration_diagnostics`, and each evidence file's key), and no artifact -pins a revision. The JSON summary records every digest, the release and the -build, and the exact publication and promotion commands. +`releases/microcosm-uk-2024-25-national/`. The JSON summary records every +digest, the derived cut tag, and the exact publication command. Use +`--cut-tag microcosm-uk-2024-25-national--` only to +override the derived tag deliberately; the override must keep that grammar, +which the contract validates on every artifact revision. Assembly stages into a private directory, validates there, and atomically renames into empty destinations: re-assembling a cut requires removing the @@ -171,39 +163,46 @@ as an operator cross-check but refuses to replace one. Run the assembler's `publish_command` first. Its shape is: ```bash -uv run microcosm-publish-release-build \ +uv run python -m microcosm.data.publish_cli \ releases/microcosm-uk-2024-25-national \ --repo-id policyengine/populace-uk-private \ - --artifact-root + --artifact-root \ + --no-latest \ + --tag-name microcosm-uk-2024-25-national-- ``` -It refuses at once, before it starts an emitter, when `HF_HUB_OFFLINE` or -`TRANSFORMERS_OFFLINE` is set, since the emitter inherits them and could not -reach the Hub. It checks the build against the release contract again, -starts the emitter, and hands nothing over unless the emitter's write-access -check finds a credential that can write the repository. It then hands every -file to the emitter with its role and SHA-256. The emitter writes the build's -folder and `releases.json` in one commit, listing the build without making -it current. The command waits for the emitter's answer and prints its -receipt: `status` is `published`, `pending` (the emitter is still trying, and -keeps the change queued for an hour), `refused` with an `error_code`, or -`unavailable` (no emitter answered). -Running the same command again is safe: a build already published with the -same release manifest is reported `published`, and one published with a -different manifest is refused (`BUILD_FOLDER_EXISTS`), since a build is never -changed after publishing. `--preflight-only` runs the checks and starts no -emitter. - The assembler also prints this `promote_command`; keep it for §6 and run it -only after the build passes the review in §5: +only after the cut passes the review in §5: ```bash -uv run microcosm-publish-release-build \ +uv run python -m microcosm.data.publish_cli \ releases/microcosm-uk-2024-25-national \ --repo-id policyengine/populace-uk-private \ - --promote + --artifact-root \ + --promote-line national \ + --tag-name microcosm-uk-2024-25-national-- ``` +Do not omit `--tag-name`, and do not pass `--no-create-tag`: every artifact in +the manifest is pinned to that immutable per-cut tag. `--no-latest` is +mandatory for the inspect publication. The promotion command replaces it with +`--promote-line national`; the CLI requires that flag to accompany +`--tag-name` and refuses to combine it with `--no-latest`. A per-cut tag without +either flag cannot move the repository-global `latest.json`. + +The two commands share the cut tag by design: the promotion recognises the +immutable tag the inspect publication created, checks that the tagged +`release_manifest.json` is byte-identical to the local one, creates no second +immutable revision, and writes only the main commit carrying +`latest-national.json`. The same recognition makes a retry safe after a +failure between tag creation and the pointer commit: rerun the same command. +A tag that describes another release refuses; publish under a fresh cut tag. + +Only a failure before the tag exists (the staging commit itself) can leave +the constant branch `release-staging/microcosm-uk-2024-25-national` behind. +Delete that branch manually in the private Hugging Face repository before +retrying. Never delete an immutable cut tag. + ## 5. Inspect on the dashboard Open the calibration-diagnostics dashboard with: @@ -216,26 +215,19 @@ Adjudicate the release using the copied certification, scoped gate reports, calibration diagnostics, and score receipt. The release remains inspect-only until that review is complete. -The dashboard shows a build published into its own folder only once it reads -`releases.json`; until then, review the assembled directory's files. - -## 6. Make the reviewed build current +## 6. Promote the reviewed cut After completing the review in §5, run the assembler's `promote_command` shown -in §4. The emitter sets the national release's `current` in `releases.json` -to this build. The command succeeds only when the receipt is `published` and -names this build as `current`. - -While the repository still holds the older `latest*.json` pointer files, the -emitter refuses every change to a release's current build -(`POINTER_FILES_PRESENT`), so that the pointer files and `releases.json` -cannot disagree. Until those files are deleted, a build can be published but -not made current: the promotion is refused at once, changes nothing and says -to run it again, and the published build stays listed. Run `promote_command` -again once they are deleted. - -The 2025 national release is the default UK load (microcosm#823): -`microcosm.data.load("uk")` and `microcosm.data.load("uk", 2025)` read its -current build from `releases.json`, and `load(..., build=)` loads a -listed build instead. An explicit `microcosm.data.load("uk", 2023)` -continues to follow `latest.json`. +in §4. The promotion moves only `latest-national.json`, recording `national` as +the line and the reviewed cut tag as its `revision`. It never moves the +repository-global `latest.json`, which remains on the June 2023 release. + +The 2025 national entry was registered off the default variant until the +first promotion, so that a default load never chased a pointer that did not +exist yet. The first certified cut was promoted on 2026-10-26, and the entry +is now the default variant (microcosm#823): `microcosm.data.load("uk")` and +`microcosm.data.load("uk", 2025)` follow `latest-national.json`. An explicit +`microcosm.data.load("uk", 2023)` continues to follow `latest.json`. + +With `SLACK_WEBHOOK_POPULACE_UK` configured, successful promotion sends an +alert naming the `national` line and the promoted revision. diff --git a/packages/microcosm-data/README.md b/packages/microcosm-data/README.md index 1f9db0d4bd..5561b14dd2 100644 --- a/packages/microcosm-data/README.md +++ b/packages/microcosm-data/README.md @@ -22,16 +22,7 @@ sim.calculate("household_net_income", 2024).sum() `load("us")` (no year) loads the latest published compact year. It resolves `latest.json`, reads the selected release manifest at the immutable release tag, verifies the artifact SHA-256, and refuses model or Core versions outside -the release's certified compatibility specifiers. - -The UK national, dense and local-area releases publish each build into its -own folder, `releases///`, and the repository's -`releases.json` records which build of each release is current. `load("uk")` -(the 2025 national release) and the 2025 dense variant read that record, then -the current build's `release_manifest.json`, then the dataset it names, all -from the build's folder, and check the SHA-256 and engine versions the same -way. `load("uk", build="")` loads a listed build instead (a withdrawn -one with a warning). `available()` lists +the release's certified compatibility specifiers. `available()` lists the default-variant `(country, year)` pairs (the ones a bare ``load(country, year)`` resolves); `available_variants()` lists every published `(country, year, variant)`, non-default lines included. @@ -39,7 +30,6 @@ resolves); `available_variants()` lists every published The old mutable-root behavior is available only as an unsafe escape hatch: `load("us", 2024, unverified_root=True)`. It emits a runtime warning because it bypasses the release pointer, manifest, digest, and engine compatibility checks. -A build-folder release has no root file, so it refuses the option. ## Why a shard, not a repo per country @@ -78,9 +68,7 @@ benchmark comparisons live outside this package. ## Release contract -Published US releases, and the UK releases that keep tags, live under -`releases//` in the Hub dataset repo, and builds of the UK -national, dense and local-area releases under `releases///`. +Published releases live under `releases//` in the Hub dataset repo. Each release must include `build_manifest.json` and `release_manifest.json`; US releases must also include `us_source_coverage.json`. A current release manifest contains a typed `calibration_diagnostics` status. `available` binds a From ae0e3271a381c565a5ebacb701a76ac629c81253 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:48:49 +0400 Subject: [PATCH 20/26] Test the two publishers' refusals and the loader's pointer-file fallback So that no UK release is ever left without a way to change its current build, each publication path refuses a repository in the other's layout: - the tagged publisher refuses a repository that has releases.json, before it writes a tag, a commit or a pointer file; - microcosm-publish-release-build refuses a repository that still has any latest*.json file, or whose files it cannot list, before any emitter starts. For a registry entry that names a release, the loader reads releases.json where the repository has one and otherwise follows its pointer file as before (main's line-pointer tests come back for that path), so load("uk") no longer fails for want of releases.json; only the file's absence, not any other error, falls back. The root-file escape hatch is refused only once releases.json exists. A POINTER_FILES_PRESENT refusal now points to tools/publish_release.sh, and review round 1's separate promotion advice goes, since the up-front refusal covers that case. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_release_publication.py | 97 ++++- .../tests/engine_free/shared/test_loader.py | 353 +++++++++++++++++- .../tests/engine_free/shared/test_registry.py | 13 + .../tests/engine_free/shared/test_release.py | 61 +++ 4 files changed, 495 insertions(+), 29 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py index d8f0dae0ea..6beda3d720 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py @@ -10,6 +10,7 @@ from __future__ import annotations import json +from dataclasses import dataclass, field from pathlib import Path import pytest @@ -49,16 +50,39 @@ } +@dataclass +class HubListing: + """The dataset repository's file list as the command reads it. + + ``files`` is what it lists, and ``listed`` the repositories it asked for. + """ + + files: list[str] = field(default_factory=list) + listed: list[str] = field(default_factory=list) + + @pytest.fixture(autouse=True) -def _hub_online(monkeypatch) -> None: +def hub_listing(monkeypatch) -> HubListing: """Run each test as on a build machine that can reach the Hub. Local test runs set ``HF_HUB_OFFLINE``, and the command refuses to start an emitter with it set. Every emitter here is the in-memory client, and - the repository's root fixture refuses to start a real one. + the repository's root fixture refuses to start a real one. The file list + the command reads, to refuse a repository that still has pointer files, + is in memory too and empty unless a test adds to it. """ for name in OFFLINE_VARIABLES: monkeypatch.delenv(name, raising=False) + listing = HubListing() + + def list_files(repository: str) -> list[str]: + listing.listed.append(repository) + return list(listing.files) + + monkeypatch.setattr( + release_publication, "_repository_files", list_files, raising=False + ) + return listing @pytest.fixture @@ -170,7 +194,10 @@ def test_pointer_files_refuse_a_build_made_current( assert outcome.receipt["status"] == "refused" assert outcome.receipt["error_code"] == "POINTER_FILES_PRESENT" - assert "without --make-current" in outcome.explanation() + # The command refuses such a repository before handing anything over; + # this is a pointer file that appeared after that check. + assert "tools/publish_release.sh" in outcome.explanation() + assert "without --make-current" not in outcome.explanation() assert (UK_REPO_ID, "releases.json") not in client.hub_files @@ -395,29 +422,65 @@ def test_the_command_fails_and_explains_a_change_that_did_not_land( assert client.closed is True -def test_a_promotion_refused_for_pointer_files_says_to_promote_again_later( +@pytest.mark.parametrize( + "pointer_file", + ["latest.json", "latest-national.json", "releases/old/latest-evidence.json"], +) +@pytest.mark.parametrize("promote", [False, True], ids=["publish", "promote"]) +def test_the_command_refuses_a_repository_with_pointer_files_before_an_emitter( national: Path, artifact_root: Path, # noqa: F811 monkeypatch, capsys, + hub_listing: HubListing, + pointer_file: str, + promote: bool, ) -> None: - """The build is published already, so publishing it again cannot help.""" - _, repository = _start_emitters(monkeypatch) - repository[(UK_REPO_ID, "latest-national.json")] = b"{}" - assert _run([str(national), "--artifact-root", str(artifact_root)], capsys)[0] == 0 + """Until a repository switches to releases.json, its releases publish + and promote through its pointer files, with tools/publish_release.sh.""" + started, repository = _start_emitters(monkeypatch) + hub_listing.files.extend(["README.md", pointer_file]) + argv = ( + [str(national), "--promote"] + if promote + else [str(national), "--artifact-root", str(artifact_root)] + ) - code, output, error = _run([str(national), "--promote"], capsys) + code, output, error = _run(argv, capsys) assert code == 1 - assert (output["status"], output["error_code"]) == ( - "refused", - "POINTER_FILES_PRESENT", + assert started == [] + assert output is None + assert hub_listing.listed == [UK_REPO_ID] + assert "refusing to publish" in error and pointer_file in error + assert "tools/publish_release.sh" in error + assert repository == {} + + +def test_the_command_refuses_when_it_cannot_list_the_repository( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, +) -> None: + started, _ = _start_emitters(monkeypatch) + + def unlistable(repository: str) -> list[str]: + raise OSError(f"401 Client Error for {repository}") + + monkeypatch.setattr( + release_publication, "_repository_files", unlistable, raising=False ) - assert "without --make-current" not in error - assert "stays published but is not current" in error - assert "Run this --promote command again once the pointer files" in error - record = json.loads(repository[(UK_REPO_ID, "releases.json")]) - assert record["releases"][UK_NATIONAL_RELEASE_ID]["current"] is None + + code, output, error = _run( + [str(national), "--artifact-root", str(artifact_root)], capsys + ) + + assert code == 1 + assert started == [] + assert output is None + assert f"could not list the files of {UK_REPO_ID}" in error + assert "401 Client Error" in error @pytest.mark.parametrize("variable", OFFLINE_VARIABLES) diff --git a/packages/microcosm-data/tests/engine_free/shared/test_loader.py b/packages/microcosm-data/tests/engine_free/shared/test_loader.py index a002689b49..6d6c5e4b5e 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_loader.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_loader.py @@ -25,6 +25,8 @@ from microcosm.data.release import ( LATEST_POINTER_PATH, latest_pointer_payload, + line_pointer_path, + line_pointer_payload, ) from test_support.microcosm_data.build_folders import ( UK_LOCAL_BUILD, @@ -43,6 +45,11 @@ UK_NATIONAL_RELEASE_ID = "microcosm-uk-2024-25-national" UK_LOCAL_RELEASE_ID = "microcosm-uk-2024-25-local-k15" UK_TAGGED_ARTIFACT = b"certified UK line artifact" +#: Until a repository switches to releases.json, UK releases are tagged and +#: made current through latest-.json pointer files. +UK_NATIONAL_CUT_TAG = f"{UK_NATIONAL_RELEASE_ID}-20260920T120000Z-deadbeef" +UK_LOCAL_LINE = "local-k15" +UK_LOCAL_CUT_TAG = f"{UK_LOCAL_RELEASE_ID}-20260920T120000Z-cafebabe" #: An earlier national build, still listed in releases.json. UK_EARLIER_BUILD = "uk-frs-calibration-attempt-20260901T000000Z-0badcafe" @@ -558,8 +565,12 @@ def unexpected_download(**_kwargs) -> str: def test_unverified_root_loading_is_refused_for_a_build_folder_release( - monkeypatch: pytest.MonkeyPatch, + monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: + """Once the repository records its builds in releases.json, it has no + root file to load.""" + hub = _build_folder_hub(tmp_path, manifest=_uk_build_folder_manifest()) + monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) monkeypatch.setattr( loader, "_dataset_class", @@ -567,6 +578,35 @@ def test_unverified_root_loading_is_refused_for_a_build_folder_release( ) with pytest.raises(ValueError, match="no root file"): load("uk", 2025, unverified_root=True) + assert hub.calls == [(UK_REPO_ID, "releases.json", None)] + + +def test_unverified_root_loading_reads_the_root_file_before_the_switch( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """Without releases.json the repository still has its root file, and the + escape hatch loads it as before.""" + hub = FakeHubDownload(tmp_path) + hub.calls.clear() + hub.files.clear() + hub._add(tmp_path, UK_REPO_ID, "microcosm_uk_2024_25.h5", None, b"root file") + monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) + constructed: list[str] = [] + + class FakeDataset: + def __init__(self, *, file_path: str) -> None: + constructed.append(file_path) + + monkeypatch.setattr(loader, "_dataset_class", lambda _spec: FakeDataset) + + with pytest.warns(RuntimeWarning, match="UNVERIFIED"): + load("uk", 2025, unverified_root=True) + + assert [Path(path).read_bytes() for path in constructed] == [b"root file"] + assert hub.calls == [ + (UK_REPO_ID, "releases.json", None), + (UK_REPO_ID, "microcosm_uk_2024_25.h5", None), + ] def test_download_verifies_the_build_folder_dataset( @@ -625,7 +665,7 @@ def test_resolve_uk_2023_still_uses_latest_json(tmp_path: Path) -> None: ] -@pytest.mark.parametrize("pointer_path", ["current.json", "latest-national.json"]) +@pytest.mark.parametrize("pointer_path", ["current.json", "latest-local-k0.json"]) def test_resolve_refuses_an_unsupported_pointer_path(pointer_path: str) -> None: spec = replace(resolve("us", 2024), pointer_path=pointer_path) @@ -759,6 +799,288 @@ def test_loader_refuses_an_unknown_dataset_role(tmp_path: Path) -> None: loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) +# Before the switch: a repository without releases.json ----------------------- +# A UK release keeps publishing with tags and latest-.json pointer files +# until its repository switches to releases.json. A registry entry that names +# a release reads releases.json where the repository has one, and otherwise +# follows its pointer file exactly as before. + + +def _uk_national_line_manifest() -> dict: + return _uk_release_manifest( + release_id=UK_NATIONAL_RELEASE_ID, revision=UK_NATIONAL_CUT_TAG + ) + + +def _uk_local_line_spec() -> DatasetSpec: + return replace(_uk_local_spec(), pointer_path=line_pointer_path(UK_LOCAL_LINE)) + + +def _uk_local_line_manifest() -> dict: + return _uk_release_manifest( + release_id=UK_LOCAL_RELEASE_ID, + revision=UK_LOCAL_CUT_TAG, + filename="microcosm_uk_2024_25_local_k15.h5", + artifact_key="microcosm_uk_2024_25_local_k15", + dataset_role=NON_DEFAULT_LOCAL_AREA_DATASET_ROLE, + default_datasets={}, + ) + + +def _line_pointer_hub( + tmp_path: Path, + *, + line: str, + release_id: str, + revision: str, + manifest: dict, +) -> FakeHubDownload: + pointer = line_pointer_payload( + release_id, + line=line, + revision=revision, + updated_at="2026-09-20T12:00:00+00:00", + ) + return _hub_with_pointer( + tmp_path, + repo_id=UK_REPO_ID, + pointer_path=line_pointer_path(line), + pointer=pointer, + manifest=manifest, + ) + + +def test_resolve_uk_default_is_the_promoted_national_line(): + """microcosm#823: once the national line's first certified cut was + promoted, the line became the default UK load; the June 2023 line stays + addressable at its year and its own pointer (Max's #823 ruling).""" + assert latest_year("uk") == 2025 + assert resolve("uk").key == ("uk", 2025, DEFAULT_VARIANT) + assert resolve("uk").pointer_path == "latest-national.json" + assert resolve("uk", 2023).pointer_path == "latest.json" + with pytest.raises(ValueError, match="variant 'national'"): + resolve("uk", 2025, variant="national") + + +def test_resolve_uk_national_variant_follows_the_line_pointer( + tmp_path: Path, +) -> None: + spec = resolve("uk", 2025) + hub = _line_pointer_hub( + tmp_path, + line="national", + release_id=UK_NATIONAL_RELEASE_ID, + revision=UK_NATIONAL_CUT_TAG, + manifest=_uk_national_line_manifest(), + ) + + certified = loader._resolve_certified_release(spec, hub_download=hub) + + manifest_path = f"releases/{UK_NATIONAL_RELEASE_ID}/release_manifest.json" + assert spec.key == ("uk", 2025, DEFAULT_VARIANT) + assert spec.pointer_path == "latest-national.json" + assert certified.release_id == UK_NATIONAL_RELEASE_ID + assert certified.build is None + assert certified.artifact_path == "microcosm_uk_2024_25.h5" + assert certified.artifact_revision == UK_NATIONAL_CUT_TAG + assert hub.calls == [ + (UK_REPO_ID, "releases.json", None), + (UK_REPO_ID, "latest-national.json", None), + (UK_REPO_ID, manifest_path, UK_NATIONAL_CUT_TAG), + ] + + +def test_download_follows_the_line_pointer_without_releases_json( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """load("uk") and download("uk") do not fail for want of releases.json.""" + hub = _line_pointer_hub( + tmp_path, + line="national", + release_id=UK_NATIONAL_RELEASE_ID, + revision=UK_NATIONAL_CUT_TAG, + manifest=_uk_national_line_manifest(), + ) + hub._add( + tmp_path, + UK_REPO_ID, + "microcosm_uk_2024_25.h5", + UK_NATIONAL_CUT_TAG, + UK_TAGGED_ARTIFACT, + ) + monkeypatch.setattr(huggingface_hub, "hf_hub_download", hub) + + path = download("uk") + + assert path.read_bytes() == UK_TAGGED_ARTIFACT + assert hub.calls[-1] == ( + UK_REPO_ID, + "microcosm_uk_2024_25.h5", + UK_NATIONAL_CUT_TAG, + ) + + +def test_a_build_pin_needs_the_repository_to_have_releases_json( + tmp_path: Path, +) -> None: + hub = _line_pointer_hub( + tmp_path, + line="national", + release_id=UK_NATIONAL_RELEASE_ID, + revision=UK_NATIONAL_CUT_TAG, + manifest=_uk_national_line_manifest(), + ) + + with pytest.raises(ValueError, match="has no releases.json"): + loader._resolve_certified_release( + resolve("uk", 2025), hub_download=hub, build=UK_NATIONAL_BUILD + ) + assert hub.calls == [(UK_REPO_ID, "releases.json", None)] + + +def test_only_a_missing_releases_json_follows_the_pointer_file(tmp_path: Path) -> None: + """An error other than the file's absence, such as an unreachable Hub, + propagates rather than reading the pointer files.""" + hub = _line_pointer_hub( + tmp_path, + line="national", + release_id=UK_NATIONAL_RELEASE_ID, + revision=UK_NATIONAL_CUT_TAG, + manifest=_uk_national_line_manifest(), + ) + + def unreachable(**request) -> str: + if request["filename"] == "releases.json": + raise ConnectionError("the Hub did not answer") + return hub(**request) + + with pytest.raises(ConnectionError, match="did not answer"): + loader._resolve_certified_release(resolve("uk", 2025), hub_download=unreachable) + assert hub.calls == [] + + +def test_line_pointer_refuses_any_artifact_revision_mismatch(tmp_path: Path) -> None: + manifest = _uk_national_line_manifest() + manifest["artifacts"]["calibration_report"] = { + "kind": "diagnostics", + "path": "calibration_diagnostics.json", + "repo_id": UK_REPO_ID, + "revision": UK_NATIONAL_RELEASE_ID, + "sha256": "0" * 64, + } + hub = _line_pointer_hub( + tmp_path, + line="national", + release_id=UK_NATIONAL_RELEASE_ID, + revision=UK_NATIONAL_CUT_TAG, + manifest=manifest, + ) + + with pytest.raises( + ValueError, + match=r"artifacts not pinned to expected revision.*calibration_report", + ): + loader._resolve_certified_release(resolve("uk", 2025), hub_download=hub) + + +def test_line_pointer_refuses_a_manifest_with_another_lines_role(tmp_path: Path): + """A line pointer carries one role: the national pointer cannot select a + local-area manifest, nor a local-area pointer a national one.""" + spec = resolve("uk", 2025) + manifest = _uk_national_line_manifest() + manifest["dataset_role"] = "non_default_local_area" + manifest["default_datasets"] = {} + hub = _line_pointer_hub( + tmp_path, + line="national", + release_id=UK_NATIONAL_RELEASE_ID, + revision=UK_NATIONAL_CUT_TAG, + manifest=manifest, + ) + with pytest.raises(ValueError, match="publishes only 'national_default'"): + loader._resolve_certified_release(spec, hub_download=hub) + + +def test_local_area_line_selects_its_only_microdata_artifact(tmp_path: Path) -> None: + manifest = _uk_local_line_manifest() + manifest["artifacts"]["calibration_report"] = { + "kind": "diagnostics", + "path": "calibration_diagnostics.json", + "repo_id": UK_REPO_ID, + "revision": UK_LOCAL_CUT_TAG, + "sha256": "0" * 64, + } + hub = _line_pointer_hub( + tmp_path, + line=UK_LOCAL_LINE, + release_id=UK_LOCAL_RELEASE_ID, + revision=UK_LOCAL_CUT_TAG, + manifest=manifest, + ) + + certified = loader._resolve_certified_release( + _uk_local_line_spec(), + hub_download=hub, + ) + + manifest_path = f"releases/{UK_LOCAL_RELEASE_ID}/release_manifest.json" + assert certified.release_id == UK_LOCAL_RELEASE_ID + assert certified.artifact_path == "microcosm_uk_2024_25_local_k15.h5" + assert certified.artifact_revision == UK_LOCAL_CUT_TAG + assert hub.calls == [ + (UK_REPO_ID, "releases.json", None), + (UK_REPO_ID, "latest-local-k15.json", None), + (UK_REPO_ID, manifest_path, UK_LOCAL_CUT_TAG), + ] + + +def test_local_area_line_refuses_nonempty_default_datasets(tmp_path: Path) -> None: + manifest = _uk_local_line_manifest() + manifest["default_datasets"] = {"national": "microcosm_uk_2024_25_local_k15"} + hub = _line_pointer_hub( + tmp_path, + line=UK_LOCAL_LINE, + release_id=UK_LOCAL_RELEASE_ID, + revision=UK_LOCAL_CUT_TAG, + manifest=manifest, + ) + + with pytest.raises(ValueError, match=r"default_datasets is not empty"): + loader._resolve_certified_release(_uk_local_line_spec(), hub_download=hub) + + +@pytest.mark.parametrize("microdata_count", [0, 2]) +def test_local_area_line_requires_exactly_one_microdata_artifact( + tmp_path: Path, + microdata_count: int, +) -> None: + manifest = _uk_local_line_manifest() + artifact = manifest["artifacts"]["microcosm_uk_2024_25_local_k15"] + if microdata_count == 0: + artifact["kind"] = "diagnostics" + else: + manifest["artifacts"]["second_microdata"] = { + "kind": "microdata", + "path": "second.h5", + "repo_id": UK_REPO_ID, + "revision": UK_LOCAL_CUT_TAG, + "sha256": "1" * 64, + } + hub = _line_pointer_hub( + tmp_path, + line=UK_LOCAL_LINE, + release_id=UK_LOCAL_RELEASE_ID, + revision=UK_LOCAL_CUT_TAG, + manifest=manifest, + ) + + with pytest.raises( + ValueError, + match=rf"{microdata_count} microdata artifacts; expected exactly one", + ): + loader._resolve_certified_release(_uk_local_line_spec(), hub_download=hub) + + def test_download_uses_pointer_manifest_and_release_revision( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: @@ -1009,9 +1331,10 @@ def test_live_latest_pointer_resolves_to_a_coherent_certified_release( which are updated atomically with each certification PR. """ spec = resolve(country, year, variant=variant) - # The UK 2025 default is a release whose builds publish into their own - # folders, so releases.json, not a pointer, says which build is current. - build_folder = spec.release is not None + # The UK 2025 default follows its line's pointer since microcosm#823, until + # its repository switches to releases.json; the pointer, not the variant, + # says how the release is named. + line = loader._line_from_pointer_path(spec.pointer_path) try: certified = loader._resolve_certified_release(spec) except Exception as exc: @@ -1023,21 +1346,22 @@ def test_live_latest_pointer_resolves_to_a_coherent_certified_release( pytest.skip( f"repo requires credentials this environment lacks (private): {exc}" ) - if build_folder and _is_missing_pointer_error(exc, "releases.json"): - # The one-time migration writes the repository's releases.json; - # until then the release has no record to read. Anything else - # once it exists (a manifest 404, a bad digest) fails. - pytest.skip(f"releases.json not yet written in {spec.hf_repo}: {exc}") + if line is not None and _is_missing_pointer_error(exc, spec.pointer_path): + # A line pointer exists only once its first cut is promoted; + # until then the line is registered but not yet live. Anything + # else on a promoted line (a manifest 404, a bad pin) fails. + pytest.skip(f"line pointer {spec.pointer_path} not yet promoted: {exc}") raise assert certified.artifact_repo_id == spec.hf_repo - if build_folder: + if certified.build is not None: + # The repository records its builds in releases.json. assert certified.release_id == spec.release assert certified.artifact_path == ( f"releases/{spec.release}/{certified.build}/{spec.filename}" ) assert certified.artifact_revision is None - else: + elif line is None: assert certified.artifact_path == spec.filename assert certified.release_id.startswith( # Live certified releases still carry the pre-rename id prefix; new @@ -1046,6 +1370,11 @@ def test_live_latest_pointer_resolves_to_a_coherent_certified_release( (f"microcosm-{country}-{spec.year}-", f"populace-{country}-{spec.year}-") ) assert certified.artifact_revision == certified.release_id + else: + # A line pointer names the immutable cut tag of its constant id. + assert certified.artifact_path == spec.filename + assert certified.release_id.startswith(f"microcosm-{country}-") + assert certified.artifact_revision.startswith(f"{certified.release_id}-") assert re.fullmatch(r"[0-9a-f]{64}", certified.artifact_sha256) assert certified.model.name == spec.engine_package diff --git a/packages/microcosm-data/tests/engine_free/shared/test_registry.py b/packages/microcosm-data/tests/engine_free/shared/test_registry.py index 2831e6f3f7..0fa6d7458a 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_registry.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_registry.py @@ -151,6 +151,19 @@ def test_uk_2025_dense_is_registered_off_the_default_variant() -> None: assert ("uk", 2025, DEFAULT_VARIANT) in REGISTRY +def test_uk_2025_national_line_is_the_default_variant_after_promotion(): + """microcosm#823: the line's first certified cut was promoted on + 2026-10-26, so the line moved to the default variant (Max's #823 + ruling) and its own variant key retired; the June 2023 line stays + addressable at its year. Until its repository switches to + releases.json, the loader follows latest-national.json.""" + spec = REGISTRY[("uk", 2025, DEFAULT_VARIANT)] + assert spec.pointer_path == "latest-national.json" + assert spec.filename == "microcosm_uk_2024_25.h5" + assert ("uk", 2025, "national") not in REGISTRY + assert REGISTRY[("uk", 2023, DEFAULT_VARIANT)].filename == "populace_uk_2023.h5" + + def test_uk_2025_national_release_is_the_default_variant(): """The national release is the default UK 2025 load: its current build in releases.json, not a pointer file; the June 2023 release stays diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release.py b/packages/microcosm-data/tests/engine_free/shared/test_release.py index 7e497e85cf..b81562c083 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release.py @@ -283,6 +283,67 @@ def test_local_k_role_moves_only_its_own_line_pointer(tmp_path: Path) -> None: assert all(path != LATEST_EVIDENCE_POINTER_PATH for path, _ in uk_hub.uploads) +#: A releases.json that the switch to build folders writes; its contents do +#: not matter to the tagged publisher, which refuses once it exists. +_RELEASES_RECORD = json.dumps( + {"schema_version": 1, "default": None, "releases": {}} +).encode() + + +@pytest.mark.parametrize( + "options", + [{}, {"update_latest": False}, {"update_latest": False, "tag_only": True}], + ids=["latest", "no-latest", "tag-only"], +) +def test_the_tagged_publisher_refuses_a_repository_with_releases_json( + hub: FakeHub, release_dir: Path, artifact_root: Path, monkeypatch, options: dict +) -> None: + """Once a repository records its builds in releases.json, the emitter + publishes there; a tag or pointer file written beside it would disagree + with the record, so the publisher refuses before it writes anything.""" + monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) + hub.seed_main_file("releases.json", _RELEASES_RECORD) + + with pytest.raises(ValueError, match="releases.json") as refusal: + publish_release( + release_dir, + "policyengine/populace-us", + api=hub, + artifact_root=artifact_root, + **options, + ) + + assert "microcosm-publish-release-build" in str(refusal.value) + assert hub.tags == [] + assert hub.uploads == [] + assert [event for event, _ in hub.events] == [] + + +def test_the_tagged_publisher_refuses_a_uk_promotion_once_releases_json_exists( + release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch +) -> None: + national = _as_uk_national_line_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) + monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) + hub = _uk_hub(tmp_path) + hub.seed_main_file("releases.json", _RELEASES_RECORD) + + with pytest.raises(ValueError, match="releases.json"): + publish_release( + national, + "policyengine/populace-uk-private", + api=hub, + artifact_root=artifact_root, + tag_name=UK_NATIONAL_CUT_TAG, + line="national", + ) + + assert hub.tags == [] + assert line_pointer_path("national") not in hub._commits[hub._refs["main"]] + + def test_prepare_build_folder_release_lists_each_file_with_its_role( release_dir: Path, artifact_root: Path, monkeypatch ) -> None: From d7bce422fea5b142d16658169e1cfe77941e44d5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:54:40 +0400 Subject: [PATCH 21/26] Refuse a repository in the other layout, and fall back to the pointer files No UK release can now reach a state where no build can be made current: - the tagged publisher reads releases.json at the main revision it commits on, and refuses a repository that has one before it writes anything; - microcosm-publish-release-build lists the repository's files with huggingface_hub and refuses, before the build is checked or any emitter starts, while any latest*.json file is there (the interface's is_pointer_file rule) or when the files cannot be listed. The loader reads releases.json for a registry entry that names a release only where the repository has one; otherwise it follows the entry's pointer file as before, latest-national.json for the UK national release, with main's line-pointer reading and role check. Only the file's absence falls back. build= needs releases.json, and unverified_root is refused only once it exists. A POINTER_FILES_PRESENT refusal now points to tools/publish_release.sh, and review round 1's separate promotion advice is gone. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/release_publication.py | 99 ++++++--- .../src/microcosm/data/loader.py | 207 ++++++++++++------ .../src/microcosm/data/registry.py | 47 ++-- .../src/microcosm/data/release.py | 32 +++ 4 files changed, 269 insertions(+), 116 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/release_publication.py b/packages/microcosm-build/src/microcosm/build/release_publication.py index 8c303b8d5c..143f031785 100644 --- a/packages/microcosm-build/src/microcosm/build/release_publication.py +++ b/packages/microcosm-build/src/microcosm/build/release_publication.py @@ -1,7 +1,7 @@ """Publish a release build into its own folder through the emitter. -A release whose builds publish into their own folders (the UK national, -dense and local-area releases, which +A release whose builds can publish into their own folders (the UK +national, dense and local-area releases, which ``microcosm.data.contract.publishes_to_build_folder`` names) is handed to the separately installed emitter with the interface's ``publish_release`` call. Microcosm decides what the build contains and checks it with the release @@ -11,6 +11,12 @@ rules in ``microcosm_emitter_interface.releases``. Nothing here commits, tags or writes a pointer file. +Until a repository switches to ``releases.json``, its releases still publish +and promote through their ``latest*.json`` pointer files with +``tools/publish_release.sh``. So the command lists the repository's files +first and refuses, before any emitter starts, while any pointer file is +there; the tagged publisher refuses a repository that has ``releases.json``. + A build is current only when the emitter's receipt says so: ``status`` is ``published`` and ``current`` is the build. A publication with ``make_current`` can land without making its build current, when a change to @@ -23,9 +29,10 @@ ``TRANSFORMERS_OFFLINE`` too, so with either set the command refuses before it starts one, and it hands nothing over until the emitter's write-access check passes, as the staged-bundle hand-over does: otherwise the change -would wait, pending, until the emitter dropped it an hour later. -Publication sends no Slack alert. The dashboard is to announce release -changes from ``releases.json``; until it does, these publications raise none. +would wait, pending, until the emitter dropped it an hour later. The +command's own listing of the repository's files uses ``huggingface_hub`` in +this process, with the same credential. Publication sends no Slack alert; +the dashboard announces changes to ``releases.json``. """ from __future__ import annotations @@ -43,6 +50,7 @@ ReleaseReceipt, unavailable_release_receipt, ) +from microcosm_emitter_interface.releases import is_pointer_file from microcosm.build.staging_dataset import hub_offline, write_access_problem from microcosm.build.telemetry_emitter import start_bundle_emitter @@ -77,19 +85,13 @@ #: How long the command waits for a promotion, which changes only #: ``releases.json``. PROMOTION_WAIT_SECONDS = 300.0 -_POINTER_FILES = ( - "The repository still has latest*.json pointer files, and the emitter " - "changes no release's current build while any exists, so that they and " - "releases.json cannot disagree." -) #: What the emitter's refusal codes mean for the operator, where its own -#: message does not say what to do next: for a publication, and for a -#: promotion of a build already published. +#: message does not say what to do next. _REFUSAL_ADVICE = { "POINTER_FILES_PRESENT": ( - f"{_POINTER_FILES} Nothing was published: publish the build without " - "--make-current, and make it current with --promote once the pointer " - "files are deleted." + "The repository has latest*.json pointer files again, so its releases " + "publish and promote through them with tools/publish_release.sh until " + "it switches to releases.json; nothing was changed." ), "BUILD_FOLDER_EXISTS": ( "Another build with this name was published already, with a different " @@ -105,13 +107,6 @@ "the emitter dropped it; run the command again." ), } -_PROMOTION_REFUSAL_ADVICE = { - **_REFUSAL_ADVICE, - "POINTER_FILES_PRESENT": ( - f"{_POINTER_FILES} The build stays published but is not current. Run " - "this --promote command again once the pointer files are deleted." - ), -} #: Why the command refuses with ``HF_HUB_OFFLINE`` or ``TRANSFORMERS_OFFLINE`` #: set: the emitter it starts inherits the variable. _OFFLINE_REFUSAL = ( @@ -158,9 +153,8 @@ class ReleasePublication: ``wanted_current`` says whether the change asked for the build to become current: a promotion, or a publication with ``make_current``. - ``promotion`` says whether it was a promotion. ``problem`` says why - nothing was handed over, when the emitter could not take the change or - its write-access check refused it. + ``problem`` says why nothing was handed over, when the emitter could not + take the change or its write-access check refused it. """ repository: str @@ -169,7 +163,6 @@ class ReleasePublication: wanted_current: bool receipt: ReleaseReceipt problem: str | None = None - promotion: bool = False @property def published(self) -> bool: @@ -200,9 +193,7 @@ def explanation(self) -> str: "again later to see whether it landed." ) if status == "refused": - advice = ( - _PROMOTION_REFUSAL_ADVICE if self.promotion else _REFUSAL_ADVICE - ).get(str(code)) + advice = _REFUSAL_ADVICE.get(str(code)) reason = self.receipt.get("message") or code return f"The emitter refused it ({code}): {reason}" + ( f" {advice}" if advice else "" @@ -269,7 +260,6 @@ def _hand_over( wanted_current=wanted_current, receipt=receipt, problem=problem, - promotion=isinstance(change, PromoteBuild), ) @@ -279,6 +269,41 @@ def _refuse_offline() -> None: raise ValueError(_OFFLINE_REFUSAL) +def _repository_files(repository: str) -> list[str]: + """Every file path on the dataset repository's ``main`` (test seam).""" + from huggingface_hub import HfApi + + return list(HfApi().list_repo_files(repository, repo_type="dataset")) + + +def _refuse_pointer_files(repository: str) -> None: + """Refuse a repository whose releases still publish through pointer files. + + While any ``latest*.json`` file is in the repository (the interface's + ``is_pointer_file`` rule, which the emitter applies too), its releases + publish and are made current with tools/publish_release.sh, and only its + switch to ``releases.json`` moves them here. A repository whose files + cannot be listed is refused too. + """ + try: + paths = _repository_files(repository) + except (OSError, ValueError) as error: + raise ValueError( + f"could not list the files of {repository} to check for " + f"latest*.json pointer files ({type(error).__name__}: {error}); " + "check the Hugging Face credential (HF_TOKEN or `hf auth login`) " + "and run the command again" + ) from error + pointer_files = sorted(path for path in paths if is_pointer_file(path)) + if pointer_files: + raise ValueError( + f"{repository} still has the pointer file(s) " + f"{', '.join(pointer_files)}, so its releases publish and are made " + "current through them with tools/publish_release.sh until it " + "switches to releases.json" + ) + + def publication_request( prepared: BuildFolderRelease, *, make_current: bool ) -> PublishRelease: @@ -319,11 +344,15 @@ def publish_release_build( queue is the one builds on this machine share, so a change still pending when it closes is retried by the next emitter started here. It refuses (``ValueError``) before anything else when ``HF_HUB_OFFLINE`` or - ``TRANSFORMERS_OFFLINE`` is set, and hands nothing over unless the - emitter's write-access check passes. + ``TRANSFORMERS_OFFLINE`` is set, then, before the build is checked or any + emitter starts, when the repository still has ``latest*.json`` pointer + files; it hands nothing over unless the emitter's write-access check + passes. """ if client is None: _refuse_offline() + named_repository, _, _ = build_folder_identity(release_dir) + _refuse_pointer_files(named_repository) prepared = prepare_build_folder_release( release_dir, artifact_root=artifact_root, repository=repository ) @@ -354,6 +383,7 @@ def promote_release_build( f"release {release!r} names {named_repository} in its artifacts, not " f"{repository}." ) + _refuse_pointer_files(named_repository) return _hand_over( PromoteBuild(repository=named_repository, release=release, build=build), client=client, @@ -429,8 +459,9 @@ def main(argv: list[str] | None = None) -> int: A build that fails its checks (the release contract, a file whose bytes differ, another repository) is refused with the reason and status 1, before any emitter starts, and so is any change while ``HF_HUB_OFFLINE`` - or ``TRANSFORMERS_OFFLINE`` is set. A change the emitter's write-access - check refuses is handed nothing and exits 1 with the reason. + or ``TRANSFORMERS_OFFLINE`` is set or while the repository still has + ``latest*.json`` pointer files. A change the emitter's write-access check + refuses is handed nothing and exits 1 with the reason. """ parser = _parser() args = parser.parse_args(argv) diff --git a/packages/microcosm-data/src/microcosm/data/loader.py b/packages/microcosm-data/src/microcosm/data/loader.py index 8639b73d59..c79f1a808a 100644 --- a/packages/microcosm-data/src/microcosm/data/loader.py +++ b/packages/microcosm-data/src/microcosm/data/loader.py @@ -1,22 +1,23 @@ """Resolve, verify, download, and load a certified microcosm release. -A release whose builds publish into their own folders (the registry's UK -2025 national and dense entries) is read through the repository's -``releases.json``: the record names the release's current build (or -``build=`` pins a listed one), the loader reads -``releases///release_manifest.json``, downloads the dataset -that manifest names from the same folder, verifies its SHA-256, and enforces -the certified model/Core versions before constructing the engine dataset. -Build folders never change after publishing, so every file is read at -``main``. - -A release that keeps the tagged layout (every US entry, and UK 2023) follows -the repository's release certificate: resolve the registry-selected pointer, -read that release's manifest at the pointer's immutable revision, download -the manifest-selected dataset at the same revision and check it the same way. -Its mutable root artifacts are available only through the explicitly unsafe -``load(..., unverified_root=True)`` escape hatch; a build-folder release has -no root file. +A registry entry that names a release whose builds can publish into their +own folders (the UK 2025 national and dense entries) is read through the +repository's ``releases.json`` once the repository has one: the record names +the release's current build (or ``build=`` pins a listed one), the loader +reads ``releases///release_manifest.json``, downloads the +dataset that manifest names from the same folder, verifies its SHA-256, and +enforces the certified model/Core versions before constructing the engine +dataset. Build folders never change after publishing, so every file is read +at ``main``. + +A repository without ``releases.json`` (every repository until its switch to +build folders) follows the release certificate as before: resolve the +registry-selected pointer (``latest.json``, or a UK release's +``latest-.json``), read that release's manifest at the pointer's +immutable revision, download the manifest-selected dataset at the same +revision and check it the same way. Its mutable root artifacts are available +only through the explicitly unsafe ``load(..., unverified_root=True)`` escape +hatch; a repository with ``releases.json`` has no root file. """ from __future__ import annotations @@ -42,12 +43,16 @@ NON_DEFAULT_LOCAL_AREA_DATASET_ROLE, RELEASE_MANIFEST_SCHEMA_VERSION, RELEASE_ROLES, + dataset_role_for_line, ) from microcosm.data.registry import DEFAULT_VARIANT, REGISTRY, DatasetSpec from microcosm.data.release import ( LATEST_POINTER_PATH, + LINE_POINTER_PATH_TEMPLATE, LatestPointer, + latest_line_release, latest_release, + line_pointer_path, ) from microcosm.data.releases_record import ( RELEASES_RECORD_PATH, @@ -65,7 +70,27 @@ ] _SHA256_PATTERN = re.compile(r"[0-9a-fA-F]{64}") +_LINE_POINTER_PATH_PATTERN = re.compile( + re.escape(LINE_POINTER_PATH_TEMPLATE).replace(re.escape("{line}"), r"(?P.+)") +) _HubDownload = Callable[..., str] +#: The exception names that mean a file is absent from the repository (the +#: Hub's ``EntryNotFoundError``, or a test fake's ``FileNotFoundError``), +#: and nothing else. +_ABSENT_FILE_ERRORS = frozenset({"EntryNotFoundError", "FileNotFoundError"}) + + +def _line_from_pointer_path(pointer_path: str) -> str | None: + """Invert the shared line-pointer template and validate its line.""" + match = _LINE_POINTER_PATH_PATTERN.fullmatch(pointer_path) + if match is None: + return None + line = match.group("line") + try: + rendered_path = line_pointer_path(line) + except ValueError: + return None + return line if rendered_path == pointer_path else None @dataclass(frozen=True) @@ -320,6 +345,19 @@ def _certified_release_from_manifest( raise ValueError( f"Release {release_id!r} has unknown dataset_role {dataset_role!r}." ) + pointer_line = ( + None if build_folder_release else _line_from_pointer_path(spec.pointer_path) + ) + if pointer_line is not None: + # A line pointer carries one role: the manifest it names must + # declare it, whatever its release id says. + expected_role = dataset_role_for_line(pointer_line) + if dataset_role != expected_role: + raise ValueError( + f"Release {release_id!r} declares dataset_role {dataset_role!r}; " + f"{spec.pointer_path!r} follows line {pointer_line!r}, which " + f"publishes only {expected_role!r} releases." + ) if build_folder_release and release_role != RELEASE_ROLES[dataset_role]: # releases.json gives a release one role, so a manifest whose role # differs is not this release's, whatever its names say. @@ -339,11 +377,12 @@ def _certified_release_from_manifest( ) artifact_label = "default" else: - if not build_folder_release: + if not build_folder_release and pointer_line is None: raise ValueError( f"Release {release_id!r} declares dataset_role " f"{NON_DEFAULT_LOCAL_AREA_DATASET_ROLE!r}; a local-area release " - "is loaded from its build folder through releases.json, not " + "is loaded from its build folder through releases.json, or " + f"through a {LINE_POINTER_PATH_TEMPLATE!r} line pointer, not " f"{spec.pointer_path!r}." ) if default_datasets != {}: @@ -490,39 +529,69 @@ def _sha256(path: Path) -> str: def _pointer_for( spec: DatasetSpec, *, hub_download: _HubDownload | None = None ) -> LatestPointer: - """Read the release pointer configured for a tagged release's ``spec``.""" - if spec.pointer_path != LATEST_POINTER_PATH: - raise ValueError( - f"Unsupported release pointer path {spec.pointer_path!r} for {spec.key}; " - f"a tagged release follows {LATEST_POINTER_PATH!r}, and a release " - "whose builds publish into their own folders is named by the " - "registry entry's release." - ) + """Read the release pointer configured for ``spec``.""" if hub_download is None: hub_download = _hub_download() - return latest_release( - spec.hf_repo, api=SimpleNamespace(hf_hub_download=hub_download) + api = SimpleNamespace(hf_hub_download=hub_download) + if spec.pointer_path == LATEST_POINTER_PATH: + return latest_release(spec.hf_repo, api=api) + line = _line_from_pointer_path(spec.pointer_path) + if line is not None: + return latest_line_release( + spec.hf_repo, + line=line, + api=api, + ) + raise ValueError( + f"Unsupported release pointer path {spec.pointer_path!r} for {spec.key}; " + f"expected {LATEST_POINTER_PATH!r} or the " + f"{LINE_POINTER_PATH_TEMPLATE!r} line-pointer form." ) +def _is_absent_file_error(exc: BaseException) -> bool: + """Whether a download failed only because the file is not there.""" + return bool({cls.__name__ for cls in type(exc).__mro__} & _ABSENT_FILE_ERRORS) + + +def _releases_record_bytes( + spec: DatasetSpec, *, hub_download: _HubDownload +) -> bytes | None: + """The repository's ``releases.json``, or ``None`` when it has none. + + Until its switch to build folders a repository has no ``releases.json``, + and its releases are found through their pointer files. Only the file's + absence means that (offline, a file that was never cached counts as + absent, as the pointer files then are); any other failure propagates. + """ + try: + record_path = hub_download( + repo_id=spec.hf_repo, filename=RELEASES_RECORD_PATH, repo_type="dataset" + ) + except Exception as exc: + if _is_absent_file_error(exc): + return None + raise + return Path(record_path).read_bytes() + + def _resolve_build_folder_release( - spec: DatasetSpec, *, build: str | None, hub_download: _HubDownload + spec: DatasetSpec, + *, + record_bytes: bytes, + build: str | None, + hub_download: _HubDownload, ) -> _CertifiedRelease: """Select a build of ``spec.release`` from ``releases.json`` and check it. The current build, unless ``build`` pins a listed one; a pinned build that has been withdrawn loads with a warning, since a pin is a deliberate - choice. A missing ``releases.json`` raises the Hub's own error. + choice. """ release = spec.release assert release is not None - record_path = Path( - hub_download( - repo_id=spec.hf_repo, filename=RELEASES_RECORD_PATH, repo_type="dataset" - ) - ) try: - record = parse_releases_record(record_path.read_bytes()) + record = parse_releases_record(record_bytes) except ValueError as exc: raise ValueError( f"{RELEASES_RECORD_PATH} in {spec.hf_repo} is not a valid release " @@ -579,9 +648,10 @@ def _resolve_certified_release( ) -> _CertifiedRelease: """Resolve and validate the release's selected build and its manifest. - A build-folder release reads ``releases.json``; a tagged release follows - its pointer to a pinned manifest, and ``build`` cannot pin one of its - builds. + An entry that names a release reads the repository's ``releases.json`` + when it has one. Otherwise, and for every other entry, the loader follows + the entry's pointer to a pinned manifest, and ``build`` cannot pin a + build. """ if spec.release is None and build is not None: raise ValueError( @@ -591,9 +661,20 @@ def _resolve_certified_release( if hub_download is None: hub_download = _hub_download() if spec.release is not None: - return _resolve_build_folder_release( - spec, build=build, hub_download=hub_download - ) + record_bytes = _releases_record_bytes(spec, hub_download=hub_download) + if record_bytes is not None: + return _resolve_build_folder_release( + spec, + record_bytes=record_bytes, + build=build, + hub_download=hub_download, + ) + if build is not None: + raise ValueError( + f"{spec.hf_repo} has no releases.json yet, so build= cannot pin a " + f"build of {spec.release!r}; its current build is the one " + f"{spec.pointer_path} names." + ) pointer = _pointer_for(spec, hub_download=hub_download) manifest_path = Path( hub_download( @@ -640,11 +721,6 @@ def _verified_download( def _unverified_root_download(spec: DatasetSpec) -> Path: - if spec.release is not None: - raise ValueError( - f"Release {spec.release!r} publishes each build into its own folder " - "and has no root file to load unverified; load its current build." - ) return Path( _hub_download()( repo_id=spec.hf_repo, @@ -663,9 +739,10 @@ def download( ) -> Path: """Download and SHA-verify a certified release artifact. - A build-folder release's current build (or the listed ``build`` it pins) - comes from ``releases.json``, and its manifest and dataset from that - build's folder. A tagged release's mutable pointer selects a release; + Where the repository has ``releases.json``, a release's current build + (or the listed ``build`` it pins) comes from it, and its manifest and + dataset from that build's folder. Otherwise the entry's mutable pointer + selects a release; both its manifest and dataset artifact are then fetched at the pointer's immutable revision. Uses the Hugging Face cache, so repeated calls do not re-download unchanged files. @@ -735,24 +812,30 @@ def load( year: Population year; ``None`` loads the latest published year. variant: Dataset variant; ``"compact"`` is the default fast national microsimulation artifact. - unverified_root: Load a tagged release's mutable root convenience - artifact while bypassing release metadata, SHA-256, and engine - certification. This unsafe compatibility escape hatch emits a - loud warning; a build-folder release has no root file. - build: Load this listed build of a build-folder release instead of - its current one. + unverified_root: Load the mutable root convenience artifact while + bypassing release metadata, SHA-256, and engine certification. + This unsafe compatibility escape hatch emits a loud warning; a + repository that records its builds in ``releases.json`` has no + root file. + build: Load this listed build of a release recorded in the + repository's ``releases.json`` instead of its current one. Raises: ImportError: If the country engine is not installed. ValueError: If release verification or engine compatibility fails. """ spec = resolve(country, year, variant=variant) - if unverified_root and (spec.release is not None or build is not None): + if unverified_root and build is not None: + raise ValueError("unverified_root cannot be combined with build=.") + if ( + unverified_root + and spec.release is not None + and _releases_record_bytes(spec, hub_download=_hub_download()) is not None + ): raise ValueError( - f"{spec.key} publishes each build into its own folder and has no " - "root file to load unverified; load a build without unverified_root." - if spec.release is not None - else "unverified_root cannot be combined with build=." + f"{spec.hf_repo} records the builds of {spec.release!r} in " + "releases.json, and has no root file to load unverified; load a " + "build without unverified_root." ) dataset_class = _dataset_class(spec) if unverified_root: diff --git a/packages/microcosm-data/src/microcosm/data/registry.py b/packages/microcosm-data/src/microcosm/data/registry.py index 58a386df11..eb4e14caf2 100644 --- a/packages/microcosm-data/src/microcosm/data/registry.py +++ b/packages/microcosm-data/src/microcosm/data/registry.py @@ -47,12 +47,13 @@ class DatasetSpec: ``"policyengine-us"`` — named in the install extra and in the ImportError when the engine is absent. pointer_path: The repository-root release pointer followed by the - certified loader, for a release that keeps the tagged layout. - release: The release whose builds publish into their own folders, - ``releases///``. The loader then reads the - repository's ``releases.json`` for the release's current build - and loads ``filename`` from that build's folder; ``pointer_path`` - is not read. ``None`` for a release that keeps the tagged layout. + certified loader while the repository has no ``releases.json``. + release: The release whose builds can publish into their own folders, + ``releases///``. Where the repository has + ``releases.json``, the loader reads the release's current build + there and loads ``filename`` from that build's folder; until the + repository switches to it, the loader follows ``pointer_path``. + ``None`` for a release that keeps the tagged layout. """ country: str @@ -119,12 +120,15 @@ def register(spec: DatasetSpec) -> DatasetSpec: register( DatasetSpec( - # microcosm#823: the UK 2024-25 national release is the default UK - # load, since its first certified build was made current on - # 2026-10-26. Its builds publish into their own folders, so the loader - # reads its current build from releases.json. resolve("uk") picks the - # latest default-variant year, so it loads this release; the June 2023 - # artifact stays at ("uk", 2023). + # microcosm#823: the UK 2024-25 national line, followed through its + # own pointer, is the default UK load. It stayed off the default + # variant until its first certified cut was promoted (review of #966; + # Max's #823 ruling), and latest-national.json has named + # microcosm-uk-2024-25-national-20261025T091414Z-a6299504 since + # 2026-10-26. resolve("uk") picks the latest default-variant year, so + # it loads this line; the June 2023 artifact stays at ("uk", 2023). + # Once the repository switches to releases.json, the loader reads the + # release's current build there instead. country="uk", year=2025, variant=DEFAULT_VARIANT, @@ -133,16 +137,18 @@ def register(spec: DatasetSpec) -> DatasetSpec: engine_module="policyengine_uk.data", engine_class="UKSingleYearDataset", engine_package="policyengine-uk", + pointer_path="latest-national.json", release="microcosm-uk-2024-25-national", ) ) register( DatasetSpec( - # microcosm#762 A18: the dense joint national + local UK release. It - # carries every constituency and local authority at K=15 clones per - # spine household. Each new dense build becomes current when it is - # published. + # microcosm#762 A18: the dense joint national + local UK build is + # tag-only; no pointer. It carries every constituency and local + # authority at K=15 clones per spine household. Once the repository + # switches to releases.json, each new dense build becomes current when + # it is published, and the loader reads it there. country="uk", year=2025, variant="dense", @@ -155,10 +161,11 @@ def register(spec: DatasetSpec) -> DatasetSpec: ) ) -# microcosm#898 reserves the local-area release as variant "local", named -# microcosm-uk-2024-25-local-k with artifact -# microcosm_uk_2024_25_local_k.h5. Add its registry entry only once a -# certified build exists. +# microcosm#898 reserves the local-area line as variant "local", with pointer +# latest-local-k.json and artifact microcosm_uk_2024_25_local_k.h5, and +# the release microcosm-uk-2024-25-local-k once its repository records +# builds in releases.json. Add its registry entry only once a certified +# artifact exists. register( DatasetSpec( diff --git a/packages/microcosm-data/src/microcosm/data/release.py b/packages/microcosm-data/src/microcosm/data/release.py index 43a2d79969..652b0e8481 100644 --- a/packages/microcosm-data/src/microcosm/data/release.py +++ b/packages/microcosm-data/src/microcosm/data/release.py @@ -70,6 +70,7 @@ validate_evidence_release_dir, validate_release_dir, ) +from microcosm.data.releases_record import RELEASES_RECORD_PATH from microcosm.data.slack import notify_release __all__ = [ @@ -1024,6 +1025,34 @@ def _repo_revision(api: object, *, repo_id: str) -> str | None: return str(value) if value else None +def _refuse_releases_record(api: object, *, repo_id: str, revision: str | None) -> None: + """Refuse a repository that records its builds in ``releases.json``. + + Such a repository publishes each build into its own folder through the + emitter, and ``releases.json`` is the only record of which build is + current; a tag or ``latest*.json`` pointer file written beside it would + disagree with the record. Only the file's absence lets the publication + go on; any other failure to read it propagates. + """ + try: + api.hf_hub_download( + repo_id=repo_id, + filename=RELEASES_RECORD_PATH, + repo_type="dataset", + revision=revision, + ) + except Exception as exc: + if _is_absent_entry_error(exc): + return + raise + raise ValueError( + f"{repo_id} records its builds in {RELEASES_RECORD_PATH}, so this " + "publisher, which tags each build and writes latest*.json pointer " + "files, refuses it; publish its builds with " + "`microcosm-publish-release-build`." + ) + + def _publish_atomic( api: object, *, @@ -1044,6 +1073,9 @@ def _publish_atomic( ) -> None: staging_branch = f"release-staging/{release_id}" main_revision = _repo_revision(api, repo_id=repo_id) + # The main commit below is made on main_revision, so a releases.json + # added after this check makes it fail rather than land beside it. + _refuse_releases_record(api, repo_id=repo_id, revision=main_revision) existing_revision = ( _tag_revision(api, repo_id=repo_id, tag=tag) if create_tag else None ) From 0592245b233fc5b908dffa09fb3ab6aa315e75fa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:55:36 +0400 Subject: [PATCH 22/26] Document publication into build folders as waiting for each repository's switch The README and microcosm-data's README describe the build-folder command beside today's UK flow: it refuses a repository that still has latest*.json pointer files, the tagged publisher refuses one that has releases.json, and UK releases keep publishing, promoting and sending Slack alerts through the pointer files until their repository's switch, which waits until the dashboard posts alerts from releases.json. The loader reads releases.json where a repository has one and the pointer files otherwise. The changelog fragment describes the narrowed change. Co-Authored-By: Claude Opus 5.5 --- README.md | 31 +++++++++++++++++++ ...4-h2c-release-builds-in-folders.changed.md | 2 +- packages/microcosm-data/README.md | 14 ++++++++- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cc0ac6a665..ba5979bfa3 100644 --- a/README.md +++ b/README.md @@ -443,6 +443,37 @@ reviewed cut with `--promote-line --tag-name `. Promotion moves only that line pointer; the UK repository-global `latest.json` remains frozen on the June 2023 release. Promotion reuses the immutable cut tag the inspect publication created (it checks the tagged manifest is byte-identical) and writes only the pointer commit, so the two-step sequence and a retry after a failed pointer commit both work. A line's registry entry is registered off the default variant until its first promotion; the default flips in a follow-up after the pointer exists. +**Build folders, after a repository's switch.** A UK national, dense or +local-area build can also be published into its own folder, +`releases///`, through the separately installed emitter, +whose release writer records it in the repository's `releases.json`, the +only record of each release's builds and which one is current: + +```bash +uv run microcosm-publish-release-build releases/ \ + --repo-id --artifact-root [--make-current] +uv run microcosm-publish-release-build releases/ --promote +``` + +A build counts as current only when the emitter's receipt is `published` and +names it as `current`. Each path refuses a repository in the other's layout, +so a UK release always has one way to change its current build: + +- `microcosm-publish-release-build` lists the repository's files and refuses, + before any emitter starts, while any `latest*.json` pointer file is there. + It also refuses with `HF_HUB_OFFLINE` or `TRANSFORMERS_OFFLINE` set, and + hands nothing over unless the emitter's write-access check passes. +- `microcosm-publish-release` (and `tools/publish_release.sh`) refuses a + repository that has `releases.json`. + +So UK releases keep publishing, promoting and sending their Slack alerts +through the pointer files, as above, until their repository's switch, one +commit that writes `releases.json` and deletes the pointer files. Release +alerts do not stop: the switch waits until the dashboard posts them from +changes to `releases.json`. `microcosm.data.load` reads a release's current +build from `releases.json` where the repository has one, and follows its +pointer file otherwise. + The publisher uploads only the contract files, the release manifest's artifacts and any `--extra-file`. The US fiscal-refresh tool therefore binds its terminal gate verdicts as manifest artifacts: `input_coverage.json`, diff --git a/changelog.d/1504-h2c-release-builds-in-folders.changed.md b/changelog.d/1504-h2c-release-builds-in-folders.changed.md index 9721c3fe20..ccf9095236 100644 --- a/changelog.d/1504-h2c-release-builds-in-folders.changed.md +++ b/changelog.d/1504-h2c-release-builds-in-folders.changed.md @@ -1 +1 @@ -Builds of the UK national, dense and local-area releases publish into their own folders through the emitter. These releases (`microcosm.data.contract.publishes_to_build_folder`) hand each build to the separately installed `microcosm-emitter` with the interface's `publish_release` call, and its release writer puts the build in `releases///` and records it in the repository's `releases.json` in one commit; Microcosm no longer commits, tags or writes `latest*.json` pointer files for them. The new `microcosm-publish-release-build` command (`microcosm.build.release_publication`, in `microcosm-build`) checks the build with the release contract, hands every file over with its role and SHA-256, refuses before it starts an emitter when `HF_HUB_OFFLINE` or `TRANSFORMERS_OFFLINE` is set, hands nothing over unless the emitter's write-access check passes, publishes with or without `--make-current`, makes a published build current with `--promote`, and succeeds only when the emitter's receipt is `published` and, when current was asked for, names the build as `current`. The build is the calibration attempt ID: both manifests name `release` and `build` as strings, the release manifest records `built_at`, `built_with_model_package` and `built_with_core_package` at its top level and a `role` on each artifact (`dataset`, `calibration_weights`, `calibration_diagnostics`, otherwise the artifact's key), and no artifact pins a `revision`. The fields `build_id`, `attempt_id` and `cut_tag` are gone from their manifests, and the assemblers' `--cut-tag` option with them. Each release's role in `releases.json` is `national` or `local_area`, from its `dataset_role`. Both UK assemblers print a publication command and a separate promotion command: while the repository still has its `latest*.json` pointer files the emitter refuses every change to a current build, so each new dense build is promoted once those files are deleted, and can be published with `--make-current` after that. The release contract checks this layout for those releases and refuses the tagged one. `microcosm.data.load` reads the current build of the UK 2025 national and dense releases from `releases.json` (or the listed build `build=` names, a withdrawn one with a warning), then its manifest and dataset from the build's folder; `unverified_root=True` is refused for such a release, and the loader no longer follows `latest-.json` pointers. `microcosm-publish-release` and `tools/publish_release.sh` keep publishing every US release, the June 2023 UK release and `populace-uk---k` releases with tags, `latest.json` and their Slack alerts, refuse the build-folder releases, and lose `--promote-line`. Publications into build folders send no Slack alert until the dashboard posts release alerts from `releases.json`. The stable releases proposed for US builds, `populace-us-2024-national` (`national`, the default) and `populace-us-2024-local` (`local_area`), are recorded in `microcosm.data.contract.PROPOSED_US_RELEASES` but not used until they are agreed with the US data builder. +Microcosm can publish a release build into its own folder through the emitter, while UK releases stay on the pointer files until their repository's switch. The new `microcosm-publish-release-build` command (`microcosm.build.release_publication`, in `microcosm-build`) checks a UK national, dense or local-area build in the build-folder layout with the release contract and hands every file to the separately installed `microcosm-emitter` with the interface's `publish_release` call, which writes `releases///` and the repository's `releases.json` in one commit; `--make-current` and `--promote` change the current build, which counts only when the emitter's receipt is `published` and names it as `current`. The command refuses before any emitter starts while the repository still has any `latest*.json` pointer file, or with `HF_HUB_OFFLINE` or `TRANSFORMERS_OFFLINE` set, and hands nothing over unless the emitter's write-access check passes; `microcosm-publish-release` refuses a repository that has `releases.json`. Build-folder manifests name `release` and `build` as strings, record `built_at`, `built_with_model_package` and `built_with_core_package` at the top level and a `role` on each artifact, and pin no `revision`; the release contract checks a UK release in that layout or in the tagged one, which the UK assemblers keep writing. For a registry entry that names a release (UK 2025 national and dense), `microcosm.data.load` reads the current build from `releases.json` where the repository has one, or the listed build `build=` names, and follows the pointer file exactly as before where it does not. UK releases keep publishing, promoting with `--promote-line` and sending Slack alerts through `tools/publish_release.sh` until the switch. The stable releases proposed for US builds, `populace-us-2024-national` (`national`, the default) and `populace-us-2024-local` (`local_area`), are recorded in `microcosm.data.contract.PROPOSED_US_RELEASES` but not used until they are agreed with the US data builder. diff --git a/packages/microcosm-data/README.md b/packages/microcosm-data/README.md index 5561b14dd2..94bbfe1f5e 100644 --- a/packages/microcosm-data/README.md +++ b/packages/microcosm-data/README.md @@ -22,7 +22,17 @@ sim.calculate("household_net_income", 2024).sum() `load("us")` (no year) loads the latest published compact year. It resolves `latest.json`, reads the selected release manifest at the immutable release tag, verifies the artifact SHA-256, and refuses model or Core versions outside -the release's certified compatibility specifiers. `available()` lists +the release's certified compatibility specifiers. + +A UK release can also be published into build folders, +`releases///`, once its repository switches to a +`releases.json` record of each release's builds and current build. The UK +2025 national and dense entries name their release: where the repository +has `releases.json`, `load("uk")` reads the current build there, then that +build's `release_manifest.json` and dataset, with the same SHA-256 and +engine checks, and `load("uk", build="")` loads a listed build (a +withdrawn one with a warning). Where it has none, the loader follows the +entry's pointer file (`latest-national.json`) exactly as before. `available()` lists the default-variant `(country, year)` pairs (the ones a bare ``load(country, year)`` resolves); `available_variants()` lists every published `(country, year, variant)`, non-default lines included. @@ -30,6 +40,8 @@ resolves); `available_variants()` lists every published The old mutable-root behavior is available only as an unsafe escape hatch: `load("us", 2024, unverified_root=True)`. It emits a runtime warning because it bypasses the release pointer, manifest, digest, and engine compatibility checks. +A repository that records its builds in `releases.json` has no root file, so it +refuses the option. ## Why a shard, not a repo per country From a06f3d83b52c28aa8e17ce39f51f58125c689441 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:50:44 +0400 Subject: [PATCH 23/26] Re-push so the pull request picks up this branch after GitHub's 2026-11-04 incident Co-Authored-By: Claude Opus 5.5 From a7a039ec0748d8c701c2c828faebbfcd0b26369e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:38:48 +0400 Subject: [PATCH 24/26] Test that only the Hub's 404 for releases.json counts as its absence Review round 2 found that the tagged publisher's releases.json check, and the loader's, treat huggingface_hub's LocalEntryNotFoundError as absence. huggingface_hub 1.18 raises it, as an EntryNotFoundError and a FileNotFoundError, when it could not ask the Hub: after a 5xx outlasted its retries, or on a 403. The fake Hubs now raise the Hub's own 404 error for a missing file, and these tests fail until the fix: - the tagged publisher refuses, writing nothing, when the read fails that way (no answer, 503, 403); - the loader does not fall back to the pointer file then, online; - the new command refuses an httpx network error while listing the repository, instead of a traceback; - its listing passes the credential the emitter reads, HF_TOKEN then HUGGINGFACE_TOKEN. Tests that already pass pin behaviour that holds: an offline load still falls back when releases.json was never cached, and each publisher refuses the other's manifest (a UK build-folder build through the tagged publisher, a tagged UK build through the new command). Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_release_publication.py | 103 ++++++++++++++++++ .../tests/engine_free/shared/test_loader.py | 70 +++++++++++- .../tests/engine_free/shared/test_release.py | 74 +++++++++++++ test_support/microcosm_data/hub_errors.py | 80 ++++++++++++++ test_support/microcosm_data/release.py | 5 +- 5 files changed, 328 insertions(+), 4 deletions(-) create mode 100644 test_support/microcosm_data/hub_errors.py diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py index 6beda3d720..c240c06121 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_release_publication.py @@ -13,6 +13,8 @@ from dataclasses import dataclass, field from pathlib import Path +import httpx +import huggingface_hub import pytest from microcosm_emitter_interface.releases import ReleaseRecordError, ReleasesRecord @@ -23,6 +25,7 @@ from test_support.microcosm_data.build_folders import UK_NATIONAL_BUILD from test_support.microcosm_data.release import ( _as_uk_national_build_folder_release, + _as_uk_national_line_release, artifact_root, # noqa: F401 (a fixture) release_dir, # noqa: F401 (a fixture) ) @@ -30,6 +33,9 @@ UK_REPO_ID = "policyengine/populace-uk-private" UK_NATIONAL_RELEASE_ID = "microcosm-uk-2024-25-national" UK_EARLIER_BUILD = "uk-frs-calibration-attempt-20260901T000000Z-0badcafe" +#: The command's own listing of the repository's files, before the fixture +#: below replaces it in every test. +REAL_REPOSITORY_FILES = release_publication._repository_files #: The variables ``huggingface_hub`` reads to refuse every Hub request. OFFLINE_VARIABLES = ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE") #: What ``check_write_access`` answers when the emitter finds no credential. @@ -457,6 +463,103 @@ def test_the_command_refuses_a_repository_with_pointer_files_before_an_emitter( assert repository == {} +def test_the_command_refuses_a_network_error_while_listing( + national: Path, + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, +) -> None: + """httpx's transport errors, such as a refused connection, are not + OSError; they are refused with the same explanation, not a traceback.""" + started, _ = _start_emitters(monkeypatch) + + def unreachable(repository: str) -> list[str]: + raise httpx.ConnectError("[Errno 61] Connection refused") + + monkeypatch.setattr( + release_publication, "_repository_files", unreachable, raising=False + ) + + code, output, error = _run( + [str(national), "--artifact-root", str(artifact_root)], capsys + ) + + assert code == 1 + assert started == [] + assert output is None + assert f"could not list the files of {UK_REPO_ID}" in error + assert "ConnectError" in error + + +@pytest.mark.parametrize( + ("environment", "token"), + [ + ({"HUGGINGFACE_TOKEN": "not-a-real-token-b"}, "not-a-real-token-b"), + ( + { + "HF_TOKEN": "not-a-real-token-a", + "HUGGINGFACE_TOKEN": "not-a-real-token-b", + }, + "not-a-real-token-a", + ), + ], + ids=["huggingface-token", "hf-token-first"], +) +def test_the_listing_reads_the_credential_the_emitter_reads( + monkeypatch, environment: dict, token: str +) -> None: + """The emitter reads HF_TOKEN, then HUGGINGFACE_TOKEN, then the saved + login; huggingface_hub alone does not read HUGGINGFACE_TOKEN, so the + listing passes it on.""" + for name in ("HF_TOKEN", "HUGGINGFACE_TOKEN"): + monkeypatch.delenv(name, raising=False) + for name, value in environment.items(): + monkeypatch.setenv(name, value) + tokens: list[str | None] = [] + + class RecordingApi: + def __init__(self, token: str | None = None) -> None: + tokens.append(token) + + def list_repo_files(self, repo_id: str, *, repo_type: str) -> list[str]: + assert (repo_id, repo_type) == (UK_REPO_ID, "dataset") + return ["README.md"] + + monkeypatch.setattr(huggingface_hub, "HfApi", RecordingApi) + + assert REAL_REPOSITORY_FILES(UK_REPO_ID) == ["README.md"] + assert tokens == [token] + + +@pytest.mark.parametrize("promote", [False, True], ids=["publish", "promote"]) +def test_the_command_refuses_a_tagged_uk_release( + release_dir: Path, # noqa: F811 + artifact_root: Path, # noqa: F811 + monkeypatch, + capsys, + hub_listing: HubListing, + promote: bool, +) -> None: + """Today's UK assemblers write the tagged layout, whose release manifest + describes the build in a ``build`` object; the command refuses it before + it lists the repository or starts an emitter.""" + tagged = _as_uk_national_line_release(release_dir) + started, _ = _start_emitters(monkeypatch) + argv = ( + [str(tagged), "--promote"] + if promote + else [str(tagged), "--artifact-root", str(artifact_root)] + ) + + code, output, error = _run(argv, capsys) + + assert code == 1 + assert started == [] + assert hub_listing.listed == [] + assert output is None + assert "does not name release" in error + + def test_the_command_refuses_when_it_cannot_list_the_repository( national: Path, artifact_root: Path, # noqa: F811 diff --git a/packages/microcosm-data/tests/engine_free/shared/test_loader.py b/packages/microcosm-data/tests/engine_free/shared/test_loader.py index 6d6c5e4b5e..a21f8e661c 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_loader.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_loader.py @@ -13,7 +13,11 @@ import huggingface_hub import pytest -from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError +from huggingface_hub.errors import ( + GatedRepoError, + LocalEntryNotFoundError, + RepositoryNotFoundError, +) import microcosm.data.loader as loader from microcosm.data import DEFAULT_VARIANT, download, latest_year, load, resolve @@ -33,6 +37,7 @@ UK_NATIONAL_BUILD, build_folder_release_manifest, ) +from test_support.microcosm_data.hub_errors import hub_unreachable, missing_on_hub #: Release id served by the hub fixture. Any well-formed id works: nothing in #: this suite may assert which release the live Hub currently points at, @@ -352,8 +357,11 @@ def __call__( try: return str(self.files[(repo_id, filename, revision)]) except KeyError as exc: - raise FileNotFoundError( - f"{repo_id}/{filename} at revision {revision!r}" + raise missing_on_hub( + repo_id, + filename, + revision, + message=f"{repo_id}/{filename} at revision {revision!r}", ) from exc @@ -959,6 +967,62 @@ def unreachable(**request) -> str: assert hub.calls == [] +@pytest.mark.parametrize( + "status_code", [None, 503, 403], ids=["no-answer", "server-error", "forbidden"] +) +def test_a_hub_failure_reading_releases_json_does_not_fall_back( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, status_code: int | None +) -> None: + """Online, huggingface_hub raises LocalEntryNotFoundError when it could + not ask the Hub, after a 5xx or on a 403. That is not the file's absence: + falling back would load the pointer's build after the switch.""" + monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", False) + hub = _line_pointer_hub( + tmp_path, + line="national", + release_id=UK_NATIONAL_RELEASE_ID, + revision=UK_NATIONAL_CUT_TAG, + manifest=_uk_national_line_manifest(), + ) + + def unreachable(**request) -> str: + if request["filename"] == "releases.json": + raise hub_unreachable(UK_REPO_ID, "releases.json", status_code=status_code) + return hub(**request) + + with pytest.raises(LocalEntryNotFoundError): + loader._resolve_certified_release(resolve("uk", 2025), hub_download=unreachable) + assert hub.calls == [] + + +def test_offline_a_releases_json_never_cached_falls_back_to_the_pointer_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """In offline mode the cache is all there is: a releases.json never + cached loads the cached pointer file's build, as an offline load did + before.""" + monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", True) + hub = _line_pointer_hub( + tmp_path, + line="national", + release_id=UK_NATIONAL_RELEASE_ID, + revision=UK_NATIONAL_CUT_TAG, + manifest=_uk_national_line_manifest(), + ) + + def offline(**request) -> str: + if request["filename"] == "releases.json": + raise hub_unreachable(UK_REPO_ID, "releases.json") + return hub(**request) + + certified = loader._resolve_certified_release( + resolve("uk", 2025), hub_download=offline + ) + + assert certified.release_id == UK_NATIONAL_RELEASE_ID + assert certified.artifact_revision == UK_NATIONAL_CUT_TAG + + def test_line_pointer_refuses_any_artifact_revision_mismatch(tmp_path: Path) -> None: manifest = _uk_national_line_manifest() manifest["artifacts"]["calibration_report"] = { diff --git a/packages/microcosm-data/tests/engine_free/shared/test_release.py b/packages/microcosm-data/tests/engine_free/shared/test_release.py index b81562c083..45f3f09427 100644 --- a/packages/microcosm-data/tests/engine_free/shared/test_release.py +++ b/packages/microcosm-data/tests/engine_free/shared/test_release.py @@ -1,6 +1,9 @@ """Tests split from packages/microcosm-data/tests/test_release.py.""" # ruff: noqa: F403, F405 +from huggingface_hub.errors import LocalEntryNotFoundError + +from test_support.microcosm_data.hub_errors import hub_unreachable from test_support.microcosm_data.release import * @@ -319,6 +322,77 @@ def test_the_tagged_publisher_refuses_a_repository_with_releases_json( assert [event for event, _ in hub.events] == [] +@pytest.mark.parametrize( + "status_code", [None, 503, 403], ids=["no-answer", "server-error", "forbidden"] +) +def test_the_tagged_publisher_refuses_when_it_cannot_read_releases_json( + hub: FakeHub, + release_dir: Path, + artifact_root: Path, + monkeypatch, + status_code: int | None, +) -> None: + """Only the Hub's 404 for releases.json lets a publication go on. + + huggingface_hub raises LocalEntryNotFoundError, which is also an + EntryNotFoundError and a FileNotFoundError, when it could not ask the + Hub: after a 5xx outlasted its retries, or on a 403. A publication that + went on could write a tag and a pointer file beside a releases.json. + """ + monkeypatch.setattr(release_module, "notify_release", lambda *a, **k: None) + download = hub.hf_hub_download + + def unreachable(*, repo_id, filename, repo_type, revision=None): + if filename == "releases.json": + raise hub_unreachable(repo_id, filename, revision, status_code=status_code) + return download( + repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision + ) + + monkeypatch.setattr(hub, "hf_hub_download", unreachable) + + with pytest.raises(LocalEntryNotFoundError): + publish_release( + release_dir, + "policyengine/populace-us", + api=hub, + artifact_root=artifact_root, + ) + + assert hub.tags == [] + assert hub.uploads == [] + assert [event for event, _ in hub.events] == [] + + +def test_the_tagged_publisher_refuses_a_uk_build_folder_release( + release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch +) -> None: + """A build in the build-folder layout pins no revision, so the tagged + publisher, which publishes a revision per build, refuses it before any + Hub request.""" + national = _as_uk_national_build_folder_release(release_dir) + monkeypatch.setattr( + release_module, "validate_release_dir", lambda _path, **_kwargs: [] + ) + hub = _uk_hub(tmp_path) + events_before = list(hub.events) + + with pytest.raises(ValueError): + release_module.prepare_release(national, artifact_root=artifact_root) + with pytest.raises(ValueError): + publish_release( + national, + "policyengine/populace-uk-private", + api=hub, + artifact_root=artifact_root, + update_latest=False, + ) + + assert hub.events == events_before + assert hub.tags == [] + assert hub.uploads == [] + + def test_the_tagged_publisher_refuses_a_uk_promotion_once_releases_json_exists( release_dir: Path, artifact_root: Path, tmp_path: Path, monkeypatch ) -> None: diff --git a/test_support/microcosm_data/hub_errors.py b/test_support/microcosm_data/hub_errors.py new file mode 100644 index 0000000000..07add0639b --- /dev/null +++ b/test_support/microcosm_data/hub_errors.py @@ -0,0 +1,80 @@ +"""Download errors as huggingface_hub 1.x raises them, for the fake Hubs. + +``hf_hub_download`` answers a file the Hub reports missing (HTTP 404) with +``RemoteEntryNotFoundError``. When it could not ask the Hub, for example +after a 5xx outlasted its retries or on a 403, and nothing is cached for that +revision, it raises ``LocalEntryNotFoundError`` instead, which also inherits +from ``EntryNotFoundError`` and ``FileNotFoundError``. Only the first means +the file is not there. +""" + +from __future__ import annotations + +import httpx +from huggingface_hub.errors import ( + HfHubHTTPError, + LocalEntryNotFoundError, + RemoteEntryNotFoundError, +) + +#: A host that never resolves; no fake makes a request to it. +_FAKE_HUB = "https://hub.invalid" + + +class MissingOnHubError(RemoteEntryNotFoundError, FileNotFoundError): + """The Hub's 404 for a file, as the fake Hubs raise it. + + It is also a ``FileNotFoundError``, as the fakes' earlier error was, so + tests that expect one keep reading the same failure. + """ + + +def _request(repo_id: str, filename: str, revision: str | None) -> httpx.Request: + return httpx.Request( + "HEAD", + f"{_FAKE_HUB}/datasets/{repo_id}/resolve/{revision or 'main'}/{filename}", + ) + + +def missing_on_hub( + repo_id: str, + filename: str, + revision: str | None = None, + *, + message: str | None = None, +) -> MissingOnHubError: + """The error for a file the Hub reports missing at ``revision``.""" + return MissingOnHubError( + message + or ( + f"404 Client Error: entry not found for {repo_id}/{filename} at " + f"revision {revision!r}" + ), + response=httpx.Response(404, request=_request(repo_id, filename, revision)), + ) + + +def hub_unreachable( + repo_id: str, + filename: str, + revision: str | None = None, + *, + status_code: int | None = None, +) -> LocalEntryNotFoundError: + """The error ``hf_hub_download`` raises when it could not ask the Hub. + + With ``status_code`` (a 5xx after the retries, or a 403), it is raised + from the Hub's HTTP error, as huggingface_hub raises it. + """ + error = LocalEntryNotFoundError( + f"could not reach the Hub for {repo_id}/{filename} and it is not in the " + "local cache" + ) + if status_code is not None: + error.__cause__ = HfHubHTTPError( + f"{status_code} Server Error for {repo_id}/{filename}", + response=httpx.Response( + status_code, request=_request(repo_id, filename, revision) + ), + ) + return error diff --git a/test_support/microcosm_data/release.py b/test_support/microcosm_data/release.py index 6632efe46a..ae048af335 100644 --- a/test_support/microcosm_data/release.py +++ b/test_support/microcosm_data/release.py @@ -46,6 +46,7 @@ UK_NATIONAL_BUILD, to_build_folder_layout, ) +from test_support.microcosm_data.hub_errors import missing_on_hub @pytest.fixture(autouse=True) @@ -530,7 +531,9 @@ def hf_hub_download(self, *, repo_id, filename, repo_type, revision=None) -> str try: content = self._commits[commit][filename] except KeyError as exc: - raise FileNotFoundError(f"{filename}@{ref}") from exc + raise missing_on_hub( + repo_id, filename, ref, message=f"{filename}@{ref}" + ) from exc local = self._download_dir / ref / filename local.parent.mkdir(parents=True, exist_ok=True) local.write_bytes(content) From 9f3367cbecbbd7773ecfec16e3b39a82d7010cff Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:41:41 +0400 Subject: [PATCH 25/26] Count only the Hub's 404 for releases.json as its absence The tagged publisher's releases.json check and the loader's now share microcosm.data.release.missing_on_hub: a download failure means the file is absent only when it is the Hub's EntryNotFoundError for a 404, not LocalEntryNotFoundError, which huggingface_hub raises when it could not ask the Hub (a 5xx after its retries, a 403) and nothing is cached. So during an outage the tagged publisher refuses before writing anything, instead of possibly writing a tag and a pointer file beside a releases.json, and the loader does not fall back to the pointer file. In offline mode, a releases.json that was never cached still reads as absent for the loader, as an offline load did before. The new command's listing turns httpx transport errors, such as a refused connection, into its "could not list" refusal, and passes HF_TOKEN, then HUGGINGFACE_TOKEN, as the emitter reads them. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/release_publication.py | 31 ++++++++++++++++--- .../src/microcosm/data/loader.py | 30 +++++++++++------- .../src/microcosm/data/release.py | 28 +++++++++++++++-- 3 files changed, 70 insertions(+), 19 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/release_publication.py b/packages/microcosm-build/src/microcosm/build/release_publication.py index 143f031785..8ebdd6575f 100644 --- a/packages/microcosm-build/src/microcosm/build/release_publication.py +++ b/packages/microcosm-build/src/microcosm/build/release_publication.py @@ -31,7 +31,7 @@ check passes, as the staged-bundle hand-over does: otherwise the change would wait, pending, until the emitter dropped it an hour later. The command's own listing of the repository's files uses ``huggingface_hub`` in -this process, with the same credential. Publication sends no Slack alert; +this process, with the credential the emitter reads. Publication sends no Slack alert; the dashboard announces changes to ``releases.json``. """ @@ -39,6 +39,7 @@ import argparse import json +import os import sys from dataclasses import dataclass from pathlib import Path @@ -270,10 +271,30 @@ def _refuse_offline() -> None: def _repository_files(repository: str) -> list[str]: - """Every file path on the dataset repository's ``main`` (test seam).""" - from huggingface_hub import HfApi + """Every file path on the dataset repository's ``main`` (test seam). - return list(HfApi().list_repo_files(repository, repo_type="dataset")) + It reads with the credential the emitter uses: ``HF_TOKEN``, then + ``HUGGINGFACE_TOKEN``, then (``huggingface_hub``'s own order) the saved + login. ``huggingface_hub`` does not read ``HUGGINGFACE_TOKEN`` itself. + """ + import huggingface_hub + + token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN") or None + api = huggingface_hub.HfApi(token=token) + return list(api.list_repo_files(repository, repo_type="dataset")) + + +def _listing_errors() -> tuple[type[BaseException], ...]: + """The failures a listing raises: the Hub's, offline mode's and httpx's. + + huggingface_hub's HTTP and offline errors are ``OSError``; httpx's + transport errors, such as a refused connection, are not. + """ + try: + import httpx + except ImportError: # pragma: no cover - huggingface_hub 1.x requires it + return (OSError, ValueError) + return (OSError, ValueError, httpx.HTTPError) def _refuse_pointer_files(repository: str) -> None: @@ -287,7 +308,7 @@ def _refuse_pointer_files(repository: str) -> None: """ try: paths = _repository_files(repository) - except (OSError, ValueError) as error: + except _listing_errors() as error: raise ValueError( f"could not list the files of {repository} to check for " f"latest*.json pointer files ({type(error).__name__}: {error}); " diff --git a/packages/microcosm-data/src/microcosm/data/loader.py b/packages/microcosm-data/src/microcosm/data/loader.py index c79f1a808a..d3965262f7 100644 --- a/packages/microcosm-data/src/microcosm/data/loader.py +++ b/packages/microcosm-data/src/microcosm/data/loader.py @@ -53,6 +53,7 @@ latest_line_release, latest_release, line_pointer_path, + missing_on_hub, ) from microcosm.data.releases_record import ( RELEASES_RECORD_PATH, @@ -74,10 +75,6 @@ re.escape(LINE_POINTER_PATH_TEMPLATE).replace(re.escape("{line}"), r"(?P.+)") ) _HubDownload = Callable[..., str] -#: The exception names that mean a file is absent from the repository (the -#: Hub's ``EntryNotFoundError``, or a test fake's ``FileNotFoundError``), -#: and nothing else. -_ABSENT_FILE_ERRORS = frozenset({"EntryNotFoundError", "FileNotFoundError"}) def _line_from_pointer_path(pointer_path: str) -> str | None: @@ -549,9 +546,18 @@ def _pointer_for( ) -def _is_absent_file_error(exc: BaseException) -> bool: - """Whether a download failed only because the file is not there.""" - return bool({cls.__name__ for cls in type(exc).__mro__} & _ABSENT_FILE_ERRORS) +def _never_cached_offline(exc: BaseException) -> bool: + """Whether huggingface_hub is offline and the file was never cached. + + Offline, the cache is all a load has, so a ``releases.json`` that was + never cached reads as absent, as the pointer files then do. + """ + try: + from huggingface_hub import constants + from huggingface_hub.utils import LocalEntryNotFoundError + except ImportError: # pragma: no cover - declared dependency + return False + return bool(constants.HF_HUB_OFFLINE) and isinstance(exc, LocalEntryNotFoundError) def _releases_record_bytes( @@ -560,16 +566,18 @@ def _releases_record_bytes( """The repository's ``releases.json``, or ``None`` when it has none. Until its switch to build folders a repository has no ``releases.json``, - and its releases are found through their pointer files. Only the file's - absence means that (offline, a file that was never cached counts as - absent, as the pointer files then are); any other failure propagates. + and its releases are found through their pointer files. Only the Hub's + answer that the file is absent (:func:`~microcosm.data.release.missing_on_hub`) + means that, or, in offline mode, a file that was never cached. Any other + failure propagates, a server error included: falling back then would load + the pointer file's build in a repository that has switched. """ try: record_path = hub_download( repo_id=spec.hf_repo, filename=RELEASES_RECORD_PATH, repo_type="dataset" ) except Exception as exc: - if _is_absent_file_error(exc): + if missing_on_hub(exc) or _never_cached_offline(exc): return None raise return Path(record_path).read_bytes() diff --git a/packages/microcosm-data/src/microcosm/data/release.py b/packages/microcosm-data/src/microcosm/data/release.py index 652b0e8481..38206e4ab5 100644 --- a/packages/microcosm-data/src/microcosm/data/release.py +++ b/packages/microcosm-data/src/microcosm/data/release.py @@ -91,6 +91,7 @@ "latest_line_release", "latest_pointer_payload", "line_pointer_path", + "missing_on_hub", "line_pointer_payload", "publish_release", "latest_release", @@ -1025,14 +1026,35 @@ def _repo_revision(api: object, *, repo_id: str) -> str | None: return str(value) if value else None +def missing_on_hub(error: BaseException) -> bool: + """Whether a download failed because the Hub answered that the file is absent. + + Only that answer counts: ``EntryNotFoundError`` for the Hub's 404 + (``RemoteEntryNotFoundError`` in huggingface_hub 1.x). huggingface_hub + also raises ``LocalEntryNotFoundError``, a subclass of it and of + ``FileNotFoundError``, when it could not ask the Hub (a 5xx that outlasted + its retries, a 403, offline mode) and nothing is cached; that says + nothing about the file, so it, like every other error, does not count. + """ + try: + from huggingface_hub.utils import EntryNotFoundError, LocalEntryNotFoundError + except ImportError: # pragma: no cover - declared dependency + return False + return isinstance(error, EntryNotFoundError) and not isinstance( + error, LocalEntryNotFoundError + ) + + def _refuse_releases_record(api: object, *, repo_id: str, revision: str | None) -> None: """Refuse a repository that records its builds in ``releases.json``. Such a repository publishes each build into its own folder through the emitter, and ``releases.json`` is the only record of which build is current; a tag or ``latest*.json`` pointer file written beside it would - disagree with the record. Only the file's absence lets the publication - go on; any other failure to read it propagates. + disagree with the record. Only the Hub's answer that the file is absent + (:func:`missing_on_hub`) lets the publication go on; any other failure + to read it, a server error included, propagates before anything is + written. """ try: api.hf_hub_download( @@ -1042,7 +1064,7 @@ def _refuse_releases_record(api: object, *, repo_id: str, revision: str | None) revision=revision, ) except Exception as exc: - if _is_absent_entry_error(exc): + if missing_on_hub(exc): return raise raise ValueError( From 651e94d99dd43ff06d84269b4c6827a1887ffd32 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:42:11 +0400 Subject: [PATCH 26/26] Say which UK releases keep a publication path through the switch Each publisher refusing the other's layout keeps a path for the UK national, dense and local-area releases. After the UK repository's switch, its June 2023 release (pointer latest.json) and populace-uk---k releases have none yet; the README says that is open for the switch. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c68e393889..858f2bb379 100644 --- a/README.md +++ b/README.md @@ -488,7 +488,8 @@ uv run microcosm-publish-release-build releases/ --promote A build counts as current only when the emitter's receipt is `published` and names it as `current`. Each path refuses a repository in the other's layout, -so a UK release always has one way to change its current build: +so the UK national, dense and local-area releases always have one way to +change their current build: - `microcosm-publish-release-build` lists the repository's files and refuses, before any emitter starts, while any `latest*.json` pointer file is there. @@ -503,7 +504,10 @@ commit that writes `releases.json` and deletes the pointer files. Release alerts do not stop: the switch waits until the dashboard posts them from changes to `releases.json`. `microcosm.data.load` reads a release's current build from `releases.json` where the repository has one, and follows its -pointer file otherwise. +pointer file otherwise. The UK repository's other releases, the June 2023 +release (whose pointer is `latest.json`) and `populace-uk---k` +releases, have no publication path after its switch yet; that is open for +the switch. The publisher uploads only the contract files, the release manifest's artifacts and any `--extra-file`. The US fiscal-refresh tool therefore binds