diff --git a/README.md b/README.md index 63fab77bcf..c0ef54002c 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,12 @@ python tools/build_us_fiscal_refresh_release.py \ This writes `progress.json`, `events.ndjson`, `calibration_progress.json`, and final candidate diagnostics under `runs//` in the staging repository. +The build stops once its H5 and its own gates' verdicts are written, at +`/build_record.json`, so it can be evaluated first; nothing it writes is +publishable. To publish it, certify it with +`tools/certify_us_national_build.py `, which runs the release's +post-export checks and writes the manifests +([Build, then certify](docs/us-release-build-rule.md#build-then-certify)). Nothing is published to `policyengine/populace-us`: the build is published only by the commands described in [Releasing & alerts](#releasing--alerts). diff --git a/changelog.d/1585-us-build-then-certify.changed.md b/changelog.d/1585-us-build-then-certify.changed.md new file mode 100644 index 0000000000..994f636a29 --- /dev/null +++ b/changelog.d/1585-us-build-then-certify.changed.md @@ -0,0 +1 @@ +The US national release tool builds and stops: it writes the dataset, its calibration weights, its diagnostics and the verdicts of the gates the build runs, plus `build_record.json`, and exits so the build can be evaluated. A new command, `tools/certify_us_national_build.py`, certifies a finished build: it runs the release's post-export checks on the written H5 and writes the manifests publication requires. Route A stops after the build too, and `route_a.sh --certify` certifies it (microcosm#1585, item 11). A build whose release gates fail still writes its H5 and record, so it can be evaluated or start a later build, but it cannot be certified, and no gate takes it as a reference. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index e3793d8c5b..58a385c1b1 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -378,8 +378,11 @@ through the emitter (`microcosm-publish-release-build`, from call to the same command with `--promote`, and withdrawing one is `microcosm-withdraw-release-build `, which sets its `withdrawn` flag through the same release writer. Each US builder writes its build to -`releases//`; the national builder and the ACS package stage also -print both commands. +`releases//`. The national builder builds and stops at +`/build_record.json`, printing the command that certifies the build; +`tools/certify_us_national_build.py` runs the release's post-export checks, +writes the manifests and prints both commands (microcosm#1585 item 11). The +ACS package stage prints both commands itself. `tools/preflight_us_release_gates.py` runs the US national release checks that need no calibration on the base before a build, and again with the finished build's `--release-manifest`. The emitter changes @@ -463,7 +466,11 @@ Before a release rerun, run the small-H5 guard sweep described in [the release build rule](us-release-build-rule.md#post-export-scoring). That fixture check is separate from full-export timing and release certification. -To check the post-export stages on a written export without a full rerun, +A US national build stops before its post-export checks; certify it with +`tools/certify_us_national_build.py ` only when it is to be published +(the release build rule's +[Build, then certify](us-release-build-rule.md#build-then-certify)). To check +the post-export stages on a written export without certifying it, subsample it and probe it as [the release build rule](us-release-build-rule.md#probing-an-export-on-a-household-subsample) describes (`tools/sample_us_export_households.py`, diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 6ea4f3ed17..c71bcb7d02 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -14,6 +14,15 @@ large enough to change how the dataset is built carries a from-scratch build and certification receipt from its own tree before it merges. Main carries the same build as a standing check afterwards. +Since a build and its certification are two steps +([Build, then certify](#build-then-certify)), a receipt and the standing check +need both halves: the build from raw sources, its certification, and the two +preflights on the certified build, the release-gate preflight on its release +manifest and the publisher's `--preflight-only` check. A Route A run without +`--certify` stops at `ROUTE_A_BUILT.json`, before the post-export checks and +those two preflights, so it shows the build half only. The same run continued +with `route_a.sh --certify` on its `RUN_ROOT` makes the receipt. + A dataset earns default status separately, by beating the incumbent. The rule main enforces is microcosm#578's: the candidate beats the incumbent on the frozen comparison register, both rescored on it, with strict improvement @@ -41,12 +50,93 @@ holdout exists and has run. Publication stays a human step. Since the US repository's switch to `releases.json`, the release tool writes each build to -`/releases/microcosm-us-2024-national/` and prints two commands: +`/releases/microcosm-us-2024-national/`. It builds and stops; the +certification step below writes the manifests and prints two commands: `microcosm-publish-release-build` publishes the build into its own folder of the national release without making it current, and the same command with `--promote` makes it the release's current build. Only that promotion makes a build the certified default. +## Build, then certify + +A US national build and its certification are two steps (microcosm#1585 item +11, PR 4a), as they are for a UK national cut. + +- **The build** (`tools/build_us_fiscal_refresh_release.py`) runs every input + stage and the gate after it, the pre-solve gates, target compilation, the + solve, the terminal gates and the H5 write, then writes the calibration NPZ + and, when asked, runs the export audit. It writes `/build_record.json` + and stops, printing the command that certifies it. Nothing it writes is + publishable: the release directory holds the calibration diagnostics and the + gate evidence, but no manifest. +- **Certification** (`tools/certify_us_national_build.py `) runs from the + record: the reform-coverage smoke, reform validation, demographics and the + holdouts on the written H5, then source coverage and take-up participation, + then both manifests. It needs the build's directory, a checkout of the + build's commit, the packages the build ran on and, where the build staged, + its staging credential; it needs none of the build's raw inputs. +- **Why.** On the 30 September and 24 October Route A builds, the work after + calibration took 28.3 h of 33.0 h and 52.8 h of 56.5 h + (`timing.elapsed_through_calibration_seconds` against + `timing.total_build_seconds`). Most of it is the post-export scoring: 41 + smoke and 55 validation reform passes, each over 177 household batches. A + build made to test a change no longer pays for them, and a build that proves + itself is certified as it stands, without a rebuild. +- **The record** pins by sha256 every file of the build that certification + reads: the H5, the calibration weights, the diagnostics, the SSI take-up + measurement and the gate evidence the build wrote (and, for an + `--scf-education-debt` build, its fit tables). Its paths are relative to + itself, so a build directory moved to another machine certifies in place. It + holds the build's provenance (its commit, the time it finished and the + packages that built it), which the manifests carry as the build's, the + options the checks read, the 13 gate verdicts the manifests carry, the + release gate summary, the calibration losses and in-sample fit, the + post-export scoring plan, the source-coverage and take-up receipts, and + where the build staged. It carries a digest of itself (`record_sha256`), so + an edit after the build is refused; anyone who recomputes the digest can + still change it, until certification signs (PR 4b). Certification rebuilds + the scoring plan and refuses one that differs from the recorded plan. +- **Refusals.** Certification refuses a record of another schema, naming the + commit that built it, whose code can certify it; a record whose files + changed after the build, or a file it would read that appeared after the + build; a checkout at another commit, or with changes outside the build + directory; packages other than the ones the build was built with (`runtime` + in the record), since the manifests name those as the build's; and a release + directory that already carries a release manifest. A build refuses an + `--out` that holds a build awaiting certification; a failed build's `--out` + may be built into again. +- **Staging.** Certification opens a staging run of its own where its build + staged (the build's run id with `-certify` appended, to the build's staging + repository), so the post-export verdicts and the manifests reach the staging + dashboard, and a failed certification marks that run failed. The build + manifest's `staging` block, which the publisher checks, is certification's, + with the build's inside it under `build`. A build that did not stage is + certified without staging, and `--no-staging` opts certification out where + the build staged too, as a build may opt out; the block's reason then says + the build staged. Certification refuses a `--staging-run-id` that names the + build or its staging run, whose files a reopened run would start afresh. +- **A failed release gate.** A build whose terminal gates fail still writes + its H5, its calibration weights, its #568 weight evidence and its record, + so it can be evaluated, and exits with the same "Release gates failed" error + once its record is written. A written-file stored-input failure or an + export-audit error after the H5 write joins those failures rather than + replacing them. Certification refuses a record that carries release-gate + failures, unless the build is evidence-tier, and refuses any build whose + release directory holds the #568 weight evidence, which only a failed build + writes. No gate judges against it: a later build refuses any file under + its `--out` as an input-mass reference, and the post-export probe refuses + its release directory as the reference. Its files may still start a later + build, as its base, selection source or warm start, since that build's own + gates judge the result, and the probe may score its H5. Input gates still + stop the build where they fail. +- **Timing.** Both manifests' `timing` blocks carry `build_seconds` and + `certify_seconds`; `total_build_seconds` is their sum. +- **Drivers.** Route A (`tools/route_a/route_a.sh`) stops after the build with + `ROUTE_A_BUILT.json`; `route_a.sh --certify` on the same `RUN_ROOT` certifies + that build, without hashing its raw inputs again, and runs the release-gate + and publisher preflights. The exact-k ladder launcher's receipt carries the + command that certifies its build. + ## What stands between main and that build A from-scratch attempt ran on main at `51c314382` on 15 and 16 September 2026 @@ -448,7 +538,9 @@ all 8 authoritative smoke verdicts agree with the full-size build. `--reference-release-dir` points at a full-size build's release directory: `releases/microcosm-us-2024-national/` for a build made since the US switch, -or `releases//` for an earlier one. The probe reads the target +or `releases//` for an earlier one. A build that has not been +certified works too: it has no manifests, so the probe reads its target +surface from the `build_record.json` in its `--out` directory. The probe reads the target surface selection from the release manifest's top level in the first case and from its `build` object in the second, and says which field it read. It supplies the build's target surface, QRF register and calibration fit (so diff --git a/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py b/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py index b707689daa..54a8368faf 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_release_contract_fixture_generation.py @@ -133,7 +133,8 @@ def test_each_manifest_golden_names_the_writers_its_real_build_calls(): """A golden freezes live bytes only while the real build path still calls the writers ``writers.json`` names for it: the UK assembler's ``_stage_and_finalize`` calls the pure function and its serializer, the US - builder's ``_main`` calls ``_build_manifests`` and + builder's certification (``_certify_us_build``, run from the build record + ``_main`` writes, microcosm#1585 item 11) calls ``_build_manifests`` and ``_finish_build_folder_release``, and that function calls ``rewrite_release_dir``.""" @@ -164,8 +165,9 @@ def named(release_id: str) -> list[tuple[str, str]]: ("microcosm.data.build_folder_manifests", "rewrite_release_dir"), ] assert {"_build_manifests", "_finish_build_folder_release"} <= _called_in( - US_BUILDER_TOOL, "_main" + US_BUILDER_TOOL, "_certify_us_build" ) + assert "_write_us_build_record" in _called_in(US_BUILDER_TOOL, "_main") assert "rewrite_release_dir" in _called_in( US_BUILDER_TOOL, "_finish_build_folder_release" ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py index 9317c8a0c0..867b7f6723 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py +++ b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py @@ -1242,3 +1242,136 @@ def test_route_a_hands_over_the_emitter_publication_commands() -> None: assert ( f'shlex.join({command}, "--repo-id", "policyengine/populace-us", "--promote"])' ) in source + + +def test_route_a_stops_after_the_build_and_certifies_only_when_asked() -> None: + """The release tool builds and stops; the driver hands the build over + unless --certify (or ROUTE_A_CERTIFY=1) asks it to certify it, which reruns + no accepted stage (microcosm#1585 item 11, PR 4a).""" + source = (ROUTE_A_TOOLS / "route_a.sh").read_text(encoding="utf-8") + + assert "--certify) CERTIFY_FLAG=1 ;;" in source + assert ': "${ROUTE_A_CERTIFY=0}"' in source + assert 'case "$ROUTE_A_CERTIFY" in 0|1)' in source + built = source.index('[ -f "$REL_OUT/build_record.json" ]') + handoff = source.index('if [ "$ROUTE_A_CERTIFY" != 1 ]; then') + certify = source.index("run_stage certify 0") + certified = source.index('[ -f "$REL_DIR/release_manifest.json" ]') + preflight = source.index("run_stage preflight-release") + assert built < handoff < certify < certified < preflight + assert '"$RUN_ROOT/ROUTE_A_BUILT.json"' in source + # A build-only run whose base preflight is blocked exits 4, as a + # certified one does; the example settings name the switch. + built_only = source[handoff:certify] + assert built_only.index('if [ "$PF_BLOCKED" = 1 ]; then') < built_only.index( + "exit 4" + ) + assert built_only.index("exit 4") < built_only.index("exit 0") + example = (ROUTE_A_TOOLS / "route_a.env.example").read_text(encoding="utf-8") + assert ': "${ROUTE_A_CERTIFY=0}"' in example + # The certify stage runs the command certify_command builds, in the + # release stage's environment. + assert ( + " certify_command\n" + ' write_config certify 110 "$RELEASE_RAM_GIB" 45 ' + '"${CERTIFY_WALL_SECONDS:-345600}" 2000000 "$W" "$BUILD_ENV" -- \\\n' + ' "${CERTIFY_ARGV[@]}"\n' + ) in source + + +def _certify_argv(staging: str | None) -> list[str]: + settings = { + "W": "/fixture/worktree", + "REL_OUT": "/fixture/release-out", + "TOKEN_WRAPPER": str(ROUTE_A_TOOLS / "with_hf_token.sh"), + "AGENT_SECRET": "/fixture/agent-secret", + } + script = "set -eu\nfail() { printf '%s\\n' \"$*\" >&2; exit 1; }\n" + script += "\n".join( + f"{key}={shlex.quote(value)}" for key, value in settings.items() + ) + script += "\nunset ROUTE_A_STAGING\n" + if staging is not None: + script += f"ROUTE_A_STAGING={shlex.quote(staging)}\n" + script += _function("certify_command") + script += '\ncertify_command\nprintf "%s\\0" "${CERTIFY_ARGV[@]}"\n' + result = subprocess.run( + ["bash", "-c", script], capture_output=True, check=False, timeout=20 + ) + assert result.returncode == 0, result.stderr.decode() + return result.stdout.decode().rstrip("\0").split("\0") + + +@pytest.mark.parametrize("staging", [None, "1", "0"]) +def test_certification_stages_like_the_release(staging: str | None) -> None: + """Certification opens a staging run where its build staged, so it gets + the release stage's staging credential; without staging it runs as the + release stage does, online and without the HF tokens (microcosm#1585 + item 11, PR 4a).""" + argv = _certify_argv(staging) + command = [ + "/fixture/worktree/.venv/bin/python", + "-B", + "tools/certify_us_national_build.py", + "/fixture/release-out", + ] + if staging == "0": + release = _release_argv("0") + launcher = release[: release.index(sys.executable)] + assert launcher == [ + "/usr/bin/env", + "-u", + "HF_TOKEN", + "-u", + "HUGGING_FACE_HUB_TOKEN", + "-u", + "HUGGINGFACE_HUB_TOKEN", + "-u", + "HUGGING_FACE_TOKEN_MAX", + ] + assert argv == [*launcher, *command, "--no-staging"] + else: + assert argv == [ + str(ROUTE_A_TOOLS / "with_hf_token.sh"), + "/fixture/agent-secret", + *command, + ] + + +def test_route_a_certifies_an_accepted_build_without_hashing_its_inputs() -> None: + """Certification reads none of the raw inputs, which the build verified + when it ran, so --certify on an accepted build hashes them neither at the + start nor after the wait (microcosm#1585 item 11, PR 4a).""" + source = (ROUTE_A_TOOLS / "route_a.sh").read_text(encoding="utf-8") + decided = source.index( + 'if [ "$ROUTE_A_CERTIFY" = 1 ] && ' + '[ -f "$RUN_ROOT/run-${C:0:12}/release-sup/ACCEPTED" ]; then' + ) + first = source.index("verify_inputs\nfi\ncheck_commit") + waited = source.index('if [ "$CERTIFY_ONLY" != 1 ]; then\n verify_inputs\n') + assert decided < first < waited + # The run directory the decision reads is the one the stages use. + assert "RUN=$RUN_ROOT/run-${C:0:12}\n" in source + # A real run calls it only inside those two guards; --resolve, which + # exits before the real run, hashes them as before. + real_run = source[source.index("# Real run.") :] + calls = [line for line in real_run.splitlines() if line.strip() == "verify_inputs"] + assert calls == [" verify_inputs", " verify_inputs"] + + +@pytest.mark.parametrize("flag", ["--certify", "--resolve"]) +def test_route_a_parses_its_modes_before_reading_settings( + tmp_path: Path, flag: str +) -> None: + script = ROUTE_A_TOOLS / "route_a.sh" + env = {**os.environ, "ROUTE_A_ENV": str(tmp_path / "absent.env")} + known = subprocess.run( + ["bash", str(script), flag], capture_output=True, env=env, timeout=20 + ) + assert known.returncode == 64 + assert b"missing settings" in known.stderr + unknown = subprocess.run( + ["bash", str(script), "--bogus"], capture_output=True, env=env, timeout=20 + ) + assert unknown.returncode == 64 + assert b"[--resolve|--certify]" in unknown.stderr diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_exact_k_ladder_launcher.py b/packages/microcosm-build/tests/engine_free/us/test_us_exact_k_ladder_launcher.py index cc966a262a..10b2f59546 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_exact_k_ladder_launcher.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_exact_k_ladder_launcher.py @@ -298,6 +298,12 @@ def fake_builder(argv): assert result["build"] == "populace-us-2024-k8-fixture" assert result["release_dir"] == str(release_dir) assert result["artifact_root"] == str(artifact_root) + # The build is not certified: the receipt carries the command that + # certifies it (microcosm#1585 item 11, PR 4a). + assert result["certified"] is False + assert result["certify_command"].endswith( + f"tools/certify_us_national_build.py {tmp_path / 'out'}" + ) # The launcher neither publishes the build nor makes it current: it prints # the commands that do, and says what promoting does. assert result["automatic_publish"] is False diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index 67f902fee7..c902b401fc 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -5,6 +5,7 @@ import json import os import re +import subprocess import sys from dataclasses import replace from datetime import UTC, datetime @@ -53,6 +54,64 @@ def _load_builder_module(): return module +def _builder_function(builder, name: str): + """One top-level function of the builder, parsed from the tool's file.""" + import ast + + tree = ast.parse(Path(builder.__file__).read_text()) + return next( + node + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name == name + ) + + +def _calls_named(function, name: str) -> list: + import ast + + return [ + node + for node in ast.walk(function) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == name + ] + + +def _manifest_call(builder): + """The one ``_build_manifests`` call, which certification makes. + + The build (``_main``) writes no manifest: it records what certification + needs in ``_us_build_record(...)``, and ``_certify_us_build`` reads the + record back and writes both manifests (microcosm#1585 item 11, PR 4a). + """ + assert not _calls_named(_builder_function(builder, "_main"), "_build_manifests") + [call] = _calls_named( + _builder_function(builder, "_certify_us_build"), "_build_manifests" + ) + return call + + +def _recorded(builder, keyword: str) -> str: + """What ``_main`` hands the build record under ``keyword``, unparsed.""" + import ast + + [call] = _calls_named(_builder_function(builder, "_main"), "_us_build_record") + return {kw.arg: ast.unparse(kw.value) for kw in call.keywords}[keyword] + + +def _recorded_gate(builder, name: str) -> str: + """The ``_main`` local the build record carries as gate ``name``.""" + import ast + + [call] = _calls_named(_builder_function(builder, "_main"), "_us_build_record") + gates = next(kw.value for kw in call.keywords if kw.arg == "gates") + return { + ast.literal_eval(key): ast.unparse(value) + for key, value in zip(gates.keys, gates.values, strict=True) + }[name] + + def _installed_variable_metadata_index(builder): try: return builder.PolicyEngineUSVariableMetadataIndex() @@ -448,26 +507,19 @@ def test_delivery_gate_result_reaches_the_manifest_gates_block() -> None: """A release built with fences must be distinguishable from one whose bands passed enforcement: the delivery gate result (effective enforced set + fenced rows with adjudication text) must ride the manifest gates - block, and main() must thread it into _build_manifests.""" + block: main() records it for certification, which threads it into + _build_manifests.""" import ast builder = _load_builder_module() tree = ast.parse(Path(builder.__file__).read_text()) - main_fn = next( - n - for n in ast.walk(tree) - if isinstance(n, ast.FunctionDef) and n.name == "_main" + assert _recorded_gate(builder, "ssi_take_up_delivery_gate_result") == ( + "ssi_take_up_delivery_gate_result" ) - manifest_calls = [ - n - for n in ast.walk(main_fn) - if isinstance(n, ast.Call) and getattr(n.func, "id", "") == "_build_manifests" - ] - assert manifest_calls, "main() must call _build_manifests" - assert all( - any(kw.arg == "ssi_take_up_delivery_gate_result" for kw in call.keywords) - for call in manifest_calls - ), "every _build_manifests call must thread the delivery gate result" + assert any( + kw.arg == "ssi_take_up_delivery_gate_result" + for kw in _manifest_call(builder).keywords + ), "the _build_manifests call must thread the delivery gate result" build_fn = next( n for n in ast.walk(tree) @@ -2723,19 +2775,17 @@ def test_authenticated_pool_h5_consumers_use_one_returned_identity() -> None: for element in base_pool_assignments[0].targets[0].elts if isinstance(element, ast.Name) ] == ["pool_frame", "base_pool_receipt", "authenticated_pool_h5"] - manifest_calls = [ - node - for node in ast.walk(main_tree) - if isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id == "_build_manifests" - ] - assert len(manifest_calls) == 1 + assert _recorded(builder, "base_pool") == "base_pool_receipt" base_pool_keyword = next( - keyword for keyword in manifest_calls[0].keywords if keyword.arg == "base_pool" + keyword + for keyword in _manifest_call(builder).keywords + if keyword.arg == "base_pool" ) assert isinstance(base_pool_keyword.value, ast.Name) assert base_pool_keyword.value.id == "base_pool_receipt" + assert 'base_pool_receipt = inputs["base_pool"]' in inspect.getsource( + builder._certify_us_build + ) assert ( "authenticated_pool_h5.verified_digest(\n" ' consumer="builder base dataset identity"' @@ -2759,13 +2809,16 @@ def test_builder_reconciles_exact_k_count_before_any_release_write() -> None: source = inspect.getsource(builder._main) count_gate = source.index("assert_exact_k_realized_count(ladder_outcome") + # The build's last write is its record; the manifests are written only + # from it, by certification (microcosm#1585 item 11, PR 4a). for later_write in ( "_write_release_calibration_diagnostics(", "release_engine.write_dataset(", "_write_npz(", - "_build_manifests(", + "_write_us_build_record(", ): assert count_gate < source.index(later_write) + _manifest_call(builder) @pytest.mark.parametrize( @@ -2955,21 +3008,18 @@ def test_acs_predictor_join_precedes_all_six_archived_model_stages() -> None: ): assert join_position < source.index(stage) - manifest_calls = [ - node - for node in ast.walk(ast.parse(source)) - if isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id == "_build_manifests" - ] - assert len(manifest_calls) == 1 + assert _recorded(builder, "acs_predictor_join") == "acs_predictor_join_receipt" receipt_keyword = next( keyword - for keyword in manifest_calls[0].keywords + for keyword in _manifest_call(builder).keywords if keyword.arg == "acs_predictor_join" ) assert isinstance(receipt_keyword.value, ast.Name) assert receipt_keyword.value.id == "acs_predictor_join_receipt" + assert ( + 'acs_predictor_join_receipt = inputs["acs_predictor_join"]' + in inspect.getsource(builder._certify_us_build) + ) def test_fiscal_target_exclusion_receipt_replays_the_compile_into_source_coverage() -> ( @@ -2988,10 +3038,13 @@ def test_fiscal_target_exclusion_receipt_replays_the_compile_into_source_coverag builder = _load_builder_module() tree = ast.parse(inspect.getsource(builder._main)) + # The build compiles and records the receipt; certification writes the + # coverage payload from the record (microcosm#1585 item 11, PR 4a). + certify_tree = ast.parse(inspect.getsource(builder._certify_us_build)) calls = { name: [ node - for node in ast.walk(tree) + for node in ast.walk(certify_tree if name.startswith("write_") else tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name @@ -3003,6 +3056,13 @@ def test_fiscal_target_exclusion_receipt_replays_the_compile_into_source_coverag ) } assert [len(found) for found in calls.values()] == [1, 1, 1] + assert _recorded(builder, "fiscal_target_exclusion_receipt") == ( + "fiscal_target_exclusion_receipt" + ) + assert ( + 'fiscal_target_exclusion_receipt = source_coverage["fiscal_target_exclusion_receipt"]' + in inspect.getsource(builder._certify_us_build) + ) compile_call = calls["compile_us_fiscal_target_registry"][0] receipt_call = calls["us_fiscal_target_exclusion_receipt"][0] assert ast.dump(receipt_call.args[0]) == ast.dump(compile_call.args[0]) @@ -3022,7 +3082,7 @@ def test_fiscal_target_exclusion_receipt_replays_the_compile_into_source_coverag coverage_writes = [ node - for node in ast.walk(tree) + for node in ast.walk(certify_tree) if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Subscript) and isinstance(node.targets[0].value, ast.Name) @@ -3032,8 +3092,7 @@ def test_fiscal_target_exclusion_receipt_replays_the_compile_into_source_coverag ] assert len(coverage_writes) == 1 assert ( - receipt_call.lineno - < coverage_writes[0].lineno + coverage_writes[0].lineno < calls["write_us_source_coverage_diagnostics"][0].lineno ) @@ -6387,9 +6446,11 @@ def _assert_stored_input_abort(builder, *, captured, release_dir, mode) -> None: """How ``_main`` acts on each stored-input verdict (microcosm#1026). A refusal is a batched pre-export gate failure: in an otherwise green run - it is the raise's only line, the gate ran once on the export frame and no - H5 is written. A premise failure aborts after the write and before any - post-export scorer opens the file, with no manifest minted. + it is the raise's only line and the gate ran once on the export frame. + The build still writes its H5 and its record, which certification refuses + (microcosm#1585 item 11, PR 4a). A premise failure aborts right after the + write, before the record, so nothing can certify the build. Neither mints + a manifest. """ with pytest.raises(RuntimeError) as abort: @@ -6406,8 +6467,14 @@ def _assert_stored_input_abort(builder, *, captured, release_dir, mode) -> None: assert str(abort.value) == ( f"Release gates failed: {STORED_INPUT_REFUSAL_FIXTURE}" ) - assert "written_dataset" not in captured - assert "stored_input_post_write_check" not in captured + assert captured["stored_input_post_write_check"] == ( + captured["written_dataset"], + captured["written_dataset"], + ) + record = json.loads( + (release_dir.parent.parent / builder.US_BUILD_RECORD_FILENAME).read_text() + ) + assert record["terminal_gate_failures"] == [STORED_INPUT_REFUSAL_FIXTURE] assert evidence["stored_inputs"] == { "passed": False, "failures": [STORED_INPUT_REFUSAL_FIXTURE], @@ -6415,6 +6482,9 @@ def _assert_stored_input_abort(builder, *, captured, release_dir, mode) -> None: } else: assert str(abort.value) == STORED_INPUT_PREMISE_FIXTURE + assert not ( + release_dir.parent.parent / builder.US_BUILD_RECORD_FILENAME + ).exists() assert captured["stored_input_post_write_check"] == ( captured["written_dataset"], captured["written_dataset"], @@ -6765,6 +6835,19 @@ def record_certified_contract(directory, *, artifact_root=None): builder.main() + # The build stops at its record (microcosm#1585 item 11, PR 4a): its + # gate evidence is written, but nothing is publishable until + # certification runs the post-export checks and writes the manifests. + assert (out / builder.US_BUILD_RECORD_FILENAME).is_file() + # The scoring plan's dry run reaches the smoke on a recording seam, but + # the build never opens the scorer on the written H5. + assert "scorer_opened_on" not in captured + assert "holdout_scored" not in captured + assert not (release_dir / "build_manifest.json").exists() + assert not (release_dir / "release_manifest.json").exists() + assert (release_dir / "stored_inputs.json").is_file() + builder.certify_main([str(out)]) + assert validated == [] assert captured["terminal_gate_events"] == [ "input_coverage", @@ -6848,6 +6931,35 @@ def record_certified_contract(directory, *, artifact_root=None): for manifest in (build_manifest, release_manifest): assert manifest["release"] == builder.US_NATIONAL_RELEASE_ID assert manifest["build"] == release_id + # The manifests' provenance is the build's, from its record, not the + # certifying process's (microcosm#1585 item 11, PR 4a). + build_record = json.loads((out / builder.US_BUILD_RECORD_FILENAME).read_text()) + # The staging run the publisher checks is certification's. This build did + # not stage, so neither did its certification; the build's block rides + # inside. + assert build_manifest["staging"] == { + "enabled": False, + "reason": "the build did not stage (--no-staging)", + "build": {"enabled": False, "reason": "--no-staging"}, + } + assert release_manifest["built_at"] == build_record["built_at"] + assert build_manifest["created_at"] == build_record["built_at"] + assert build_manifest["runtime"] == build_record["runtime"] + assert build_manifest["code"]["git_commit"] == build_record["code"]["git_commit"] + assert ( + release_manifest["built_with_model_package"]["version"] + == build_record["runtime"]["policyengine-us"] + ) + # Every file the release manifest binds is one certification wrote, or + # one of the build's that its record pins by digest. + pinned = { + Path(pinned["path"]).name: pinned["sha256"] + for pinned in build_record["files"].values() + } + for key, artifact in release_manifest["artifacts"].items(): + if artifact["path"] in builder.US_CERTIFICATION_OUTPUT_FILES: + continue + assert pinned.get(artifact["path"]) == artifact["sha256"], key assert build_manifest["dataset"]["filename"] == "microcosm_us_2024.h5" assert release_manifest["default_datasets"] == {"national": "microcosm_us_2024"} if not skipped_smoke: @@ -7348,6 +7460,8 @@ def table(self, entity): ] if terminal_mode != "telemetry" and not prepared_pool: argv.append("--no-staging") + if terminal_mode == "merge": + argv.append("--audit-export-targets") argv += [ "--acs-person-zip", str(acs_person_zip), @@ -7399,6 +7513,7 @@ def table(self, entity): ] monkeypatch.setattr(sys, "argv", argv) monkeypatch.setattr(builder, "_git_dirty", lambda: False) + monkeypatch.setattr(builder, "_git_dirty_paths", lambda **_: []) def fake_sha256(path): if prepared_pool and Path(path) == pool_manifest: @@ -7467,6 +7582,26 @@ def complete(self): "_build_progress", lambda *args, **kwargs: live_telemetry, ) + if terminal_mode == "merge": + # An export audit that errors on a failed build joins its failures. + def failing_export_audit(path, result, target_specs, **kwargs): + raise AssertionError("export audit sentinel") + + monkeypatch.setattr( + builder, "_assert_export_matches_calibration", failing_export_audit + ) + if terminal_mode in {"merge", "crash", "target_frame_checkpoint"}: + # A build whose release gates fail still writes its H5 (microcosm#1585 + # item 11, PR 4a). These modes keep the real engine's gates and fake + # only its writer. + def fake_failed_write_dataset(self, frame, path, *, period): + captured["written_dataset"] = Path(path) + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_bytes(b"release h5") + + monkeypatch.setattr( + builder.PolicyEngineUSEngine, "write_dataset", fake_failed_write_dataset + ) if terminal_mode in { "integrity", "retirement", @@ -7622,7 +7757,10 @@ def fake_written_stored_input_check(path, pre_export): Path(path), captured.get("written_dataset"), ) - if terminal_mode == "stored_input_premise": + # A failed build's written file can fail its premise too + # (microcosm#1585 item 11, PR 4a): the merge run's failure joins its + # release gate failures. + if terminal_mode in {"stored_input_premise", "merge"}: return STORED_INPUT_PREMISE_FIXTURE return None @@ -9461,10 +9599,26 @@ def fake_release_gate_failures(*args, **kwargs): "zero_count": 0, }, } - # Artifact exclusion: the failed run leaves evidence, never artifacts. - # H5s land under the out root (not the release dir), so sweep the tree. - assert not list(out.rglob("*.h5")) + # A failed build writes its H5 for evaluation, and its record, which + # carries the failures; certification refuses it while they stand, so it + # never becomes a release (microcosm#1585 item 11, PR 4a). + assert captured["written_dataset"] == out / "artifacts" / builder.DATASET_FILENAME + failed_record = json.loads((out / builder.US_BUILD_RECORD_FILENAME).read_text()) + assert failed_record["terminal_gate_failures"] + assert message == "Release gates failed: " + "; ".join( + failed_record["terminal_gate_failures"] + ) + if terminal_mode == "merge": + # What the written file and the export audit fail after the H5 write + # joins the record's failures and the refusal, instead of replacing + # the refusal and leaving the H5 without a record. + assert failed_record["terminal_gate_failures"][-2:] == [ + STORED_INPUT_PREMISE_FIXTURE, + "Export audit failed: AssertionError: export audit sentinel", + ] assert not list(release_dir.glob("*manifest*")) + with pytest.raises(SystemExit, match="cannot be certified"): + builder.certify_main([str(out)]) if terminal_mode in qrf_tail_register_modes: assert captured["qrf_tail_register_seen"] == { "estate_income": "measured concentrated on another lineage", @@ -13540,9 +13694,15 @@ def keywords(function: str) -> dict[str, str]: assert keywords("_with_scf_education_debt_stage")["fit_path"] == ( "release_dir / US_SCF_EDUCATION_DEBT_FIT_FILENAME if dry_run is None else None" ) - assert keywords("_build_manifests")["scf_education_debt"] == ( - "args.scf_education_debt" - ) + # Certification reads the flag from the build record's settings. + assert "scf_education_debt" in builder.US_BUILD_RECORD_SETTINGS + assert ast.unparse( + next( + kw.value + for kw in _manifest_call(builder).keywords + if kw.arg == "scf_education_debt" + ) + ) == ("args.scf_education_debt") @pytest.mark.parametrize("readable", (True, False), ids=("available", "unavailable")) @@ -14150,18 +14310,16 @@ def test_gate_evidence_files_are_the_files_their_gates_write() -> None: ] assert len(solves) == 3 assert runtime_call.lineno < min(solves) - [manifest_call] = [ - node - for node in ast.walk(main_fn) - if isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id == "_build_manifests" - ] + manifest_call = _manifest_call(builder) keywords = { keyword.arg: ast.unparse(keyword.value) for keyword in manifest_call.keywords } assert keywords["export_input_mass_reference"] == "export_input_mass_reference" assert keywords["calibration_runtime"] == "calibration_runtime" + assert _recorded(builder, "export_input_mass_reference") == ( + "export_input_mass_reference" + ) + assert _recorded(builder, "calibration_runtime") == "calibration_runtime" assert keywords["skipped_gates"] == ( "('reform_coverage_smoke',) if args.skip_reform_coverage_smoke else ()" ) @@ -14186,15 +14344,11 @@ def test_fiscal_target_exclusion_receipt_writer_uses_the_manifest_key() -> None: import ast builder = _load_builder_module() - source = Path(builder.__file__).read_text() - main_fn = next( - node - for node in ast.walk(ast.parse(source)) - if isinstance(node, ast.FunctionDef) and node.name == "_main" - ) + # Certification writes the coverage payload (microcosm#1585 item 11, PR 4a). + certify_fn = _builder_function(builder, "_certify_us_build") coverage_keys = [ target.slice - for node in ast.walk(main_fn) + for node in ast.walk(certify_fn) if isinstance(node, ast.Assign) for target in node.targets if isinstance(target, ast.Subscript) @@ -16156,14 +16310,35 @@ def test_release_h5_write_sits_between_batched_raise_and_smoke() -> None: source = inspect.getsource(builder._main) tree = ast.parse(source) + # The smoke runs in certification, from the build record, which pins + # the written H5 by digest (microcosm#1585 item 11, PR 4a): the build + # writes the H5, then the record, and certification scores that file. + certify_smokes = _calls_named( + _builder_function(builder, "_certify_us_build"), "us_reform_coverage_smoke_gate" + ) + assert len(certify_smokes) == 1, certify_smokes + assert '"dataset": artifact_root / dataset_filename' in inspect.getsource( + builder._us_build_record + ) + # A certified-tier build records its batched refusal and raises it only + # once its record is written; certification refuses the record + # (microcosm#1585 item 11, PR 4a). The build never raises it before the + # write, so the H5 always exists for evaluation. batched_raises: list[int] = [] writes: list[int] = [] smokes: list[int] = [] + final_raises = [ + node.lineno + for node in ast.walk(tree) + if isinstance(node, ast.Raise) and ast.unparse(node) == "raise build_refusal" + ] for node in ast.walk(tree): - if isinstance(node, ast.Raise): - segment = ast.get_source_segment(source, node) or "" - if "terminal_gate_failures" in segment: - batched_raises.append(node.lineno) + if ( + isinstance(node, ast.Assign) + and ast.unparse(node.targets[0]) == "build_refusal" + and "terminal_gate_failures" in (ast.get_source_segment(source, node) or "") + ): + batched_raises.append(node.lineno) elif isinstance(node, ast.Call): func = node.func name = ( @@ -16173,20 +16348,26 @@ def test_release_h5_write_sits_between_batched_raise_and_smoke() -> None: ) if name == "write_dataset": writes.append(node.lineno) - elif name == "us_reform_coverage_smoke_gate": + elif name == "_write_us_build_record": smokes.append(node.lineno) - assert len(batched_raises) == 1, batched_raises + # The batched refusal is made before the H5 write and restated once the + # written file's checks have run, so it names what they fail too + # (microcosm#1585 item 11, PR 4a). + assert len(batched_raises) == 2, batched_raises + refusal, restated = sorted(batched_raises) assert len(writes) == 1, ( "main() must write the export H5 exactly once; the smoke gate and " f"release manifest read that file (microcosm#443). Found: {writes}" ) assert len(smokes) == 1, smokes - assert batched_raises[0] < writes[0] < smokes[0], ( - "Ordering contract violated: batched pre-export raise " - f"(line {batched_raises[0]}) < H5 write ({writes[0]}) < smoke " - f"({smokes[0]}) must hold so a gate-failed run never produces the " - "H5 and the smoke scores the just-written file." + assert len(final_raises) == 1, final_raises + assert refusal < writes[0] < restated < smokes[0] < final_raises[0], ( + "Ordering contract violated: batched pre-export refusal " + f"(line {refusal}) < H5 write ({writes[0]}) < restated refusal " + f"({restated}) < build record ({smokes[0]}) < its raise " + f"({final_raises[0]}) must hold so a gate-failed build leaves its H5 " + "and record and the smoke scores the just-written file." ) @@ -17697,10 +17878,13 @@ def _ancestor_if_tests(node: ast.AST) -> list[str]: assert "args.evidence_release" in _ancestor_if_tests(refusal) [sidecar] = _calls("_write_final_household_weight_evidence") assert record.lineno < refusal.lineno < sidecar.lineno + # The certified tier records the batched refusal and raises it once its + # record is written (microcosm#1585 item 11, PR 4a). batched_raise = next( node for node in ast.walk(main_fn) - if isinstance(node, ast.Raise) + if isinstance(node, ast.Assign) + and ast.unparse(node.targets[0]) == "build_refusal" and "Release gates failed: " in (ast.get_source_segment(source, node) or "") and node.lineno > sidecar.lineno ) @@ -18520,6 +18704,42 @@ def _ancestor_if_tests(node: ast.AST) -> list[str]: "gates must abort in both modes" ) + # The terminal set continues in certification, from the build record + # (microcosm#1585 item 11, PR 4a): every release-gate raise there comes + # after the accumulator, so each must be a conversion site. + assert _recorded(builder, "terminal_gate_failures") == "terminal_gate_failures" + assert _recorded(builder, "evidence_failure_owner_patterns") == ( + "evidence_failure_owner_patterns" + ) + certify_fn = _builder_function(builder, "_certify_us_build") + main_owner_checks = len( + [ + node + for node in ast.walk(main_fn) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "_evidence_known_failures" + ] + ) + main_fn = certify_fn + for parent in ast.walk(main_fn): + for child in ast.iter_child_nodes(parent): + parents[child] = parent + certify_raises = [ + node + for node in ast.walk(main_fn) + if isinstance(node, ast.Raise) + and "Release gates failed: " in (ast.get_source_segment(source, node) or "") + ] + assert certify_raises, "certification lost its release-gate raises" + for raise_node in certify_raises: + assert any( + test in certified_guard_tests for test in _ancestor_if_tests(raise_node) + ), ( + f"certification raise at line {raise_node.lineno} must sit under one " + f"of {sorted(certified_guard_tests)}" + ) + refusals = [ node for node in ast.walk(main_fn) @@ -18584,8 +18804,9 @@ def _ancestor_if_tests(node: ast.AST) -> list[str]: and isinstance(node.func, ast.Name) and node.func.id == "_evidence_known_failures" ] - assert len(owner_check_calls) == 5, ( - f"expected 5 owner-resolution sites in _main(), found {len(owner_check_calls)}" + assert (main_owner_checks, len(owner_check_calls)) == (1, 4), ( + "expected 5 owner-resolution sites, 1 in _main() and 4 in " + f"certification; found {main_owner_checks} and {len(owner_check_calls)}" ) @@ -19009,8 +19230,10 @@ def test_spm_composition_gate_rides_the_batched_pre_export_raise() -> None: ``test_release_h5_write_sits_between_batched_raise_and_smoke`` uses, and it pins the three properties the placement exists for: the gate is evaluated exactly once, its verdict joins the single batched pre-export failure list, - and that raise precedes both the export H5 write and the calibration NPZ - write. + and that refusal is recorded before both the export H5 write and the + calibration NPZ write. A refused build writes its H5 for evaluation and + raises once its record is written, so it is never certified + (microcosm#1585 item 11, PR 4a). """ import ast import inspect @@ -19025,10 +19248,12 @@ def test_spm_composition_gate_rides_the_batched_pre_export_raise() -> None: writes: list[int] = [] npz_writes: list[int] = [] for node in ast.walk(tree): - if isinstance(node, ast.Raise): - segment = ast.get_source_segment(source, node) or "" - if "terminal_gate_failures" in segment: - batched_raises.append(node.lineno) + if ( + isinstance(node, ast.Assign) + and ast.unparse(node.targets[0]) == "build_refusal" + and "terminal_gate_failures" in (ast.get_source_segment(source, node) or "") + ): + batched_raises.append(node.lineno) elif isinstance(node, ast.Call): func = node.func name = ( @@ -19055,14 +19280,18 @@ def test_spm_composition_gate_rides_the_batched_pre_export_raise() -> None: "the gate's verdict must join terminal_gate_failures, or a failing " f"export is exported anyway; found {extends}" ) - assert len(batched_raises) == 1, batched_raises + # The refusal is restated after the written file's checks, before the + # build record (microcosm#1585 item 11, PR 4a); the first is the + # batched pre-export refusal. + assert len(batched_raises) == 2, batched_raises + refusal = min(batched_raises) assert len(writes) == 1, writes assert len(npz_writes) == 1, npz_writes - assert gate_calls[0] < extends[0] < batched_raises[0] < writes[0] < npz_writes[0], ( + assert gate_calls[0] < extends[0] < refusal < writes[0] < npz_writes[0], ( "Ordering contract violated: the SPM composition gate " f"({gate_calls[0]}) must be evaluated and extended into the batch " - f"({extends[0]}) before the batched pre-export raise " - f"({batched_raises[0]}), which must precede the export H5 write " + f"({extends[0]}) before the batched pre-export refusal " + f"({refusal}), which must precede the export H5 write " f"({writes[0]}) and the calibration NPZ write ({npz_writes[0]})." ) @@ -19082,20 +19311,32 @@ def test_spm_composition_gate_is_not_guarded_by_skip_reform_validation() -> None source = inspect.getsource(builder._main) tree = ast.parse(source) - skipped_lines: set[int] = set() - for node in ast.walk(tree): - if not isinstance(node, ast.If): - continue - if "args.skip_reform_validation" not in ( - ast.get_source_segment(source, node.test) or "" - ): - continue - for branch in (*node.body, *node.orelse): - for inner in ast.walk(branch): - if hasattr(inner, "lineno"): - skipped_lines.add(inner.lineno) - - assert skipped_lines, "expected at least one --skip-reform-validation guard" + def guarded_lines(source: str) -> set[int]: + lines: set[int] = set() + for node in ast.walk(ast.parse(source)): + if not isinstance(node, ast.If): + continue + if "args.skip_reform_validation" not in ( + ast.get_source_segment(source, node.test) or "" + ): + continue + for branch in (*node.body, *node.orelse): + for inner in ast.walk(branch): + if hasattr(inner, "lineno"): + lines.add(inner.lineno) + return lines + + # Reform validation runs in certification (microcosm#1585 item 11, PR + # 4a), where the guard lives; the gate runs in the build. + certify_source = inspect.getsource(builder._certify_us_build) + assert guarded_lines(certify_source), ( + "expected at least one --skip-reform-validation guard" + ) + assert not _calls_named( + _builder_function(builder, "_certify_us_build"), + "_spm_composition_gate_failures", + ) + skipped_lines = guarded_lines(source) gate_calls = [ node.lineno for node in ast.walk(tree) @@ -19576,11 +19817,14 @@ def test_national_state_surface_source_coverage_excludes_dropped_cd_sources() -> def test_main_derives_source_coverage_aliases_from_the_target_surface() -> None: builder = _load_builder_module() main_source = inspect.getsource(builder._main) + certify_source = inspect.getsource(builder._certify_us_build) + assert _recorded(builder, "target_surface_selection") == "target_surface_selection" assert "_source_coverage_aliases(\n target_surface_selection\n )" in ( - main_source + certify_source ) assert '"soi-congressional-district-2022",' not in main_source + assert '"soi-congressional-district-2022",' not in certify_source @pytest.mark.parametrize( @@ -19723,3 +19967,903 @@ def went_on(*args, **kwargs): assert raised.value.reason == "command_not_found" assert builder._ACTIVE_EMITTER is None assert not output.exists() + + +# --------------------------------------------------------------------------- +# Build, then certify (microcosm#1585 item 11, PR 4a): the build ends with its +# record; certification runs from it. +# --------------------------------------------------------------------------- + + +def _build_record_fixture( + builder, + tmp_path: Path, + *, + terminal_gate_failures=(), + staging=None, + staging_settings=None, +) -> tuple[Path, dict]: + """A minimal finished build: the files certification reads, and its record. + + Its gate evidence is two of the build's files; the build wrote no ESI + premium evidence, and the smoke's is certification's to write. + """ + + release_root = tmp_path / "build" + release_dir = release_root / "releases" / builder.US_NATIONAL_RELEASE_ID + artifact_root = release_root / "artifacts" + release_dir.mkdir(parents=True) + artifact_root.mkdir() + (artifact_root / builder.DATASET_FILENAME).write_bytes(b"h5") + (artifact_root / builder.CALIBRATION_FILENAME).write_bytes(b"npz") + (release_dir / "calibration_diagnostics.json").write_text("{}") + (release_dir / "us_ssi_take_up.json").write_text('{"bands": []}') + (release_dir / "input_coverage.json").write_text('{"passed": true}') + (release_dir / "stored_inputs.json").write_text('{"passed": true}') + gate = builder.GateResult( + name="target_profile", + passed=False, + failures=("one target missing",), + details={"counts": [1, 2], "share": 0.5}, + ) + result = SimpleNamespace( + initial_loss=2.0, + final_loss=float("nan"), + fraction_within_10pct=0.75, + diagnostics=[ + SimpleNamespace(final_estimate=10.0, target=12.0), + SimpleNamespace(final_estimate=float("inf"), target=None), + ], + problem=SimpleNamespace( + targets=[SimpleNamespace(name="jct_a"), SimpleNamespace(name="jct_b")] + ), + ) + # The engine-bound consumers (the smoke, reform validation and + # demographics) skipped, so the scoring plan builds without an engine and + # records its batching. + args = SimpleNamespace( + **{name: name.startswith("skip_") for name in builder.US_BUILD_RECORD_SETTINGS}, + ) + args.maximum_microsim_batch_size = 2 + plan = builder._record_post_export_scoring_plan( + args, n_households=5, result=result, release_id="populace-us-2024-test-build" + ) + payload = builder._us_build_record( + release_id="populace-us-2024-test-build", + release_root=release_root, + release_dir=release_dir, + artifact_root=artifact_root, + dataset_key=builder.DATASET_KEY, + dataset_filename=builder.DATASET_FILENAME, + calibration_key=builder.CALIBRATION_KEY, + calibration_filename=builder.CALIBRATION_FILENAME, + commit="c" * 40, + built_at="2026-11-17T12:00:00+00:00", + # This environment's, so certify_main's tests certify in it. + runtime=builder._runtime_versions(), + args=args, + evidence_failure_owner_patterns=(("pattern", "PolicyEngine/microcosm#1"),), + terminal_gate_failures=terminal_gate_failures, + n_households=5, + result=result, + post_export_scoring_plan=plan, + release_gate_failures=["one target missing"], + registry=builder._RecordedTargetRegistry(version="v1", n_specs=3), + target_surface={"sha256": "s", "n_targets": 3}, + dropped={"dropped_target_names": []}, + gates={ + name: (gate if name == "target_profile_gate" else None) + for name in builder.US_BUILD_RECORD_GATES + }, + warm_start_calibration=None, + selection_source=None, + target_surface_selection=None, + ledger_artifact={"facts_sha256": "f"}, + default_dataset=None, + medicaid_enrollment_substitutions=(), + exact_k_ladder=None, + base_pool=None, + acs_predictor_join=None, + export_input_mass_reference=None, + calibration_runtime=None, + diagnostics_outcome=builder.DiagnosticsWriteSuccess( + status="available", + path=release_dir / "calibration_diagnostics.json", + schema_version=builder.CALIBRATION_DIAGNOSTICS_SCHEMA_VERSION, + sha256=builder._sha256(release_dir / "calibration_diagnostics.json"), + ), + scf_wealth_signal=None, + fiscal_target_sources=[], + congressional_district_vintage_crosswalk=None, + fiscal_target_exclusion_receipt={"rules": []}, + fsa_target_receipt=None, + take_up_participation={"programs": []}, + medicaid_take_up_diagnostics={"states": []}, + snap_state_take_up_diagnostics={"states": []}, + timing={"calibration_seconds": 1.0, "build_seconds": 3.0}, + staging=staging or {"enabled": False, "reason": "--no-staging"}, + staging_settings=staging_settings + or { + "no_staging": True, + "repo_id": None, + "prefix": "runs", + "upload_interval_seconds": 30.0, + }, + ) + path = builder._write_us_build_record(release_root, payload) + return path, payload + + +class _CertifyTelemetry: + """Certification's progress handle, as certify_main drives it.""" + + def __init__(self) -> None: + self.events: list[tuple[str, object]] = [] + + def stage(self, stage, **details) -> None: + self.events.append(("stage", stage)) + + def attach_artifact(self, name, path, **details) -> None: + self.events.append(("attach_artifact", name)) + + def complete(self) -> None: + self.events.append(("complete", None)) + + def fail(self, error) -> None: + self.events.append(("fail", error)) + + +def _stub_certify_telemetry(builder, monkeypatch) -> dict[str, object]: + """Start no emitter, and hand certification a recording progress handle.""" + + seen: dict[str, object] = {"telemetry": _CertifyTelemetry()} + + def start_emitter(**run): + seen["emitter_run"] = run + return SimpleNamespace(client=None, available=False) + + def certify_progress(args, *, record, run_id, emitter): + seen["progress_run_id"] = run_id + return seen["telemetry"] + + monkeypatch.setattr(builder, "start_local_telemetry_emitter_service", start_emitter) + monkeypatch.setattr(builder, "_certify_progress", certify_progress) + return seen + + +def test_the_build_record_carries_what_certification_reads(tmp_path: Path) -> None: + import math + + builder = _load_builder_module() + path, payload = _build_record_fixture(builder, tmp_path) + + assert path == tmp_path / "build" / builder.US_BUILD_RECORD_FILENAME + # Strict JSON: a non-finite loss is recorded by name, never as NaN. + text = path.read_text() + assert "NaN" not in text and "Infinity" not in text + assert ( + payload["files"]["dataset"]["path"] == "artifacts/" + builder.DATASET_FILENAME + ) + record = builder._read_us_build_record(path) + result = record.calibration_result() + assert result.initial_loss == 2.0 + assert math.isnan(result.final_loss) + # The in-sample consumers read the same estimates and targets the build's + # calibration result gave, non-finite values dropped. + assert builder._in_sample_estimates(result) == {"jct_a": 10.0} + assert builder._in_sample_targets(result) == {"jct_a": 12.0} + gates = record.gates() + assert gates["target_profile_gate"] == builder.GateResult( + name="target_profile", + passed=False, + failures=("one target missing",), + details={"counts": [1, 2], "share": 0.5}, + ) + assert gates["health_input_gate"] is None + assert len(record.registry_summary()) == 3 + assert ( + record.diagnostics_outcome().sha256 + == payload["manifest"]["diagnostics_outcome"]["sha256"] + ) + assert record.evidence_failure_owner_patterns == ( + ("pattern", "PolicyEngine/microcosm#1"), + ) + assert record.terminal_gate_failures == () + assert record.certify_args().maximum_microsim_batch_size == 2 + # The manifests' provenance rides the record: the time the build + # finished and the packages that built it. + assert record.built_at == "2026-11-17T12:00:00+00:00" + assert record.runtime == builder._runtime_versions() + # It pins every file of the build that certification reads, under its + # artifact key in the manifests, and no file certification writes. + assert set(payload["files"]) == { + "dataset", + "calibration_weights", + "calibration_diagnostics", + "us_ssi_take_up", + "input_coverage", + "stored_inputs", + } + + +def test_a_moved_build_certifies_in_place(tmp_path: Path) -> None: + """Paths are relative to the record, so a copied build directory reads.""" + builder = _load_builder_module() + path, _ = _build_record_fixture(builder, tmp_path) + moved = tmp_path / "elsewhere" + path.parent.rename(moved) + + record = builder._read_us_build_record(moved / builder.US_BUILD_RECORD_FILENAME) + + assert record.release_root == moved.resolve() + assert record.artifact_root == moved.resolve() / "artifacts" + + +@pytest.mark.parametrize( + "role", + [ + "dataset", + "calibration_weights", + "calibration_diagnostics", + "us_ssi_take_up", + "input_coverage", + "stored_inputs", + ], +) +def test_certification_refuses_a_build_whose_files_changed( + tmp_path: Path, role: str +) -> None: + builder = _load_builder_module() + path, payload = _build_record_fixture(builder, tmp_path) + (path.parent / payload["files"][role]["path"]).write_bytes(b"changed") + + with pytest.raises(RuntimeError, match=f"its {role} file .* hashes to"): + builder._read_us_build_record(path) + + +def test_certification_refuses_build_evidence_that_appeared_later( + tmp_path: Path, +) -> None: + """Gate evidence the build did not write would ride the manifests with no + digest the build recorded; the smoke's evidence is certification's own.""" + builder = _load_builder_module() + path, _ = _build_record_fixture(builder, tmp_path) + release_dir = path.parent / "releases" / builder.US_NATIONAL_RELEASE_ID + (release_dir / "reform_coverage_smoke.json").write_text('{"stale": true}') + builder._read_us_build_record(path) + + (release_dir / "esi_premiums.json").write_text('{"passed": true}') + with pytest.raises(RuntimeError, match=r"\(esi_premiums\) is not a file"): + builder._read_us_build_record(path) + + +def test_certification_refuses_a_record_it_cannot_read(tmp_path: Path) -> None: + builder = _load_builder_module() + path, payload = _build_record_fixture(builder, tmp_path) + path.write_text(json.dumps({**payload, "schema_version": 99})) + with pytest.raises(RuntimeError, match="schema 99"): + builder._read_us_build_record(path) + path.write_text(json.dumps({**payload, "kind": "another"})) + with pytest.raises(RuntimeError, match="not a US national build record"): + builder._read_us_build_record(path) + + +def test_certification_refuses_a_changed_scoring_plan(tmp_path: Path) -> None: + builder = _load_builder_module() + path, payload = _build_record_fixture(builder, tmp_path) + record = builder._read_us_build_record(path) + args = record.certify_args() + args.maximum_microsim_batch_size = 3 # another batching than the build's + + with pytest.raises(RuntimeError, match="differs from the one the build recorded"): + record.post_export_scoring_plan(args, result=record.calibration_result()) + + +def test_certify_main_refuses_another_commit_and_a_certified_build( + tmp_path: Path, monkeypatch +) -> None: + builder = _load_builder_module() + path, _ = _build_record_fixture(builder, tmp_path) + monkeypatch.setattr(builder, "_git_dirty_paths", lambda **_: []) + seen_telemetry = _stub_certify_telemetry(builder, monkeypatch) + certified: list[object] = [] + monkeypatch.setattr( + builder, + "_certify_us_build", + lambda record, *, telemetry: certified.append((record, telemetry)), + ) + + monkeypatch.setattr(builder, "_git_output", lambda *args: "d" * 40) + with pytest.raises(SystemExit, match="certify it from a checkout of that commit"): + builder.certify_main([str(path.parent)]) + + monkeypatch.setattr(builder, "_git_output", lambda *args: "c" * 40) + seen: list[Path] = [] + + def dirty(*, excluding): + seen.append(excluding) + return [" M tools/x.py", "?? stray.txt"] + + monkeypatch.setattr(builder, "_git_dirty_paths", dirty) + with pytest.raises(SystemExit, match=r"dirty git worktree: M tools/x.py; \?\?"): + builder.certify_main([str(path.parent)]) + # The build's own directory is left out of the check. + assert seen == [path.parent.resolve()] + + monkeypatch.setattr(builder, "_git_dirty_paths", lambda **_: []) + release_dir = path.parent / "releases" / builder.US_NATIONAL_RELEASE_ID + (release_dir / "release_manifest.json").write_text("{}") + with pytest.raises(RuntimeError, match="already carries a certified release"): + builder.certify_main([str(path.parent)]) + assert certified == [] + + # An earlier certification's outputs are cleared before a rerun. + (release_dir / "release_manifest.json").unlink() + (release_dir / "reform_coverage_smoke.json").write_text('{"stale": true}') + builder.certify_main([str(path.parent)]) + assert len(certified) == 1 + assert not (release_dir / "reform_coverage_smoke.json").exists() + # Certification runs in a telemetry run of its own, named after the + # build's, and hands its progress handle to the post-export stages. + assert seen_telemetry["emitter_run"] == { + "run_id": "populace-us-2024-test-build-certify", + "country_code": "US", + "pipeline": "us_fiscal_refresh", + "candidate_id": "populace-us-2024-test-build", + "release_id": "populace-us-2024-test-build", + "run_kind": "certification", + } + assert seen_telemetry["progress_run_id"] == "populace-us-2024-test-build-certify" + assert certified[0][1] is seen_telemetry["telemetry"] + + +def test_certify_main_refuses_a_build_whose_release_gates_failed( + tmp_path: Path, monkeypatch +) -> None: + """A failed build writes its H5 for evaluation, never a release + (microcosm#1585 item 11, PR 4a); an evidence-tier build's failures are + owned, so its record certifies into the evidence release.""" + builder = _load_builder_module() + path, payload = _build_record_fixture( + builder, tmp_path, terminal_gate_failures=["Input coverage failed: x"] + ) + monkeypatch.setattr(builder, "_git_dirty_paths", lambda **_: []) + monkeypatch.setattr(builder, "_git_output", lambda *args: "c" * 40) + _stub_certify_telemetry(builder, monkeypatch) + certified: list[object] = [] + monkeypatch.setattr( + builder, + "_certify_us_build", + lambda record, *, telemetry: certified.append(record), + ) + + with pytest.raises(SystemExit, match="1 release gate.*Input coverage failed: x"): + builder.certify_main([str(path.parent)]) + assert certified == [] + + payload["settings"]["evidence_release"] = True + builder._write_us_build_record(path.parent, payload) + builder.certify_main([str(path.parent)]) + assert len(certified) == 1 + + +def test_certify_main_refuses_a_build_that_wrote_failed_weight_evidence( + tmp_path: Path, monkeypatch +) -> None: + """Only a build whose release gates failed writes the #568 weight + evidence, so certification refuses its directory whatever its record says + (microcosm#1585 item 11, PR 4a).""" + builder = _load_builder_module() + path, _ = _build_record_fixture(builder, tmp_path) + monkeypatch.setattr(builder, "_git_dirty_paths", lambda **_: []) + monkeypatch.setattr(builder, "_git_output", lambda *args: "c" * 40) + _stub_certify_telemetry(builder, monkeypatch) + certified: list[object] = [] + monkeypatch.setattr( + builder, + "_certify_us_build", + lambda record, *, telemetry: certified.append(record), + ) + release_dir = path.parent / "releases" / builder.US_NATIONAL_RELEASE_ID + (release_dir / builder.FINAL_HOUSEHOLD_WEIGHTS_FILENAME).write_bytes(b"w") + + with pytest.raises(SystemExit, match="weight evidence a build writes when its"): + builder.certify_main([str(path.parent)]) + assert certified == [] + + +def test_certification_refuses_an_edited_record(tmp_path: Path) -> None: + """The record carries a digest of itself, so clearing a failed build's + failures by hand is refused; a record rewritten through the writer is the + deliberate path, until certification signs (PR 4b).""" + builder = _load_builder_module() + path, payload = _build_record_fixture( + builder, tmp_path, terminal_gate_failures=["Input coverage failed: x"] + ) + written = json.loads(path.read_text()) + assert written["record_sha256"] == builder._us_build_record_digest(written) + + edited = {**written, "terminal_gate_failures": []} + path.write_text(json.dumps(edited)) + with pytest.raises(RuntimeError, match="does not hash to the record_sha256"): + builder._read_us_build_record(path) + + builder._write_us_build_record(path.parent, payload) + assert builder._read_us_build_record(path).terminal_gate_failures == ( + "Input coverage failed: x", + ) + + +def test_certify_main_marks_its_staging_run_failed(tmp_path: Path, monkeypatch) -> None: + builder = _load_builder_module() + path, _ = _build_record_fixture(builder, tmp_path) + monkeypatch.setattr(builder, "_git_dirty_paths", lambda **_: []) + monkeypatch.setattr(builder, "_git_output", lambda *args: "c" * 40) + seen = _stub_certify_telemetry(builder, monkeypatch) + error = RuntimeError("Release gates failed: the smoke failed") + + def failing_certification(record, *, telemetry): + raise error + + monkeypatch.setattr(builder, "_certify_us_build", failing_certification) + with pytest.raises(RuntimeError, match="the smoke failed"): + builder.certify_main([str(path.parent)]) + assert seen["telemetry"].events == [("fail", error)] + + # A staging run that cannot open fails the emitter's run instead. + failed: list[BaseException] = [] + emitter = SimpleNamespace(client=object(), available=True, fail=failed.append) + monkeypatch.setattr( + builder, "start_local_telemetry_emitter_service", lambda **run: emitter + ) + unopened = OSError("staging directory is read-only") + + def unopenable(args, *, record, run_id, emitter): + raise unopened + + monkeypatch.setattr(builder, "_certify_progress", unopenable) + with pytest.raises(OSError, match="read-only"): + builder.certify_main([str(path.parent)]) + assert failed == [unopened] + + +def test_certification_stages_where_its_build_staged( + tmp_path: Path, monkeypatch +) -> None: + """Certification's own staging run carries the post-export verdicts and + the manifests; it follows the build's choice and destination, and + --no-staging opts it out, saying when the build staged.""" + builder = _load_builder_module() + emitter = SimpleNamespace(client=None, available=False) + + # A build that did not stage (--exact-k requires that) is certified + # without staging, with --no-staging or without it. + path, _ = _build_record_fixture(builder, tmp_path) + record = builder._read_us_build_record(path) + for argv in ([str(path.parent)], [str(path.parent), "--no-staging"]): + args = builder._certify_parser().parse_args(argv) + progress = builder._certify_progress( + args, record=record, run_id="b-certify", emitter=emitter + ) + assert progress.staging_bundle is None + assert ( + progress.staging_opt_out_reason == "the build did not stage (--no-staging)" + ) + assert builder._staging_manifest_block(progress) == { + "enabled": False, + "reason": "the build did not stage (--no-staging)", + } + + staged = tmp_path / "staged" + staged.mkdir() + path, _ = _build_record_fixture( + builder, + staged, + staging={ + "enabled": True, + "run_id": "build-run", + "repo_id": "policyengine/populace-us-staging", + "uploads_succeeded": 4, + }, + staging_settings={ + "no_staging": False, + "repo_id": "policyengine/populace-us-staging", + "prefix": "builds", + "upload_interval_seconds": 12.0, + }, + ) + record = builder._read_us_build_record(path) + # --no-staging opts certification out where its build staged too, as a + # build may opt out; the reason says the build staged. + opted_out = builder._certify_progress( + builder._certify_parser().parse_args([str(path.parent), "--no-staging"]), + record=record, + run_id="b-certify", + emitter=emitter, + ) + assert opted_out.staging_bundle is None + assert builder._staging_manifest_block(opted_out) == { + "enabled": False, + "reason": "--no-staging at certification; the build staged (run build-run)", + } + # A build that staged is certified into the same repository and prefix. + built: dict[str, object] = {} + + def build_progress(staging_args, **kwargs): + built.update(vars(staging_args), **kwargs) + return "progress" + + monkeypatch.setattr(builder, "_build_progress", build_progress) + assert ( + builder._certify_progress( + builder._certify_parser().parse_args([str(path.parent)]), + record=record, + run_id="b-certify", + emitter=emitter, + ) + == "progress" + ) + assert built == { + "no_staging": False, + "staging_run_id": "b-certify", + "staging_dir": None, + "staging_repo_id": "policyengine/populace-us-staging", + "staging_prefix": "builds", + "staging_upload_interval_seconds": 12.0, + "release_root": record.release_root, + "release_id": record.build, + "run_id": "b-certify", + "emitter": emitter, + "epoch_every": builder.CALIBRATION_EPOCH_EVERY, + } + + +def test_a_build_refuses_an_out_awaiting_certification(tmp_path: Path) -> None: + """A rerun into the --out of a build awaiting certification would + overwrite it; a failed build's --out may still be built into again.""" + builder = _load_builder_module() + root = tmp_path / "build" + builder._refuse_overwriting_a_build_awaiting_certification(root) + + path, payload = _build_record_fixture(builder, tmp_path) + with pytest.raises(RuntimeError, match="awaiting certification"): + builder._refuse_overwriting_a_build_awaiting_certification(root) + + payload["terminal_gate_failures"] = ["Input coverage failed: x"] + builder._write_us_build_record(root, payload) + builder._refuse_overwriting_a_build_awaiting_certification(root) + + # An evidence-tier build's owned failures certify, so it awaits too. + payload["settings"]["evidence_release"] = True + builder._write_us_build_record(root, payload) + with pytest.raises(RuntimeError, match="awaiting certification"): + builder._refuse_overwriting_a_build_awaiting_certification(root) + + path.write_text("not json") + with pytest.raises(RuntimeError, match="awaiting certification"): + builder._refuse_overwriting_a_build_awaiting_certification(root) + + +def test_certification_never_reopens_the_builds_staging_run(tmp_path: Path) -> None: + """A staging run's files start afresh when it opens, so a + --staging-run-id naming the build or its staging run is refused, before + certification touches the build (review of #1672).""" + builder = _load_builder_module() + path, _ = _build_record_fixture( + builder, + tmp_path, + staging={ + "enabled": True, + "run_id": "build-run", + "repo_id": "policyengine/populace-us-staging", + "uploads_succeeded": 4, + }, + staging_settings={ + "no_staging": False, + "repo_id": "policyengine/populace-us-staging", + "prefix": "builds", + "upload_interval_seconds": 12.0, + }, + ) + earlier = ( + path.parent + / "releases" + / builder.US_NATIONAL_RELEASE_ID + / "reform_validation.json" + ) + earlier.write_text('{"an earlier attempt": true}') + + for run_id in ("build-run", "populace-us-2024-test-build"): + with pytest.raises( + SystemExit, match=f"--staging-run-id {run_id} names build" + ) as refusal: + builder.certify_main([str(path.parent), "--staging-run-id", run_id]) + assert str(refusal.value).endswith("leave it out for build-run-certify.") + # Refused before a rerun removes an earlier attempt's outputs. + assert earlier.read_text() == '{"an earlier attempt": true}' + + +def test_the_build_record_digests_what_certification_reads_back( + tmp_path: Path, +) -> None: + """JSON writes every key as a string, so the build digests its record as + certification reads it back: a mapping keyed by integers, or by integers + and strings, still matches its digest (review of #1672).""" + builder = _load_builder_module() + path, payload = _build_record_fixture(builder, tmp_path) + payload["manifest"]["dropped"] = {2: "two", 10: "ten"} + payload["timing"] = {**payload["timing"], 3: 1.0} + + builder._write_us_build_record(path.parent, payload) + + record = builder._read_us_build_record(path) + assert record.manifest_inputs["dropped"] == {"2": "two", "10": "ten"} + assert record.timing["3"] == 1.0 + + +def test_a_rerun_into_an_out_awaiting_certification_stops_before_any_work( + tmp_path: Path, monkeypatch +) -> None: + """main refuses an --out holding a build awaiting certification with its + first refusals, before the base download, any output directory or the + gate shadow's files, and leaves the build as it was (review of #1672).""" + builder = _load_builder_module() + path, _ = _build_record_fixture(builder, tmp_path) + out = path.parent + + def files() -> dict[Path, bytes]: + return { + file.relative_to(out): file.read_bytes() + for file in out.rglob("*") + if file.is_file() + } + + before = files() + monkeypatch.setattr(builder, "_git_dirty", lambda: False) + monkeypatch.setattr( + builder, + "_download_base_h5", + lambda: pytest.fail("the rerun reached the base download"), + ) + + with pytest.raises( + RuntimeError, match="holds a finished build awaiting certification" + ): + builder.main( + [ + "--ledger-facts", + str(tmp_path / "facts.jsonl"), + "--out", + str(out), + "--release-id", + "populace-us-2024-rerun", + "--no-staging", + ] + ) + assert files() == before + + +def test_a_failed_build_holds_every_file_under_its_out(tmp_path: Path) -> None: + """A path belongs to the build whose record is nearest above it. That + build failed if its record carries failures that refuse it, or its + release directory holds the #568 weight evidence; an evidence-tier + build's owned failures certify (review of #1672).""" + builder = _load_builder_module() + path, payload = _build_record_fixture(builder, tmp_path) + record_path = path.resolve() + h5 = path.parent / payload["files"]["dataset"]["path"] + release_dir = path.parent / payload["layout"]["release_dir"] + + assert builder._failed_build_holding(h5) is None + assert builder._failed_build_holding(tmp_path / "elsewhere.h5") is None + + payload["terminal_gate_failures"] = ["Input coverage failed: x"] + builder._write_us_build_record(path.parent, payload) + failed = ( + f"build populace-us-2024-test-build ({record_path}), which failed 1 " + "release gate(s) when it was built" + ) + for held in (h5, release_dir, path.parent / "checkpoints" / "frame.h5"): + assert builder._failed_build_holding(held) == failed + + payload["settings"]["evidence_release"] = True + builder._write_us_build_record(path.parent, payload) + assert builder._failed_build_holding(h5) is None + + (release_dir / builder.FINAL_HOUSEHOLD_WEIGHTS_FILENAME).write_bytes(b"w") + assert builder._failed_build_holding(h5) == ( + f"build populace-us-2024-test-build ({record_path}), whose release " + "directory holds the weight evidence a build writes when its release " + f"gates fail ({builder.FINAL_HOUSEHOLD_WEIGHTS_FILENAME}; microcosm#568)" + ) + + +@pytest.mark.parametrize( + "flag", ["--input-mass-reference-h5", "--export-input-mass-reference-h5"] +) +def test_a_failed_build_is_no_input_mass_reference( + tmp_path: Path, capsys, flag: str +) -> None: + """An input-mass reference is the certified yardstick a gate judges the + build against, so a failed build's H5 is refused there and a green + build's is read as before (review of #1672).""" + builder = _load_builder_module() + path, payload = _build_record_fixture(builder, tmp_path) + file = path.parent / payload["files"]["dataset"]["path"] + argv = [ + "--ledger-facts", + str(tmp_path / "facts.jsonl"), + "--out", + str(tmp_path / "next"), + "--no-staging", + flag, + str(file), + ] + + assert getattr(builder._parse_args(argv), flag[2:].replace("-", "_")) == file + + payload["terminal_gate_failures"] = ["Input coverage failed: x"] + builder._write_us_build_record(path.parent, payload) + with pytest.raises(SystemExit): + builder._parse_args(argv) + assert ( + f"{flag} {file} belongs to build populace-us-2024-test-build" + in capsys.readouterr().err + ) + + +@pytest.mark.parametrize( + ("flag", "role"), + [ + ("--base-h5", "dataset"), + ("--selection-source-h5", "dataset"), + ("--warm-start-calibration-npz", "calibration_weights"), + ], +) +def test_a_failed_build_may_start_a_later_build( + tmp_path: Path, flag: str, role: str +) -> None: + """A failed build's H5 and calibration weights may start a later build, as + its base, selection source or warm start, which cuts a rerun's time while + its data is fixed: that build's own gates judge its result.""" + builder = _load_builder_module() + path, payload = _build_record_fixture( + builder, tmp_path, terminal_gate_failures=["Input coverage failed: x"] + ) + file = path.parent / payload["files"][role]["path"] + assert builder._failed_build_holding(file) is not None + argv = [ + "--ledger-facts", + str(tmp_path / "facts.jsonl"), + "--out", + str(tmp_path / "next"), + "--no-staging", + flag, + str(file), + ] + + assert getattr(builder._parse_args(argv), flag[2:].replace("-", "_")) == file + + +def test_a_record_of_an_earlier_schema_names_the_code_that_built_it( + tmp_path: Path, +) -> None: + """A record an earlier commit wrote carries no digest of itself. It is + refused as a record of another schema, not as an edited one, and so is a + rerun into its --out, both naming the code that can certify it; a failed + one may still be built over.""" + builder = _load_builder_module() + path, _ = _build_record_fixture(builder, tmp_path) + current = builder.US_BUILD_RECORD_SCHEMA_VERSION + older = { + key: value + for key, value in json.loads(path.read_text()).items() + if key != "record_sha256" + } + older["schema_version"] = current - 1 + path.write_text(json.dumps(older)) + advice = f"Certify the build with the code it was built with ({'c' * 40})" + + with pytest.raises(RuntimeError) as refused: + builder._read_us_build_record(path) + assert ( + f"has build record schema {current - 1}; this tool reads schema {current}. " + f"{advice}, or build it again into a new --out." + ) in str(refused.value) + assert "record_sha256" not in str(refused.value) + + with pytest.raises(RuntimeError) as refused: + builder._refuse_overwriting_a_build_awaiting_certification(path.parent) + assert ( + f"awaiting certification ({builder.US_BUILD_RECORD_FILENAME}) with build " + f"record schema {current - 1}, which this tool does not read. {advice}, " + "or choose a new --out for this build." + ) in str(refused.value) + + older["terminal_gate_failures"] = ["Input coverage failed: x"] + path.write_text(json.dumps(older)) + builder._refuse_overwriting_a_build_awaiting_certification(path.parent) + assert builder._certify_with_its_own_code({}) == ( + "Certify the build with the code it was built with" + ) + + +def test_certify_main_refuses_packages_other_than_the_builds( + tmp_path: Path, monkeypatch +) -> None: + """The manifests name the packages that built the H5, so its checks must + run on them: a moved build certifies only where they are installed.""" + builder = _load_builder_module() + path, payload = _build_record_fixture(builder, tmp_path) + monkeypatch.setattr(builder, "_git_dirty_paths", lambda **_: []) + monkeypatch.setattr(builder, "_git_output", lambda *args: "c" * 40) + _stub_certify_telemetry(builder, monkeypatch) + certified: list[object] = [] + monkeypatch.setattr( + builder, + "_certify_us_build", + lambda record, *, telemetry: certified.append(record), + ) + built_with = payload["runtime"]["policyengine-us"] + monkeypatch.setattr( + builder, + "_runtime_versions", + lambda: {**payload["runtime"], "policyengine-us": "9.9.9"}, + ) + + with pytest.raises( + SystemExit, + match=( + rf"built with policyengine-us {re.escape(built_with)}; certify it " + r"with those packages, not policyengine-us 9\.9\.9" + ), + ): + builder.certify_main([str(path.parent)]) + assert certified == [] + + +def test_the_dirty_check_leaves_out_a_build_inside_the_work_tree( + tmp_path: Path, monkeypatch +) -> None: + """An unignored in-repo --out leaves the build's files untracked; only + the code certification runs is checked, not the build it reads.""" + builder = _load_builder_module() + repo = tmp_path / "repo" + repo.mkdir() + # No user or system git configuration (an untracked-files setting, say) + # reaches the check. + monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + + def git(*args: str) -> None: + subprocess.run( + ["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], + cwd=repo, + check=True, + capture_output=True, + ) + + git("init", "-q") + (repo / "tracked.txt").write_text("a\n") + git("add", "tracked.txt") + git("commit", "-qm", "init") + build = repo / "build [1]" + (build / "releases").mkdir(parents=True) + (build / builder.US_BUILD_RECORD_FILENAME).write_text("{}") + (repo / "sub").mkdir() + monkeypatch.chdir(repo / "sub") + + assert builder._git_dirty_paths(excluding=build) == [] + # A build directory outside the work tree leaves nothing out. + assert builder._git_dirty_paths(excluding=tmp_path / "elsewhere") == [ + '?? "build [1]/"' + ] + # Nor does one that is the work tree itself. + assert builder._git_dirty_paths(excluding=repo) == ['?? "build [1]/"'] + + (repo / "tracked.txt").write_text("b\n") + (repo / "stray.txt").write_text("u\n") + assert builder._git_dirty_paths(excluding=build) == [ + " M tracked.txt", + "?? stray.txt", + ] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py index c24d8d8234..0f3e5b3d04 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py @@ -556,6 +556,75 @@ def test_the_target_surface_resolves_from_a_build_folder_release_manifest( assert probe_tool.resolve_target_surface(None, None, identity)["mode"] == "full" +def test_the_target_surface_resolves_from_an_uncertified_builds_record( + probe_tool, tmp_path +) -> None: + """A build not yet certified has no manifest; the probe reads its + selection from the build_record.json two levels above its release + directory (microcosm#1585 item 11, PR 4a). A flag still wins.""" + selection = { + "mode": "national_state", + "dropped_congressional_district_targets": 27_148, + } + release_dir = tmp_path / "out" / "releases" / "microcosm-us-2024-national" + release_dir.mkdir(parents=True) + assert probe_tool.reference_build_record(release_dir) is None + record_path = tmp_path / "out" / "build_record.json" + record_path.write_text( + json.dumps({"manifest": {"target_surface_selection": selection}}) + ) + assert probe_tool.reference_build_record(release_dir) == record_path.resolve() + record = json.loads(record_path.read_text()) + + assert probe_tool.resolve_target_surface(None, None, None, record) == { + "mode": "national_state", + "dropped_congressional_district_targets": 27_148, + "source": "reference build_record.json manifest.target_surface_selection", + } + full = {"manifest": {"target_surface_selection": None}} + assert probe_tool.resolve_target_surface(None, None, None, full)["mode"] == "full" + assert ( + probe_tool.resolve_target_surface("full", None, None, record)["source"] + == "--target-surface" + ) + + +def test_a_failed_build_is_no_reference(probe_tool, builder, tmp_path, capsys) -> None: + """A failed build keeps its H5 to be evaluated, which the probe may score + as --export, but its release directory is refused as the reference + (review of #1672).""" + out = tmp_path / "out" + release_dir = out / "releases" / "microcosm-us-2024-national" + release_dir.mkdir(parents=True) + (out / "build_record.json").write_text( + json.dumps( + { + "kind": builder.US_BUILD_RECORD_KIND, + "build": "populace-us-2024-failed", + "layout": {"release_dir": "releases/microcosm-us-2024-national"}, + "settings": {"evidence_release": False}, + "terminal_gate_failures": ["Input coverage failed: x"], + } + ) + ) + argv = [ + "--export", + str(tmp_path / "sample.h5"), + "--out", + str(tmp_path / "probe"), + "--reference-release-dir", + str(release_dir), + ] + + with pytest.raises(SystemExit): + probe_tool.main(argv) + assert ( + f"--reference-release-dir {release_dir} belongs to build " + "populace-us-2024-failed" in capsys.readouterr().err + ) + assert not (tmp_path / "probe").exists() + + def test_census_with_a_receipt_is_refused( probe_tool, builder, fake_reforms, chain, tmp_path ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index c45b8db3a4..deeeb97a7f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py @@ -808,11 +808,14 @@ def fake_write_calibration_diagnostics( def test_main_and_writers_never_build_a_whole_pool_simulation(builder) -> None: - """(i) Neither _main nor the reform-validation and demographics writers - call default_simulate_factory or construct a Microsimulation, and _main - feeds the smoke from the batched scorer.""" + """(i) Neither _main, certification, nor the reform-validation and + demographics writers call default_simulate_factory or construct a + Microsimulation, and certification feeds the smoke from the batched + scorer. Certification (``_certify_us_build``) runs from the build record + ``_main`` writes after the H5 (microcosm#1585 item 11, PR 4a).""" for name in ( "_main", + "_certify_us_build", "_write_reform_validation", "_write_demographics", "_write_ssi_social_security_holdout", @@ -824,13 +827,15 @@ def test_main_and_writers_never_build_a_whole_pool_simulation(builder) -> None: assert "Microsimulation" not in called, name assert "USSingleYearDataset" not in called, name - source, tree = _function_source(builder, "_main") + main_source, main_tree = _function_source(builder, "_main") + source, tree = _function_source(builder, "_certify_us_build") calls = [node for node in ast.walk(tree) if isinstance(node, ast.Call)] + main_calls = [node for node in ast.walk(main_tree) if isinstance(node, ast.Call)] - def calls_to(name: str) -> list[ast.Call]: + def calls_to(name: str, among=None) -> list[ast.Call]: return [ call - for call in calls + for call in (calls if among is None else among) if name in (getattr(call.func, "id", None), getattr(call.func, "attr", None)) ] @@ -839,12 +844,16 @@ def calls_to(name: str) -> list[ast.Call]: assert [ast.unparse(call) for call in calls_to("_open_post_export_scorer")] == [ "_open_post_export_scorer(post_export_scoring_plan, dataset_path)" ] - # It opens the file this run has just written, never a previous run's - # bytes at the same path (microcosm#443), and before the smoke scores. - (write_call,) = calls_to("write_dataset") + # It opens the file the build wrote, which the record pins by digest + # (never a previous run's bytes at the same path, microcosm#443), and + # before the smoke scores. The record is written after the H5. + (write_call,) = calls_to("write_dataset", main_calls) + (record_call,) = calls_to("_write_us_build_record", main_calls) + assert write_call.lineno < record_call.lineno + assert not calls_to("_open_post_export_scorer", main_calls) (open_call,) = calls_to("_open_post_export_scorer") (smoke_gate_call,) = calls_to("us_reform_coverage_smoke_gate") - assert write_call.lineno < open_call.lineno < smoke_gate_call.lineno + assert open_call.lineno < smoke_gate_call.lineno # The smoke's served baseline is its own recorded plan, with that plan's # reform pass count for progress (#1556), and the gate reads that # consumer's seam. @@ -905,7 +914,7 @@ def calls_to(name: str) -> list[ast.Call]: assert demographics_call.lineno < sha_assignments[0].lineno < manifest_call.lineno diagnostics_call = next( node - for node in ast.walk(tree) + for node in ast.walk(main_tree) if isinstance(node, ast.Call) and getattr(node.func, "id", None) == "_write_release_calibration_diagnostics" ) @@ -944,14 +953,23 @@ def calls_to(name: str) -> list[ast.Call]: ] == "post_export_scoring" # The plan is recorded (never raised) before the diagnostics, and its own # failure joins the terminal batch ahead of the export write. - recorded = source.index( + recorded = main_source.index( "post_export_scoring_plan = _record_post_export_scoring_plan(" ) - joined = source.index( + joined = main_source.index( "terminal_gate_failures.extend(post_export_scoring_plan.terminal_failures())" ) - assert recorded < source.index("_write_release_calibration_diagnostics(") < joined - assert joined < source.index("release_engine.write_dataset(") + assert ( + recorded < main_source.index("_write_release_calibration_diagnostics(") < joined + ) + assert joined < main_source.index("release_engine.write_dataset(") + # Certification scores the plan the build recorded: it rebuilds it and + # refuses one that differs (microcosm#1585 item 11, PR 4a). + assert "post_export_scoring_plan=post_export_scoring_plan" in main_source + assert ( + "post_export_scoring_plan = record.post_export_scoring_plan(args, result=result)" + in source + ) def test_main_opens_the_scorer_its_plan_recorded( @@ -1451,7 +1469,7 @@ def test_scored_sha_is_bound_at_load_and_checked_by_the_manifest( with pytest.raises(ValueError, match="not opened on this scorer"): scorer.finish_consumer(other.open_consumer("fixture", ())) - _, tree = _function_source(builder, "_main") + _, tree = _function_source(builder, "_certify_us_build") manifest_call = next( node for node in ast.walk(tree) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_stored_input_register.py b/packages/microcosm-build/tests/engine_free/us/test_us_stored_input_register.py index 4b636cac9a..0990f3f0ec 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_stored_input_register.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_stored_input_register.py @@ -371,9 +371,12 @@ def test_main_runs_the_gate_in_the_batch_and_checks_the_written_h5(builder): failures join ``terminal_gate_failures`` unconditionally (statements of ``_main``'s own body, under no ``if``, loop or ``try``), before the batched raise's ``if terminal_gate_failures:`` block. The H5 write comes - after that block; the post-write check and its unconditional - ``raise RuntimeError`` come right after the write and before the - post-export scorer opens. The behaviour of both aborts is pinned through + after that block; the post-write check and its ``raise RuntimeError`` + (on a green build; a failed build records the failure with its release + gate failures) come right after the write and before the build record, + the only way into certification, where the post-export scorer opens + (microcosm#1585 item 11, PR 4a). The behaviour of both aborts is + pinned through ``_main`` itself by the ``stored_input_*`` modes of ``test_main_writes_diagnostics_before_post_calibration_gate_failure``.""" @@ -470,12 +473,25 @@ def site_call(value, name): ), "post-write abort", ) - assert len(body[abort].body) == 1 and not body[abort].orelse - assert ast.unparse(body[abort].body[0]) == (f"raise RuntimeError({premise_name})") + # A green build aborts on the written file's premise; a build whose + # release gates failed records it with them instead, so its record is + # still written and the refusal names it (microcosm#1585 item 11, PR 4a). + assert not body[abort].orelse + assert [ast.unparse(statement) for statement in body[abort].body] == [ + f"if build_refusal is None:\n raise RuntimeError({premise_name})", + f"terminal_gate_failures.append({premise_name})", + ] scorer = position( - lambda node: assigned_from(node, "_open_post_export_scorer"), - "post-export scorer", + lambda node: assigned_from(node, "_write_us_build_record"), + "build record", + ) + assert not any(calls(node, "_open_post_export_scorer") for node in body) + certify = next( + node + for node in ast.walk(tree) + if isinstance(node, ast.FunctionDef) and node.name == "_certify_us_build" ) + assert calls(certify, "_open_post_export_scorer") assert gate < joined < batched < write < premise < abort < scorer assert premise == write + 1 and abort == premise + 1 diff --git a/tools/build_us_exact_k_ladder_release.py b/tools/build_us_exact_k_ladder_release.py index 65cf4c5852..fadfcb3e34 100644 --- a/tools/build_us_exact_k_ladder_release.py +++ b/tools/build_us_exact_k_ladder_release.py @@ -472,11 +472,12 @@ def launch( out: Path, release_builder: Callable[[Sequence[str] | None], object] = fiscal_release.main, ) -> dict[str, object]: - """Validate pins, run the house release path, and write a publish receipt. + """Validate pins, build through the house release path, and write a receipt. - The receipt names the build and its release, the national one, and - carries the commands that publish the build and make it current; the - launcher runs neither. + The release tool builds and stops (microcosm#1585 item 11, PR 4a), so the + receipt names the build and its release, the national one, and carries + the command that certifies the build, then the commands that publish it + and make it current. The launcher runs none of them. """ config = _read_config(config_path) @@ -506,8 +507,11 @@ def launch( "artifact_root": str(artifact_root), "k": k, "seed": config.seed, - # Publishing lists the build in the release; promoting, after review, - # makes it current. The launcher does neither. + # Certifying runs the release's post-export checks and writes the + # manifests; publishing then lists the build in the release, and + # promoting, after review, makes it current. The launcher does none. + "certified": False, + "certify_command": fiscal_release._certify_command(resolved_out), "automatic_publish": False, "makes_current": False, "publish_command": commands["publish_command"], diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index aad13fd49c..26a8f0318a 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -9,11 +9,18 @@ (microcosm#1570): a certified or exact-k build of the national release, ``microcosm-us-2024-national``, or an evidence-tier build of the evidence release, ``microcosm-us-2024-evidence``. The release directory is -``/releases//``; both manifests name the release and the build -(the ``populace-us-2024-…`` build ID) in the build-folder layout; the run -checks the directory against its tier's release contract and prints the -``microcosm-publish-release-build`` commands that publish the build into its -own folder of the release and then make it the release's current build. +``/releases//``. + +The run builds and stops (microcosm#1585 item 11, PR 4a): once the H5, the +calibration weights, the diagnostics and the build's gate evidence are +written, it writes ``/build_record.json`` and prints the command that +certifies the build, so the build can be evaluated first. Nothing it writes +is publishable. ``tools/certify_us_national_build.py`` certifies it: the +release's post-export checks on the written H5, then both manifests, which +name the release and the build (the ``populace-us-2024-…`` build ID) in the +build-folder layout, and the ``microcosm-publish-release-build`` commands +that publish the build into its own folder of the release and then make it +the release's current build. """ from __future__ import annotations @@ -47,6 +54,7 @@ import math import platform import re +import shlex import shutil import subprocess import sys @@ -57,7 +65,7 @@ from contextlib import contextmanager, nullcontext from datetime import UTC, datetime from pathlib import Path -from types import MethodType +from types import MethodType, SimpleNamespace from typing import Any import numpy as np @@ -470,6 +478,7 @@ ) from microcosm.diagnostics import ( CALIBRATION_DIAGNOSTICS_SCHEMA_VERSION, + DiagnosticsWriteFailure, DiagnosticsWriteOutcome, DiagnosticsWriteSuccess, ) @@ -2245,6 +2254,14 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: ) except ValueError as error: parser.error(str(error)) + for attribute, flag in _REFERENCE_H5_OPTIONS: + path = getattr(args, attribute) + failed = None if path is None else _failed_build_holding(path) + if failed is not None: + parser.error( + f"{flag} {path} belongs to {failed}. A failed build is never " + "the reference a gate judges this build against." + ) return args @@ -2620,6 +2637,137 @@ def _refuse_certified_release_dir_reuse(release_dir: Path) -> None: ) +def _refuse_overwriting_a_build_awaiting_certification(release_root: Path) -> None: + """Fail loud when --out holds a finished build that awaits certification. + + A build stops at its record (microcosm#1585 item 11, PR 4a), so its + directory carries no release manifest until certification writes one, + and :func:`_refuse_certified_release_dir_reuse` would let a rerun + overwrite it. A build whose release gates failed can never be certified, + so a rerun into its --out still replaces it, as it did before builds + wrote a record. A record of another schema is refused the same way, and + the refusal names the code that can certify it. + """ + + path = Path(release_root) / US_BUILD_RECORD_FILENAME + if not path.is_file(): + return + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + payload = None + if _recorded_release_gate_failures(payload): + return + awaiting = ( + f"{release_root} holds a finished build awaiting certification " + f"({US_BUILD_RECORD_FILENAME})" + ) + if ( + isinstance(payload, dict) + and payload.get("schema_version") != US_BUILD_RECORD_SCHEMA_VERSION + ): + raise RuntimeError( + f"{awaiting} with build record schema " + f"{payload.get('schema_version')!r}, which this tool does not read. " + f"{_certify_with_its_own_code(payload)}, or choose a new --out for " + "this build." + ) + raise RuntimeError( + f"{awaiting}. Certify it with {_certify_command(release_root)}, or " + "choose a new --out for this build." + ) + + +def _recorded_release_gate_failures(payload: object) -> list[str]: + """The release-gate failures in a build record that refuse its build. + + A build whose release gates fail records them and is never certified + (microcosm#1585 item 11, PR 4a). An evidence-tier build records the + failures its owners own and is certified with them, so none of its + failures refuse it. A payload that is not a build record has none. + """ + + try: + failures = payload["terminal_gate_failures"] + evidence_release = payload["settings"]["evidence_release"] + except (KeyError, TypeError): + return [] + if evidence_release or not isinstance(failures, list): + return [] + return [str(line) for line in failures] + + +#: The #568 weight evidence. Only a build whose release gates fail writes it, +#: and a green build removes any it finds. +US_FAILED_BUILD_WEIGHT_EVIDENCE = ( + FINAL_HOUSEHOLD_WEIGHTS_FILENAME, + FINAL_HOUSEHOLD_WEIGHT_IDS_FILENAME, + FINAL_HOUSEHOLD_WEIGHTS_METADATA_FILENAME, +) + +#: The options whose H5 is the reference a gate judges this build against. +#: A failed build's files are refused there. As a starting point (--base-h5, +#: --selection-source-h5, --warm-start-calibration-npz) they are allowed: +#: they can cut a rerun's time while its data is fixed, and the build's own +#: gates judge its result. +_REFERENCE_H5_OPTIONS = ( + ("input_mass_reference_h5", "--input-mass-reference-h5"), + ("export_input_mass_reference_h5", "--export-input-mass-reference-h5"), +) + + +def _failed_build_holding(path: Path) -> str | None: + """The build whose release gates failed that ``path`` belongs to, or None. + + A build whose release gates fail still writes its H5, its calibration + weights and its record, so it can be evaluated (microcosm#1585 item 11, + PR 4a), and its files may start a later build. No gate judges against + it: a later build refuses its files as an input-mass reference, and the + post-export probe refuses its release directory as the reference. A + path belongs to the build whose record sits in the nearest directory + above it. That build failed if its record carries failures that refuse + it, or if its release directory holds the #568 weight evidence. Like the + record's digest, this stops a mistake, not an edit, until certification + signs (PR 4b). + """ + + target = Path(path).resolve() + for release_root in target.parents: + record_path = release_root / US_BUILD_RECORD_FILENAME + if not record_path.is_file(): + continue + try: + payload = json.loads(record_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if not isinstance(payload, dict) or payload.get("kind") != US_BUILD_RECORD_KIND: + continue + build = f"build {payload.get('build')} ({record_path})" + failures = _recorded_release_gate_failures(payload) + if failures: + return ( + f"{build}, which failed {len(failures)} release gate(s) when it " + "was built" + ) + try: + release_dir = release_root / payload["layout"]["release_dir"] + except (KeyError, TypeError): + return None + evidence = [ + name + for name in US_FAILED_BUILD_WEIGHT_EVIDENCE + if (release_dir / name).exists() + ] + if evidence: + return ( + f"{build}, whose release directory holds the weight evidence a " + f"build writes when its release gates fail ({', '.join(evidence)}; " + "microcosm#568)" + ) + return None + return None + + #: Files the release manifest declares whenever they exist, written only by #: a run that does not skip their check, with the option that skips it. _SKIPPABLE_CHECK_FILES = ( @@ -3403,6 +3551,31 @@ def _git_dirty() -> bool: return bool(_git_output("status", "--porcelain")) +def _git_dirty_paths(*, excluding: Path) -> list[str]: + """The work tree's ``git status --porcelain`` lines, leaving out ``excluding``. + + Certification checks the code it runs, not the build it reads: a build + whose ``--out`` lies inside the work tree, unignored, would otherwise make + its own certification refuse it, since the build's files are untracked + there. The build directory is left out only when it lies strictly inside + the work tree; its files are the record's to check, by digest. + """ + + top = Path(_git_output("rev-parse", "--show-toplevel")).resolve() + pathspec = ["."] + try: + inside = Path(excluding).resolve().relative_to(top) + except ValueError: + inside = None + if inside is not None and inside != Path("."): + pathspec.append(f":(exclude,literal){inside.as_posix()}") + # Unstripped, so each line keeps its two status columns. + status = subprocess.check_output( + ("git", "-C", str(top), "status", "--porcelain", "--", *pathspec), text=True + ) + return [line for line in status.splitlines() if line] + + def _download_base_h5() -> Path: """The base a run without ``--base-h5`` starts from: the US national release's current build, SHA-verified by the loader (microcosm#1570). @@ -11136,6 +11309,10 @@ def _build_manifests( diagnostics_outcome: DiagnosticsWriteOutcome | None = None, scf_wealth_signal: Mapping[str, object] | None = None, scf_education_debt: bool = False, + release_gate_failures: Sequence[str] | None = None, + git_commit: str | None = None, + built_at: str | None = None, + runtime_versions: Mapping[str, str] | None = None, ) -> None: dataset_path = artifact_root / dataset_filename calibration_path = artifact_root / calibration_filename @@ -11216,29 +11393,42 @@ def _build_manifests( coverage_path, coverage_sha ), } - gate_failures = _release_gate_failures( - result, - dropped, - target_profile_gate, - health_input_gate, - base_population_gate, - incumbent_diagnostics, - immigration_gate, - input_mass_reference_gate, - degenerate_input_gate, - ecps_parity_gate=ecps_parity_gate, - hours_worked_gate=hours_worked_gate, - snap_take_up_gate=snap_take_up_gate, - eligibility_inputs_gate=eligibility_inputs_gate, - pregnancy_gate=pregnancy_gate, - reported_coverage_vintage_gate=reported_coverage_vintage_gate, - snap_discretionary_exemption_gate=snap_discretionary_exemption_gate, - target_registry=registry, + # A build record carries the summary its build computed: the + # calibration result and the registry it reads stay in the build's + # process (microcosm#1585 item 11, PR 4a). + gate_failures = ( + list(release_gate_failures) + if release_gate_failures is not None + else _release_gate_failures( + result, + dropped, + target_profile_gate, + health_input_gate, + base_population_gate, + incumbent_diagnostics, + immigration_gate, + input_mass_reference_gate, + degenerate_input_gate, + ecps_parity_gate=ecps_parity_gate, + hours_worked_gate=hours_worked_gate, + snap_take_up_gate=snap_take_up_gate, + eligibility_inputs_gate=eligibility_inputs_gate, + pregnancy_gate=pregnancy_gate, + reported_coverage_vintage_gate=reported_coverage_vintage_gate, + snap_discretionary_exemption_gate=snap_discretionary_exemption_gate, + target_registry=registry, + ) ) - commit = _git_output("rev-parse", "HEAD") - built_at = datetime.now(UTC).isoformat() - runtime = _runtime_versions() + # A certified build's provenance is its build's, from its record: the + # commit, the time it was made and the packages that made it, not the + # certifying process's (microcosm#1585 item 11, PR 4a). + commit = git_commit if git_commit is not None else _git_output("rev-parse", "HEAD") + if built_at is None: + built_at = datetime.now(UTC).isoformat() + runtime = ( + dict(runtime_versions) if runtime_versions is not None else _runtime_versions() + ) timing_payload = dict(timing or {}) warm_start_payload = ( dict(warm_start_calibration) @@ -13080,13 +13270,15 @@ def _build_progress( release_id: str, run_id: str | None = None, emitter: LocalTelemetryEmitter, + epoch_every: int | None = None, ) -> _BuildProgress: global _ACTIVE_PROGRESS # Each call establishes the current run, so a handle from a previous one # can never be marked failed in place of this build's. _ACTIVE_PROGRESS = None run_id = run_id or args.staging_run_id or release_id - epoch_every = _calibration_epoch_every(args) + if epoch_every is None: + epoch_every = _calibration_epoch_every(args) if args.no_staging: _ACTIVE_PROGRESS = _BuildProgress( run_id=run_id, @@ -13220,6 +13412,835 @@ def _is_release_refusal(error: BaseException) -> bool: return isinstance(error, Exception) +#: The build record a build leaves beside ``artifacts/`` and ``releases/`` +#: (microcosm#1585 item 11, PR 4a). The build ends once its H5, calibration +#: weights, diagnostics and gate evidence are written; certification is a +#: separate step (``tools/certify_us_national_build.py``) that runs the +#: release's post-export checks from this record and writes the manifests the +#: publisher requires. +US_BUILD_RECORD_FILENAME = "build_record.json" +US_BUILD_RECORD_KIND = "microcosm_us_national_build_record" +#: Schema 2 added the build's provenance (``built_at``, ``runtime``), its +#: staging settings and the record's own digest (``record_sha256``). A record +#: of another schema is certified with the code that built it. +US_BUILD_RECORD_SCHEMA_VERSION = 2 +#: The options of the build that its post-export checks read. Certification +#: takes them from the record, never from its own command line, so a build is +#: certified exactly as it was configured. +US_BUILD_RECORD_SETTINGS = ( + "allow_reform_coverage_smoke_failures", + "evidence_release", + "maximum_microsim_batch_size", + "scf_education_debt", + "skip_demographics", + "skip_out_of_sample_reforms", + "skip_reform_coverage_smoke", + "skip_reform_validation", +) +#: The build's gate verdicts its manifests carry, under the keyword +#: :func:`_build_manifests` takes each by. +US_BUILD_RECORD_GATES = ( + "target_profile_gate", + "ssi_take_up_delivery_gate_result", + "health_input_gate", + "base_population_gate", + "immigration_gate", + "degenerate_input_gate", + "ecps_parity_gate", + "hours_worked_gate", + "snap_take_up_gate", + "eligibility_inputs_gate", + "pregnancy_gate", + "reported_coverage_vintage_gate", + "snap_discretionary_exemption_gate", +) + + +def _build_record_gate(gate: GateResult | None) -> dict[str, object] | None: + if gate is None: + return None + return { + "name": gate.name, + "passed": bool(gate.passed), + "failures": list(gate.failures), + "details": dict(gate.details), + } + + +def _gate_from_build_record(record: Mapping[str, Any] | None) -> GateResult | None: + if record is None: + return None + return GateResult( + name=str(record["name"]), + passed=bool(record["passed"]), + failures=tuple(str(line) for line in record["failures"]), + details=dict(record["details"]), + ) + + +def _build_record_loss(value: float) -> float | str: + """A calibration loss in strict JSON: non-finite losses as their names.""" + value = float(value) + return value if math.isfinite(value) else repr(value) + + +def _build_record_finite(value: object) -> float | None: + if value is None: + return None + value = float(value) + return value if math.isfinite(value) else None + + +def _canonical_json(payload: object) -> str: + return json.dumps(payload, sort_keys=True, allow_nan=False) + + +class _RecordedCalibrationResult: + """The calibration result as certification reads it, from the record. + + The post-export consumers read each target's name, final estimate and + target value (reform validation's in-sample rows); the manifests read + the three losses, since the release's gate summary is computed when the + build ends and recorded (``release_gate_failures``). (A plain class: + this tool is loaded by file path in the tests, outside ``sys.modules``, + where ``dataclasses`` cannot resolve the module's string annotations.) + """ + + def __init__( + self, + *, + initial_loss: float | str, + final_loss: float | str, + fraction_within_10pct: float | str, + in_sample_fit: Sequence[Sequence[object]], + ) -> None: + self.initial_loss = float(initial_loss) + self.final_loss = float(final_loss) + self.fraction_within_10pct = float(fraction_within_10pct) + self.diagnostics = [ + SimpleNamespace(final_estimate=estimate, target=target) + for _, estimate, target in in_sample_fit + ] + self.problem = SimpleNamespace( + targets=[SimpleNamespace(name=str(name)) for name, _, _ in in_sample_fit] + ) + + +class _RecordedTargetRegistry: + """The target registry as :func:`_build_manifests` reads it: version, size.""" + + def __init__(self, *, version: object, n_specs: int) -> None: + self.version = version + self.n_specs = int(n_specs) + + def __len__(self) -> int: + return self.n_specs + + +def _us_build_files_certification_reads( + release_dir: Path, *, scf_education_debt: bool +) -> dict[str, Path]: + """The build's own files in its release directory that certification reads. + + Certification hashes each into the manifests (and reads the QRF tail + register and the stored-input verdict back from theirs), so the build + record pins each one the build wrote, under its artifact key in the + manifests. Gate evidence that certification writes itself (the + reform-coverage smoke) is not among them. + """ + + files = {"us_ssi_take_up": release_dir / "us_ssi_take_up.json"} + files.update( + (key, release_dir / filename) + for key, filename in US_RELEASE_GATE_EVIDENCE_FILES.items() + if filename not in US_CERTIFICATION_OUTPUT_FILES + ) + if scf_education_debt: + files.update( + (key, release_dir / filename) + for key, filename in US_SCF_EDUCATION_DEBT_FIT_ARTIFACTS.items() + ) + return files + + +def _us_build_record( + *, + release_id: str, + release_root: Path, + release_dir: Path, + artifact_root: Path, + dataset_key: str, + dataset_filename: str, + calibration_key: str, + calibration_filename: str, + commit: str, + built_at: str, + runtime: Mapping[str, str], + args: argparse.Namespace, + evidence_failure_owner_patterns: Sequence[tuple[str, str]], + terminal_gate_failures: Sequence[str], + n_households: int, + result, + post_export_scoring_plan: _PostExportScoringPlan, + release_gate_failures: Sequence[str] | None, + registry: TargetRegistry, + target_surface: Mapping[str, object], + dropped: Mapping[str, object], + gates: Mapping[str, GateResult | None], + warm_start_calibration: Mapping[str, object] | None, + selection_source: Mapping[str, object] | None, + target_surface_selection: Mapping[str, object] | None, + ledger_artifact: Mapping[str, object] | None, + default_dataset: Mapping[str, object] | None, + medicaid_enrollment_substitutions: Sequence[Mapping[str, object]], + exact_k_ladder: Mapping[str, object] | None, + base_pool: Mapping[str, object] | None, + acs_predictor_join: Mapping[str, object] | None, + export_input_mass_reference: Mapping[str, object] | None, + calibration_runtime: Mapping[str, object] | None, + diagnostics_outcome: DiagnosticsWriteOutcome, + scf_wealth_signal: Mapping[str, object] | None, + fiscal_target_sources: object, + congressional_district_vintage_crosswalk: Mapping[str, object] | None, + fiscal_target_exclusion_receipt: object, + fsa_target_receipt: object, + take_up_participation: Mapping[str, object], + medicaid_take_up_diagnostics: Mapping[str, object], + snap_state_take_up_diagnostics: Mapping[str, object], + timing: Mapping[str, object], + staging: Mapping[str, object], + staging_settings: Mapping[str, object], +) -> dict[str, object]: + """What certification needs of a finished build, as strict JSON. + + Everything certification reads that is not a file of the build: its + provenance (its commit, the time it finished and the packages that built + it), options, gate verdicts, calibration summary, scoring plan and the + receipts that ride the manifests. The files themselves are pinned by + digest: the H5, the calibration weights, the diagnostics and every other + file of the build that certification reads + (:func:`_us_build_files_certification_reads`). + """ + + if set(gates) != set(US_BUILD_RECORD_GATES): + raise ValueError( + "The build record carries exactly the gates its manifests write: " + f"expected {sorted(US_BUILD_RECORD_GATES)}, got {sorted(gates)}." + ) + + def relative(path: Path) -> str: + return path.relative_to(release_root).as_posix() + + files = { + "dataset": artifact_root / dataset_filename, + "calibration_weights": artifact_root / calibration_filename, + } + if diagnostics_outcome.status == "available": + files["calibration_diagnostics"] = release_dir / "calibration_diagnostics.json" + diagnostics = { + "status": "available", + "schema_version": diagnostics_outcome.schema_version, + "sha256": diagnostics_outcome.sha256, + } + else: + diagnostics = { + "status": "failed", + "expected_schema_version": diagnostics_outcome.expected_schema_version, + "error_code": diagnostics_outcome.error_code, + "message": diagnostics_outcome.message, + } + files.update( + (role, path) + for role, path in _us_build_files_certification_reads( + release_dir, scf_education_debt=bool(args.scf_education_debt) + ).items() + if path.is_file() + ) + return { + "schema_version": US_BUILD_RECORD_SCHEMA_VERSION, + "kind": US_BUILD_RECORD_KIND, + "release": release_dir.name, + "build": release_id, + "code": {"repository": "PolicyEngine/microcosm", "git_commit": commit}, + # The manifests' built_at and built-with packages: the time the build + # finished and the packages that built it, not certification's. + "built_at": built_at, + "runtime": dict(runtime), + "layout": { + "release_dir": relative(release_dir), + "artifact_root": relative(artifact_root), + "dataset_key": dataset_key, + "dataset_filename": dataset_filename, + "calibration_key": calibration_key, + "calibration_filename": calibration_filename, + }, + "files": { + role: {"path": relative(path), "sha256": _sha256(path)} + for role, path in files.items() + }, + "settings": {name: getattr(args, name) for name in US_BUILD_RECORD_SETTINGS}, + "evidence_failure_owner_patterns": [ + [pattern, owner] for pattern, owner in evidence_failure_owner_patterns + ], + "terminal_gate_failures": list(terminal_gate_failures), + "n_households": int(n_households), + # The calibration fit as the reform-validation consumer reads it: each + # target's name, final estimate and target value, in solve order. + "in_sample_fit": [ + [ + str(target.name), + _build_record_finite(diagnostic.final_estimate), + _build_record_finite(diagnostic.target), + ] + for diagnostic, target in zip( + result.diagnostics, result.problem.targets, strict=True + ) + ], + "post_export_scoring_plan": post_export_scoring_plan.record(), + "manifest": { + "result": { + "initial_loss": _build_record_loss(result.initial_loss), + "final_loss": _build_record_loss(result.final_loss), + "fraction_within_10pct": _build_record_loss( + result.fraction_within_10pct + ), + }, + "registry": {"version": registry.version, "n_specs": len(registry)}, + "release_gate_failures": ( + None if release_gate_failures is None else list(release_gate_failures) + ), + "target_surface": dict(target_surface), + "dropped": dict(dropped), + "gates": { + name: _build_record_gate(gates[name]) for name in US_BUILD_RECORD_GATES + }, + "warm_start_calibration": warm_start_calibration, + "selection_source": selection_source, + "target_surface_selection": target_surface_selection, + "ledger_artifact": ledger_artifact, + "default_dataset": default_dataset, + "medicaid_enrollment_substitutions": [ + dict(record) for record in medicaid_enrollment_substitutions + ], + "exact_k_ladder": exact_k_ladder, + "base_pool": base_pool, + "acs_predictor_join": acs_predictor_join, + "export_input_mass_reference": export_input_mass_reference, + "calibration_runtime": calibration_runtime, + "diagnostics_outcome": diagnostics, + "scf_wealth_signal": scf_wealth_signal, + }, + "source_coverage": { + "fiscal_target_sources": fiscal_target_sources, + "congressional_district_vintage_crosswalk": ( + congressional_district_vintage_crosswalk + ), + "fiscal_target_exclusion_receipt": fiscal_target_exclusion_receipt, + "fsa_student_loan_target_receipt": fsa_target_receipt, + }, + "take_up": { + "participation": take_up_participation, + "medicaid": medicaid_take_up_diagnostics, + "snap_state": snap_state_take_up_diagnostics, + }, + "timing": dict(timing), + "staging": dict(staging), + # Where the build staged, so certification stages there too. + "staging_settings": dict(staging_settings), + } + + +def _us_build_record_digest(record: Mapping[str, object]) -> str: + """The sha256 of a build record's canonical JSON, its own digest aside.""" + + body = {key: value for key, value in record.items() if key != "record_sha256"} + return hashlib.sha256(_canonical_json(body).encode("utf-8")).hexdigest() + + +def _write_us_build_record(release_root: Path, record: Mapping[str, object]) -> Path: + """Write the build record atomically; certification refuses a torn one. + + The record carries a digest of itself, so certification refuses one + edited after its build wrote it. That catches an edit, not a forgery: + anyone who recomputes the digest can change the record, until + certification signs (PR 4b). + """ + + path = release_root / US_BUILD_RECORD_FILENAME + # Digested as certification reads it back: JSON writes every key as a + # string, so a mapping keyed otherwise would digest differently once read. + record = json.loads( + json.dumps( + {key: value for key, value in record.items() if key != "record_sha256"}, + allow_nan=False, + ) + ) + record["record_sha256"] = _us_build_record_digest(record) + text = json.dumps(record, indent=1, allow_nan=False) + "\n" + staged = path.with_name(f".{path.name}.tmp") + staged.write_text(text, encoding="utf-8") + staged.replace(path) + return path + + +class _USBuildRecord: + """A finished build, read back from its :data:`US_BUILD_RECORD_FILENAME`. + + Paths are relative to the record's directory, so a build folder moved to + another machine certifies in place. (A plain class, for the reason + :class:`_RecordedCalibrationResult` gives.) + """ + + def __init__(self, payload: Mapping[str, Any], *, release_root: Path) -> None: + layout = payload["layout"] + self.payload = payload + self.release_root = release_root + self.build = str(payload["build"]) + self.release = str(payload["release"]) + self.commit = str(payload["code"]["git_commit"]) + self.built_at = str(payload["built_at"]) + self.runtime = { + str(name): str(version) for name, version in payload["runtime"].items() + } + self.release_dir = release_root / layout["release_dir"] + self.artifact_root = release_root / layout["artifact_root"] + self.dataset_key = str(layout["dataset_key"]) + self.dataset_filename = str(layout["dataset_filename"]) + self.calibration_key = str(layout["calibration_key"]) + self.calibration_filename = str(layout["calibration_filename"]) + self.settings = dict(payload["settings"]) + self.evidence_failure_owner_patterns = tuple( + (str(pattern), str(owner)) + for pattern, owner in payload["evidence_failure_owner_patterns"] + ) + self.terminal_gate_failures = tuple( + str(line) for line in payload["terminal_gate_failures"] + ) + self.n_households = int(payload["n_households"]) + self.timing = dict(payload["timing"]) + self.staging = dict(payload["staging"]) + self.staging_settings = dict(payload["staging_settings"]) + self.manifest_inputs = dict(payload["manifest"]) + self.source_coverage = dict(payload["source_coverage"]) + self.take_up = dict(payload["take_up"]) + + def certify_args(self) -> argparse.Namespace: + """The build's options its post-export checks read.""" + return argparse.Namespace(**self.settings) + + def post_export_scoring_plan( + self, args: argparse.Namespace, *, result + ) -> _PostExportScoringPlan: + """The build's scoring plan, rebuilt and held to the one it recorded.""" + plan = _record_post_export_scoring_plan( + args, n_households=self.n_households, result=result, release_id=self.build + ) + recorded = self.payload["post_export_scoring_plan"] + if _canonical_json(plan.record()) != _canonical_json(recorded): + raise RuntimeError( + f"Build {self.build}: the post-export scoring plan rebuilt for " + "certification differs from the one the build recorded in " + f"{US_BUILD_RECORD_FILENAME}; certify the build with the code " + f"it was built with ({self.commit})." + ) + return plan + + def gates(self) -> dict[str, GateResult | None]: + recorded = self.manifest_inputs["gates"] + return { + name: _gate_from_build_record(recorded[name]) + for name in US_BUILD_RECORD_GATES + } + + def calibration_result(self) -> _RecordedCalibrationResult: + return _RecordedCalibrationResult( + **self.manifest_inputs["result"], + in_sample_fit=self.payload["in_sample_fit"], + ) + + def registry_summary(self) -> _RecordedTargetRegistry: + return _RecordedTargetRegistry(**self.manifest_inputs["registry"]) + + def diagnostics_outcome(self) -> DiagnosticsWriteOutcome: + recorded = dict(self.manifest_inputs["diagnostics_outcome"]) + if recorded["status"] == "available": + return DiagnosticsWriteSuccess( + status="available", + path=self.release_dir / "calibration_diagnostics.json", + schema_version=recorded["schema_version"], + sha256=recorded["sha256"], + ) + return DiagnosticsWriteFailure( + status="failed", + expected_schema_version=recorded["expected_schema_version"], + error_code=recorded["error_code"], + message=recorded["message"], + ) + + +def _certify_with_its_own_code(payload: Mapping[str, object]) -> str: + """Where a record of another schema certifies: with the code that built it.""" + + code = payload.get("code") + commit = code.get("git_commit") if isinstance(code, dict) else None + built_with = f" ({commit})" if isinstance(commit, str) and commit else "" + return f"Certify the build with the code it was built with{built_with}" + + +def _read_us_build_record(path: Path) -> _USBuildRecord: + """Read a build record and check the files it pins are the build's.""" + + path = Path(path) + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + raise RuntimeError(f"Cannot read the build record {path}: {error}") from error + if not isinstance(payload, dict) or payload.get("kind") != US_BUILD_RECORD_KIND: + raise RuntimeError(f"{path} is not a US national build record.") + # Before the digest: a record of another schema need not carry one. + if payload.get("schema_version") != US_BUILD_RECORD_SCHEMA_VERSION: + raise RuntimeError( + f"{path} has build record schema {payload.get('schema_version')!r}; " + f"this tool reads schema {US_BUILD_RECORD_SCHEMA_VERSION}. " + f"{_certify_with_its_own_code(payload)}, or build it again into a " + "new --out." + ) + if payload.get("record_sha256") != _us_build_record_digest(payload): + raise RuntimeError( + f"{path} does not hash to the record_sha256 it carries; the record " + "changed after its build wrote it." + ) + release_root = path.resolve().parent + for role, pinned in payload["files"].items(): + file_path = release_root / pinned["path"] + if not file_path.is_file(): + raise RuntimeError( + f"Build {payload['build']}: its {role} file {file_path} is missing." + ) + actual = _sha256(file_path) + if actual != pinned["sha256"]: + raise RuntimeError( + f"Build {payload['build']}: its {role} file {file_path} hashes to " + f"{actual}, not the {pinned['sha256']} the build recorded; the " + "build's files changed after it finished." + ) + # A file certification would read that the build did not write: the + # manifests would bind it with no digest the build recorded. + for role, file_path in _us_build_files_certification_reads( + release_root / payload["layout"]["release_dir"], + scf_education_debt=bool(payload["settings"]["scf_education_debt"]), + ).items(): + if role not in payload["files"] and file_path.is_file(): + raise RuntimeError( + f"Build {payload['build']}: {file_path} ({role}) is not a file " + "the build recorded; it appeared after the build finished." + ) + return _USBuildRecord(payload, release_root=release_root) + + +#: Files certification writes into the release directory, beside the +#: manifests. A rerun after a failed certification removes them first, so a +#: check this run skips cannot leave an earlier attempt's verdict behind. +US_CERTIFICATION_OUTPUT_FILES = ( + "reform_coverage_smoke.json", + "reform_validation.json", + "demographics.json", + "us_ssi_social_security_holdout.json", + "us_medicare_irmaa_holdout.json", + "us_population_structure_holdout.json", + "us_source_coverage.json", + "us_take_up_participation.json", + "us_medicaid_take_up.json", + "us_snap_state_take_up.json", + "build_manifest.json", +) + + +def _certify_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="certify_us_national_build.py", + description=( + "Certify a finished US national build: run the release's " + "post-export checks (the reform-coverage smoke, reform validation, " + "demographics and the holdouts) on its written H5 and write the " + "manifests that microcosm-publish-release-build requires. The " + "build is the --out directory of " + "tools/build_us_fiscal_refresh_release.py, which holds " + f"{US_BUILD_RECORD_FILENAME}." + ), + ) + parser.add_argument( + "build_dir", + type=Path, + help=f"The build's --out directory, holding {US_BUILD_RECORD_FILENAME}.", + ) + parser.add_argument( + "--no-staging", + action="store_true", + help=( + "Certify without a staging run, even where the build staged; " + "hosted telemetry remains active. The build manifest's staging " + "block then records the opt-out, saying when the build staged, " + "beside the build's own block. A build that did not stage is " + "certified without one regardless." + ), + ) + parser.add_argument( + "--staging-run-id", + help=( + "The certification's staging run id, never the build's own, since " + "a staging run's files start afresh when it opens. Defaults to the " + "build's staging run id with -certify appended." + ), + ) + parser.add_argument( + "--staging-dir", + type=Path, + help=( + "Local directory for the certification's staging run files. " + "Defaults to /staging/runs/." + ), + ) + return parser + + +def _certify_progress( + args: argparse.Namespace, + *, + record: _USBuildRecord, + run_id: str, + emitter: LocalTelemetryEmitter, +) -> _BuildProgress: + """Certification's staging run, where its build staged. + + The post-export verdicts and the manifests reach the staging dashboard, + as they did when a build certified itself (microcosm#1585 item 11, PR + 4a). Certification stages where its build did, to the build's repository + and prefix, in a run of its own, since a staging run's files start afresh + when it opens. A build that did not stage (``--no-staging``, which + ``--exact-k`` requires) is certified without staging. ``--no-staging`` + opts certification out where the build staged too, as a build may opt + out: the publisher accepts a stated opt-out, and the reason says the + build staged, so the manifest shows that its certification did not. + """ + + settings = record.staging_settings + if settings["no_staging"] or args.no_staging: + build_run = record.staging.get("run_id") + reason = ( + "the build did not stage (--no-staging)" + if settings["no_staging"] + else "--no-staging at certification; the build staged" + + (f" (run {build_run})" if build_run else "") + ) + return _BuildProgress( + run_id=run_id, + emitter=emitter, + staging_bundle=None, + staging_opt_out_reason=reason, + ) + staging_dir = args.staging_dir + if staging_dir is None and not settings["repo_id"]: + # A build that staged only locally is certified into the same layout. + staging_dir = record.release_root / "staging" / "runs" / run_id + return _build_progress( + SimpleNamespace( + no_staging=False, + staging_run_id=run_id, + staging_dir=staging_dir, + staging_repo_id=settings["repo_id"], + staging_prefix=settings["prefix"], + staging_upload_interval_seconds=settings["upload_interval_seconds"], + ), + release_root=record.release_root, + release_id=record.build, + run_id=run_id, + emitter=emitter, + epoch_every=CALIBRATION_EPOCH_EVERY, + ) + + +def _refuse_reopening_the_builds_staging_run( + args: argparse.Namespace, record: _USBuildRecord +) -> None: + """Refuse a ``--staging-run-id`` that names the build or its staging run. + + Certification stages in a run of its own: a staging run's files start + afresh when it opens, so a run reopened under the build's id would + replace the build's progress and calibration curve. + """ + + build_run = record.staging.get("run_id") + if args.staging_run_id is not None and args.staging_run_id in { + build_run, + record.build, + }: + raise SystemExit( + f"--staging-run-id {args.staging_run_id} names build {record.build} " + "or its staging run; certification stages in a run of its own, " + "since a staging run's files start afresh when it opens. Choose " + f"another, or leave it out for {build_run or record.build}-certify." + ) + + +def certify_main(argv: Sequence[str] | None = None) -> None: + """Certify a finished build from its record (microcosm#1585 item 11, PR 4a). + + Certification runs at the commit the build was built at, from a clean + worktree (the build directory aside), with the packages the build was + built with, so the checks and the manifests are the build's own code and + score the H5 on the versions its manifests name. A build whose release + directory already carries a release manifest is refused: a certified + build is never changed. Certification opens its own staging run where + the build staged (:func:`_certify_progress`) and marks it failed if it + does not finish. + """ + + global _ACTIVE_EMITTER + args = _certify_parser().parse_args(argv) + record = _read_us_build_record(args.build_dir / US_BUILD_RECORD_FILENAME) + _refuse_reopening_the_builds_staging_run(args, record) + failures = _recorded_release_gate_failures(record.payload) + if failures: + raise SystemExit( + f"Build {record.build} failed {len(failures)} release gate(s) when " + "it was built, so it cannot be certified: " + "; ".join(failures) + ) + # Only a build whose release gates failed writes the #568 weight + # evidence (a green build removes any it finds), so its presence refuses + # the build whatever its record says. + weight_evidence = [ + name + for name in US_FAILED_BUILD_WEIGHT_EVIDENCE + if (record.release_dir / name).exists() + ] + if weight_evidence: + raise SystemExit( + f"Build {record.build}: its release directory holds the weight " + f"evidence a build writes when its release gates fail " + f"({', '.join(weight_evidence)}, microcosm#568), so it cannot be " + "certified." + ) + dirty = _git_dirty_paths(excluding=record.release_root) + if dirty: + raise SystemExit( + "Refusing to certify a build from a dirty git worktree: " + + "; ".join(dirty[:5]) + + ("; ..." if len(dirty) > 5 else "") + ) + head = _git_output("rev-parse", "HEAD") + if head != record.commit: + raise SystemExit( + f"Build {record.build} was built at {record.commit}; certify it " + f"from a checkout of that commit, not {head}." + ) + runtime = _runtime_versions() + mismatched = sorted( + name + for name in record.runtime.keys() | runtime.keys() + if record.runtime.get(name) != runtime.get(name) + ) + if mismatched: + raise SystemExit( + f"Build {record.build} was built with " + + ", ".join(f"{name} {record.runtime.get(name)}" for name in mismatched) + + "; certify it with those packages, not " + + ", ".join(f"{name} {runtime.get(name)}" for name in mismatched) + + ", so its checks run on the versions its manifests name." + ) + _refuse_certified_release_dir_reuse(record.release_dir) + for name in US_CERTIFICATION_OUTPUT_FILES: + (record.release_dir / name).unlink(missing_ok=True) + run_id = args.staging_run_id or ( + f"{record.staging.get('run_id') or record.build}-certify" + ) + _ACTIVE_EMITTER = start_local_telemetry_emitter_service( + run_id=run_id, + country_code="US", + pipeline="us_fiscal_refresh", + candidate_id=record.build, + release_id=record.build, + run_kind="certification", + ) + telemetry: _BuildProgress | None = None + try: + telemetry = _certify_progress( + args, record=record, run_id=run_id, emitter=_ACTIVE_EMITTER + ) + _certify_us_build(record, telemetry=telemetry) + except BaseException as error: + try: + if telemetry is not None: + telemetry.fail(error) + elif _ACTIVE_EMITTER.available: + _ACTIVE_EMITTER.fail(error) + except Exception as telemetry_error: # pragma: no cover - defensive + # A failing failure-report must not replace the real traceback. + print( + "warning: could not record the certification's staging run as " + f"failed: {type(telemetry_error).__name__}: {telemetry_error}", + file=sys.stderr, + ) + raise + + +def _certify_command(release_root: Path) -> str: + """The command that certifies the build in ``release_root``.""" + return shlex.join( + [ + "uv", + "run", + "--no-sync", + "python", + "tools/certify_us_national_build.py", + str(release_root), + ] + ) + + +def _print_built_result( + *, + build: str, + release_root: Path, + release_dir: Path, + artifact_root: Path, + build_record: Path, + release_gate_failures: Sequence[str] = (), +) -> None: + """Print the finished build and the command that certifies it. + + A build that failed a release gate is printed too, so its H5 can be + evaluated, with the failures that stop certification. + + A build is not publishable until it is certified: certification runs the + release's post-export checks on the written H5 and writes the manifests + ``microcosm-publish-release-build`` requires (microcosm#1585 item 11, PR + 4a). + """ + print( + json.dumps( + { + "release": release_dir.name, + "build": build, + "certified": False, + "certifiable": not release_gate_failures, + "release_gate_failures": list(release_gate_failures), + "build_record": str(build_record), + "release_dir": str(release_dir), + "artifact_root": str(artifact_root), + "certify_command": _certify_command(release_root), + "next": ( + "The build is written and checked; it is not publishable " + "until certify_command has run the release's post-export " + "checks and written its manifests." + ), + }, + indent=2, + sort_keys=True, + ) + ) + + #: This tool's scope of us/gates.json, evaluated in shadow beside today's #: gates (microcosm#1585 item 11, PR 2 of 4). US_NATIONAL_GATE_SCOPE = "us_national" @@ -13758,6 +14779,10 @@ def _main(argv: Sequence[str] | None = None) -> int | None: _refuse_skipped_checks_left_files( args.out.resolve() / "releases" / _release_for_build(args), args ) + if dry_run is None: + # A build stops at its record (microcosm#1585 item 11, PR 4a), so an + # --out awaiting certification carries no release manifest yet. + _refuse_overwriting_a_build_awaiting_certification(args.out.resolve()) pinned_incumbent_payload: dict[str, object] | None = None pinned_incumbent_sha256: str | None = None if args.exact_k is not None: @@ -16843,6 +17868,9 @@ def _main(argv: Sequence[str] | None = None) -> int | None: enforced_ecps_parity_gate = ( None if args.allow_ecps_parity_gaps else ecps_parity_gate ) + # The summary the manifests' calibration gate block carries, recorded for + # certification (microcosm#1585 item 11, PR 4a); None when it crashed. + release_gate_summary: list[str] | None = None try: gate_failures = shadow_failures( "us_national_release_gates", @@ -16900,6 +17928,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: } ), ) + release_gate_summary = list(gate_failures) except Exception as error: # Degraded-mode guard (microcosm#547): the batch must still form and # the diagnostics artifact must still be written when earlier @@ -17427,6 +18456,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # below: each already evaluates and reports its full failure set # internally, and both require the written H5 / export artifacts that a # gate-failed run must not produce. + # A failed release gate no longer withholds a build's H5 (microcosm#1585 + # item 11, PR 4a): a build is evaluated before anyone certifies it. Its + # failures ride the build record, certification refuses the build while + # they stand, and the build exits non-zero once its record is written. + build_refusal: RuntimeError | None = None if terminal_gate_failures: # Evidence tier (microcosm#506): owners are resolved NOW so an # unowned failure refuses the export before the H5 and manifest work @@ -17469,7 +18503,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: ) if evidence_refusal is not None: raise evidence_refusal - raise RuntimeError( + build_refusal = RuntimeError( "Release gates failed: " + "; ".join(terminal_gate_failures) ) # The owned failures ride into the release manifest's known_failures @@ -17481,28 +18515,30 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # is unowned the run dies post-H5 — weights retained in the written # dataset, per the #568 doctrine for late-gate failures — and no # manifest is minted. - terminal_batch_telemetry.stage( - "release_gates", - status="failed", - message=( - "Release gates failed; --evidence-release continues to " - "export with the failures recorded (microcosm#506)." - ), - failures=terminal_gate_failures, - force_upload=True, - ) + else: + terminal_batch_telemetry.stage( + "release_gates", + status="failed", + message=( + "Release gates failed; --evidence-release continues to " + "export with the failures recorded (microcosm#506)." + ), + failures=terminal_gate_failures, + force_upload=True, + ) # A green run must not inherit a prior failed attempt's weight evidence # (microcosm#568 round 2): with --out/--release-id reuse, stale evidence # files would coexist with a certified release whose manifest knows # nothing about them. The batched gates have passed (or --evidence-release # is recording their failures), so any evidence present here belongs to a # superseded attempt — remove it before the release artifacts are written. - for stale_evidence in ( - release_dir / FINAL_HOUSEHOLD_WEIGHTS_FILENAME, - release_dir / FINAL_HOUSEHOLD_WEIGHT_IDS_FILENAME, - release_dir / FINAL_HOUSEHOLD_WEIGHTS_METADATA_FILENAME, - ): - stale_evidence.unlink(missing_ok=True) + if build_refusal is None: + for stale_evidence in ( + release_dir / FINAL_HOUSEHOLD_WEIGHTS_FILENAME, + release_dir / FINAL_HOUSEHOLD_WEIGHT_IDS_FILENAME, + release_dir / FINAL_HOUSEHOLD_WEIGHTS_METADATA_FILENAME, + ): + stale_evidence.unlink(missing_ok=True) dataset_path = artifact_root / dataset_filename # The export H5 write: everything below (reform smoke, take-up contract, # release manifest sha) reads THIS file, and it must be written only after @@ -17530,7 +18566,221 @@ def _main(argv: Sequence[str] | None = None) -> int | None: ), ) if stored_input_premise_failure is not None: - raise RuntimeError(stored_input_premise_failure) + if build_refusal is None: + raise RuntimeError(stored_input_premise_failure) + # A failed build still ends at its record (microcosm#1585 item 11, + # PR 4a): what its written file fails joins its release gate failures + # instead of replacing them. + terminal_gate_failures.append(stored_input_premise_failure) + # The build ends here (microcosm#1585 item 11, PR 4a). The optional export + # audit and the calibration NPZ read the calibration result, which only + # this process holds, so they run first. Every later stage scores the + # written H5 and runs from the build record (_certify_us_build), so a + # build can be judged before anyone pays for those checks. + if args.audit_export_targets: + if telemetry is not None: + telemetry.stage( + "post_export_audit", + message="Auditing exported H5 against calibration targets.", + ) + try: + _assert_export_matches_calibration( + dataset_path, + result, + target_specs, + maximum_microsim_batch_size=args.maximum_microsim_batch_size, + ) + except Exception as error: + if build_refusal is None: + raise + terminal_gate_failures.append( + f"Export audit failed: {type(error).__name__}: {error}" + ) + + if telemetry is not None: + telemetry.stage("write_calibration_npz", message="Writing calibration NPZ.") + calibration_path = artifact_root / calibration_filename + _write_npz(calibration_path, result=result, registry=registry) + # Keep a copy of the exact base artifact beside diagnostics for local audit. + _copy_base_h5_for_local_audit( + base_h5, + release_root / f"base_{base_h5.name}", + authenticated_pool_h5=authenticated_pool_h5, + ) + if build_refusal is not None: + # The refusal names every failure the record carries, those found + # after the H5 write included. + build_refusal = RuntimeError( + "Release gates failed: " + "; ".join(terminal_gate_failures) + ) + timing["build_seconds"] = time.perf_counter() - build_started + build_record_path = _write_us_build_record( + release_root, + _us_build_record( + release_id=release_id, + release_root=release_root, + release_dir=release_dir, + artifact_root=artifact_root, + dataset_key=dataset_key, + dataset_filename=dataset_filename, + calibration_key=calibration_key, + calibration_filename=calibration_filename, + commit=full_commit, + built_at=datetime.now(UTC).isoformat(), + runtime=_runtime_versions(), + args=args, + evidence_failure_owner_patterns=evidence_failure_owner_patterns, + terminal_gate_failures=terminal_gate_failures, + n_households=int(export_frame.n("household")), + result=result, + post_export_scoring_plan=post_export_scoring_plan, + release_gate_failures=release_gate_summary, + registry=registry, + target_surface=current_target_surface, + dropped=compilation, + gates={ + "target_profile_gate": target_profile_gate, + "ssi_take_up_delivery_gate_result": ssi_take_up_delivery_gate_result, + "health_input_gate": health_input_gate, + "base_population_gate": base_population_gate, + "immigration_gate": immigration_gate, + "degenerate_input_gate": degenerate_input_gate, + "ecps_parity_gate": enforced_ecps_parity_gate, + "hours_worked_gate": hours_worked_gate, + "snap_take_up_gate": snap_take_up_gate, + "eligibility_inputs_gate": eligibility_inputs_gate, + "pregnancy_gate": pregnancy_gate, + "reported_coverage_vintage_gate": reported_coverage_vintage_gate, + "snap_discretionary_exemption_gate": ( + snap_discretionary_exemption_gate + ), + }, + warm_start_calibration=warm_start_calibration, + selection_source=selection_source_payload, + target_surface_selection=target_surface_selection, + ledger_artifact=ledger_artifact.provenance(), + default_dataset=default_dataset, + medicaid_enrollment_substitutions=medicaid_enrollment_substitutions, + exact_k_ladder=exact_k_ladder_provenance, + base_pool=base_pool_receipt, + acs_predictor_join=acs_predictor_join_receipt, + export_input_mass_reference=export_input_mass_reference, + calibration_runtime=calibration_runtime, + diagnostics_outcome=diagnostics_outcome, + scf_wealth_signal=scf_wealth_signal, + fiscal_target_sources=_fiscal_target_source_provenance(target_specs), + congressional_district_vintage_crosswalk=( + congressional_district_vintage_crosswalk_metadata + ), + fiscal_target_exclusion_receipt=fiscal_target_exclusion_receipt, + fsa_target_receipt=fsa_target_receipt, + take_up_participation=us_take_up_participation_diagnostics(export_frame), + medicaid_take_up_diagnostics=medicaid_take_up_diagnostics, + snap_state_take_up_diagnostics=snap_state_take_up_diagnostics, + timing=timing, + staging=_staging_manifest_block(telemetry), + staging_settings={ + "no_staging": bool(args.no_staging), + "repo_id": args.staging_repo_id or None, + "prefix": args.staging_prefix, + "upload_interval_seconds": float(args.staging_upload_interval_seconds), + }, + ), + ) + if telemetry is not None: + telemetry.attach_artifact("build_record", build_record_path) + if build_refusal is None: + telemetry.complete() + _print_built_result( + build=release_id, + release_root=release_root, + release_dir=release_dir, + artifact_root=artifact_root, + build_record=build_record_path, + release_gate_failures=terminal_gate_failures if build_refusal else (), + ) + if build_refusal is not None: + raise build_refusal + + +def _certify_us_build( + record: _USBuildRecord, *, telemetry: _BuildProgress | None = None +) -> None: + """Run a finished build's post-export checks and write its manifests. + + The build (``_main``) ends once its H5, calibration weights, diagnostics, + gate evidence and :data:`US_BUILD_RECORD_FILENAME` are written. This + scores the written H5 (the reform-coverage smoke, reform validation, + demographics and the holdouts), writes the source-coverage and take-up + receipts and both manifests, and leaves the release directory in the + build-folder layout for ``microcosm-publish-release-build`` + (microcosm#1585 item 11, PR 4a). Every input is the record, or a file + whose digest the record pins: nothing is read from the build's process. + The manifests' provenance (the commit, ``built_at`` and the built-with + packages) is the build's, from the record. + """ + + certify_started = time.perf_counter() + args = record.certify_args() + release_id = record.build + release_dir = record.release_dir + artifact_root = record.artifact_root + dataset_key = record.dataset_key + dataset_filename = record.dataset_filename + calibration_key = record.calibration_key + calibration_filename = record.calibration_filename + dataset_path = artifact_root / dataset_filename + evidence_failure_owner_patterns = record.evidence_failure_owner_patterns + terminal_gate_failures = list(record.terminal_gate_failures) + timing = dict(record.timing) + result = record.calibration_result() + registry = record.registry_summary() + post_export_scoring_plan = record.post_export_scoring_plan(args, result=result) + inputs = record.manifest_inputs + if inputs["release_gate_failures"] is None: + raise RuntimeError( + f"Build {release_id}: its release gate summary crashed when it was " + "built, so its manifests cannot record the calibration gate." + ) + gates = record.gates() + target_profile_gate = gates["target_profile_gate"] + ssi_take_up_delivery_gate_result = gates["ssi_take_up_delivery_gate_result"] + health_input_gate = gates["health_input_gate"] + base_population_gate = gates["base_population_gate"] + immigration_gate = gates["immigration_gate"] + degenerate_input_gate = gates["degenerate_input_gate"] + enforced_ecps_parity_gate = gates["ecps_parity_gate"] + hours_worked_gate = gates["hours_worked_gate"] + snap_take_up_gate = gates["snap_take_up_gate"] + eligibility_inputs_gate = gates["eligibility_inputs_gate"] + pregnancy_gate = gates["pregnancy_gate"] + reported_coverage_vintage_gate = gates["reported_coverage_vintage_gate"] + snap_discretionary_exemption_gate = gates["snap_discretionary_exemption_gate"] + # Read only by the gate summary, which the build recorded. + incumbent_diagnostics = None + enforced_input_mass_reference_gate = None + current_target_surface = inputs["target_surface"] + compilation = inputs["dropped"] + warm_start_calibration = inputs["warm_start_calibration"] + selection_source_payload = inputs["selection_source"] + target_surface_selection = inputs["target_surface_selection"] + default_dataset = inputs["default_dataset"] + medicaid_enrollment_substitutions = inputs["medicaid_enrollment_substitutions"] + exact_k_ladder_provenance = inputs["exact_k_ladder"] + base_pool_receipt = inputs["base_pool"] + acs_predictor_join_receipt = inputs["acs_predictor_join"] + export_input_mass_reference = inputs["export_input_mass_reference"] + calibration_runtime = inputs["calibration_runtime"] + diagnostics_outcome = record.diagnostics_outcome() + scf_wealth_signal = inputs["scf_wealth_signal"] + source_coverage = record.source_coverage + congressional_district_vintage_crosswalk_metadata = source_coverage[ + "congressional_district_vintage_crosswalk" + ] + fiscal_target_exclusion_receipt = source_coverage["fiscal_target_exclusion_receipt"] + fsa_target_receipt = source_coverage["fsa_student_loan_target_receipt"] + medicaid_take_up_diagnostics = record.take_up["medicaid"] + snap_state_take_up_diagnostics = record.take_up["snap_state"] # Route A remediation (microcosm#956): every post-export stage below (the # smoke, reform validation, demographics) scores THIS file through one # household-batched scorer instead of one whole-pool Microsimulation each. @@ -17616,24 +18866,6 @@ def _main(argv: Sequence[str] | None = None) -> int | None: _evidence_known_failures( terminal_gate_failures, evidence_failure_owner_patterns ) - if args.audit_export_targets: - if telemetry is not None: - telemetry.stage( - "post_export_audit", - message="Auditing exported H5 against calibration targets.", - ) - _assert_export_matches_calibration( - dataset_path, - result, - target_specs, - maximum_microsim_batch_size=args.maximum_microsim_batch_size, - ) - - if telemetry is not None: - telemetry.stage("write_calibration_npz", message="Writing calibration NPZ.") - calibration_path = artifact_root / calibration_filename - _write_npz(calibration_path, result=result, registry=registry) - if not args.skip_reform_validation: if telemetry is not None: telemetry.stage( @@ -17746,7 +18978,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: **surface_exclusions, }, ) - coverage["fiscal_target_sources"] = _fiscal_target_source_provenance(target_specs) + coverage["fiscal_target_sources"] = source_coverage["fiscal_target_sources"] if congressional_district_vintage_crosswalk_metadata is not None: coverage["congressional_district_vintage_crosswalk"] = ( congressional_district_vintage_crosswalk_metadata @@ -17788,7 +19020,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "take_up_participation", message="Writing take-up participation diagnostics.", ) - take_up_participation = us_take_up_participation_diagnostics(export_frame) + take_up_participation = record.take_up["participation"] write_us_take_up_participation_diagnostics( take_up_participation, release_dir / "us_take_up_participation.json", @@ -17848,7 +19080,8 @@ def _main(argv: Sequence[str] | None = None) -> int | None: release_dir / "us_snap_state_take_up.json", ) telemetry.stage("manifests", message="Writing release manifests.") - timing["total_build_seconds"] = time.perf_counter() - build_started + timing["certify_seconds"] = time.perf_counter() - certify_started + timing["total_build_seconds"] = timing["build_seconds"] + timing["certify_seconds"] evidence_known_failures = None if args.evidence_release: if not terminal_gate_failures: @@ -17885,14 +19118,18 @@ def _main(argv: Sequence[str] | None = None) -> int | None: pregnancy_gate=pregnancy_gate, reported_coverage_vintage_gate=reported_coverage_vintage_gate, snap_discretionary_exemption_gate=snap_discretionary_exemption_gate, + release_gate_failures=inputs["release_gate_failures"], timing=timing, warm_start_calibration=warm_start_calibration, selection_source=selection_source_payload, target_surface_selection=target_surface_selection, - ledger_artifact=ledger_artifact.provenance(), + ledger_artifact=inputs["ledger_artifact"], default_dataset=default_dataset, medicaid_enrollment_substitutions=medicaid_enrollment_substitutions, - staging=_staging_manifest_block(telemetry), + # The staging run the publisher checks is certification's, which + # carries the post-export verdicts and the manifests; the build's + # rides inside it. + staging={**_staging_manifest_block(telemetry), "build": dict(record.staging)}, dataset_key=dataset_key, dataset_filename=dataset_filename, calibration_key=calibration_key, @@ -17911,6 +19148,9 @@ def _main(argv: Sequence[str] | None = None) -> int | None: diagnostics_outcome=diagnostics_outcome, scf_wealth_signal=scf_wealth_signal, scf_education_debt=args.scf_education_debt, + git_commit=record.commit, + built_at=record.built_at, + runtime_versions=record.runtime, ) # Both manifests name the release and this build, in the build-folder # layout, before telemetry attaches them; the directory must then pass @@ -17929,12 +19169,6 @@ def _main(argv: Sequence[str] | None = None) -> int | None: ) telemetry.complete() - # Keep a copy of the exact base artifact beside diagnostics for local audit. - _copy_base_h5_for_local_audit( - base_h5, - release_root / f"base_{base_h5.name}", - authenticated_pool_h5=authenticated_pool_h5, - ) _print_build_result( build=release_id, release_dir=release_dir, diff --git a/tools/certify_us_national_build.py b/tools/certify_us_national_build.py new file mode 100755 index 0000000000..d0fe298fd9 --- /dev/null +++ b/tools/certify_us_national_build.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Certify a finished US national build so it can be published. + +``tools/build_us_fiscal_refresh_release.py`` builds the dataset and stops: it +writes the H5, the calibration weights, the diagnostics, every gate verdict +the build itself checks, and ``build_record.json``, then exits so the build +can be evaluated. Nothing it writes is publishable. + +This command runs the release's post-export checks on that build: the +reform-coverage smoke, reform validation, demographics and the holdouts, +scored on the written H5, then the source coverage and take-up receipts. It +writes both manifests, so ``microcosm-publish-release-build`` can then +publish the build (microcosm#1585 item 11, PR 4a). It reads the build's +options from its record, never from its own command line, and runs at the +commit the build was built at:: + + uv run --no-sync python tools/certify_us_national_build.py + +A failed certification leaves the build as it was; rerun this command once +the cause is fixed. A certified build is never certified again. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +_TOOLS_DIR = Path(__file__).resolve().parent +if str(_TOOLS_DIR) not in sys.path: + sys.path.insert(0, str(_TOOLS_DIR)) + +import build_us_fiscal_refresh_release as fiscal_release # noqa: E402 + + +def main(argv: list[str] | None = None) -> None: + fiscal_release.certify_main(argv) + + +if __name__ == "__main__": + main() diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index d9ea886b6a..6a487db370 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -3063,19 +3063,33 @@ def resolve_target_surface( flag: str | None, dropped: int | None, release_manifest: Mapping[str, Any] | None, + build_record: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """The build's target surface: the flag, else the reference release - manifest's ``target_surface_selection``, else ``full``. + manifest's ``target_surface_selection``, else, for a build not yet + certified, its ``build_record.json``'s, else ``full``. A manifest in the build-folder layout (microcosm#1570) names its build in ``build`` and records the selection at its top level; one in the tagged - layout records it in its ``build`` object. + layout records it in its ``build`` object. A build that has not been + certified has no manifest; its record carries the selection under + ``manifest`` (microcosm#1585 item 11, PR 4a). """ build = None if release_manifest is None else release_manifest.get("build") tagged = isinstance(build, Mapping) details = build if tagged else release_manifest or {} selection = details.get("target_surface_selection") field = "build.target_surface_selection" if tagged else "target_surface_selection" + source = f"reference release_manifest.json {field}" + if release_manifest is None and build_record is not None: + selection = (build_record.get("manifest") or {}).get("target_surface_selection") + source = "reference build_record.json manifest.target_surface_selection" + if not selection and flag is None: + return { + "mode": "full", + "dropped_congressional_district_targets": dropped, + "source": source, + } if flag is not None: return { "mode": flag, @@ -3090,7 +3104,7 @@ def resolve_target_surface( if dropped is not None else selection.get("dropped_congressional_district_targets") ), - "source": f"reference release_manifest.json {field}", + "source": source, } return { "mode": "full", @@ -3117,6 +3131,18 @@ def _read_json(path: Path | None): return None if path is None else json.loads(Path(path).read_text()) +def reference_build_record(release_dir: Path | None) -> Path | None: + """The record of the build whose release directory is the reference. + + A build writes ``build_record.json`` in its ``--out`` directory, two + levels above ``releases//`` (microcosm#1585 item 11, PR 4a). + """ + if release_dir is None: + return None + candidate = Path(release_dir).resolve().parent.parent / "build_record.json" + return candidate if candidate.is_file() else None + + def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--export", type=Path, required=True, help="H5 to score") @@ -3157,7 +3183,10 @@ def main(argv: Sequence[str] | None = None) -> int: help="a full-size build's release directory (releases//, or " "an older build's releases//): " "defaults --reference-smoke, --reference-validation, " - "--reference-build-manifest and --calibration-diagnostics to its files", + "--reference-build-manifest and --calibration-diagnostics to its files. " + "A build not yet certified works too: its target surface then comes " + "from the build_record.json in its --out directory. A build whose " + "release gates failed is refused", ) parser.add_argument( "--reference-smoke", @@ -3212,6 +3241,16 @@ def main(argv: Sequence[str] | None = None) -> int: help="rows per chunked source read (default: sized from 128 MiB)", ) args = parser.parse_args(argv) + if args.reference_release_dir is not None: + # A failed build keeps its H5 to be evaluated, which the probe may + # score as --export, but it is no reference (microcosm#1585 item 11). + failed = load_builder()._failed_build_holding(args.reference_release_dir) + if failed is not None: + parser.error( + f"--reference-release-dir {args.reference_release_dir} belongs " + f"to {failed}. A failed build can be scored as --export, but " + "not taken as the reference." + ) receipt_path = args.sample_receipt if receipt_path is None: @@ -3229,6 +3268,7 @@ def main(argv: Sequence[str] | None = None) -> int: args.target_surface, args.dropped_congressional_district_targets, _read_json(references["release_manifest"]), + _read_json(reference_build_record(args.reference_release_dir)), ) register = None if args.qrf_tail_register is not None: diff --git a/tools/route_a/README.md b/tools/route_a/README.md index cfc387d66c..3b47e6f3b5 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -1,15 +1,30 @@ # Route A release driver -`route_a.sh` builds a US PUF-support base, builds a fiscal-refresh release -candidate from that base, a build of `microcosm-us-2024-national`, runs -`preflight_us_release_gates.py` twice and runs `microcosm-publish-release-build` -with `--preflight-only`. It leaves a hand-off with `published: false`. -Publication remains a separate manual step that Max authorizes. +`route_a.sh` builds a US PUF-support base, then a fiscal-refresh release +build from that base, a build of `microcosm-us-2024-national`, and stops. The +build is written and checked by its own gates, but it is not publishable: the +run ends with `ROUTE_A_BUILT.json`, so the build can be evaluated first +(microcosm#1585 item 11, PR 4a). + +`route_a.sh --certify` (or `ROUTE_A_CERTIFY=1`) on the same `RUN_ROOT` skips +the accepted stages and certifies that build with +`tools/certify_us_national_build.py`, which runs the release's post-export +checks on the written H5 and writes the manifests publication requires. Once +the build is accepted, the driver does not hash the raw inputs again, since +certification reads none of them. It then runs `preflight_us_release_gates.py` +against the release manifest and `microcosm-publish-release-build` with +`--preflight-only`, and leaves a hand-off with `published: false`. Publication +remains a separate manual step that Max authorizes. Only a run with +`--certify` is a from-scratch build and certification receipt: a run that +stops at `ROUTE_A_BUILT.json` has not been through the post-export checks or +either preflight. The driver, `supervise.py`, `sample_series.py`, `check_flags.py` and `with_hf_token.sh` live together here. The driver, supervisor and sampler -originated in the off-repository Route A tooling. The release stage now enables -staging telemetry by default; `ROUTE_A_STAGING=0` restores `--no-staging`. +originated in the off-repository Route A tooling. The release and certify +stages enable staging telemetry by default; `ROUTE_A_STAGING=0` restores +`--no-staging` for both; when the build staged and its certification does not, +the build manifest records the opt-out. ## Configure and run @@ -189,7 +204,8 @@ overnight chain is alive, unless `EARLY_START_AFTER_HEAVY=1` and its log records | `prefetch` | Fetches the ASEC unemployment archive, SCF summary/full extracts, SIPP financial-assets/tips donors and ORG donor through the release's fetch helpers. Exit 0 is required before release. An initial failure lets the base proceed; release retries it. | | `base` | Runs `build_us_puf_support_base.py --stage all` on the pinned raw inputs, with seed 0, 32 estimators, target year 2024, district assignment/crosswalk and block ladder. Requires exit 0 and the expected H5, then hashes it. | | `preflight-base` | Runs `preflight_us_release_gates.py` on that H5 and the pinned feed, with the configured new-lineage mode and optional export-mass reference. Accepts 0 (clean) or 2 (AT-RISK); `RELEASE_DESPITE_PREFLIGHT_FAIL=1` also accepts 1 here. | -| `release` | Runs `build_us_fiscal_refresh_release.py --base-h5` with the feed, SSI basis, SCF extract and configured release arguments; its `--release-id` is the build ID. Requires exit 0 and `/releases/microcosm-us-2024-national/release_manifest.json`. Staging telemetry is enabled for this stage. | +| `release` | Runs `build_us_fiscal_refresh_release.py --base-h5` with the feed, SSI basis, SCF extract and configured release arguments; its `--release-id` is the build ID. Requires exit 0 and `/build_record.json`. Staging telemetry is enabled for this stage. Without `--certify` the run ends here with `ROUTE_A_BUILT.json`. | +| `certify` | With `--certify` only: runs `tools/certify_us_national_build.py `. Certification stages where its build staged, in a run of its own, so with `ROUTE_A_STAGING=1` it gets the release stage's staging credential; with `ROUTE_A_STAGING=0` it runs as the release stage does, online without the HF credential variables, and with `--no-staging`. Requires exit 0 and `/releases/microcosm-us-2024-national/release_manifest.json`. | | `preflight-release` | Repeats the release-gate preflight with the candidate's release manifest. Accepts 0 or 2. | | `publisher-preflight` | Runs `microcosm-publish-release-build --preflight-only` against the release directory, `/releases/microcosm-us-2024-national`, where a national run writes its build, and the artifacts. Requires exit 0. The command checks the build with its release contract, prints what it would publish, and starts no emitter. It takes no `--extra-file`: the command publishes every artifact the release manifest lists, including the two SCF education-debt fit tables of a release run with `--scf-education-debt` in `RELEASE_EXTRA_ARGS`. | @@ -197,8 +213,9 @@ Both gate preflights and the publisher preflight remove the HF credential variables and Slack webhook variables, set `POPULACE_RELEASE_ENV=/dev/null` and `HF_HUB_OFFLINE=1`. The base and prefetch retain their original command and `PYTHONUNBUFFERED=1` configuration. An empty `PREFLIGHT_NEW_LINEAGE_ARGS` records -both gate preflights as `BLOCKED`, permits the build, and ends with -`ROUTE_A_BLOCKED.json` and exit 4 instead of `ROUTE_A_DONE.json`. +both gate preflights as `BLOCKED`, permits the build, and ends with exit 4: +after a run without `--certify`, with `ROUTE_A_BUILT.json`; after +certification, with `ROUTE_A_BLOCKED.json` instead of `ROUTE_A_DONE.json`. Every stage runs through the supervisor's admission check and limits: @@ -208,6 +225,7 @@ Every stage runs through the supervisor's admission check and limits: | base | 100 | 80 | max(26, 70 − checkpoint GiB) | 21600 | 64800 | | gate preflights | 24 | 16 | 22 | 3600 | 7200 | | release | 110 | `RELEASE_RAM_GIB` (example: 50) | 45 | `RELEASE_WALL_SECONDS` (example: 345600) | 2000000 | +| certify | 110 | `RELEASE_RAM_GIB` (example: 50) | 45 | `CERTIFY_WALL_SECONDS` (default: 345600) | 2000000 | | publisher preflight | 24 | 16 | 22 | 7200 | 14400 | The driver waits up to `RESOURCE_WAIT_HOURS` (example: 12) for admission and @@ -231,7 +249,11 @@ is waited for, and failed/refused directories are moved aside. Base stages resume by completed checkpoint prefix. Failed release attempts get a new release ID while retaining the shared checkpoint root. With `PRUNE_BASE_CHECKPOINTS=1`, base `*.frame.h5` files are removed after hashing the -finished H5. The hand-off file written at the end (`ROUTE_A_DONE.json` or +finished H5. A run without `--certify` ends with `ROUTE_A_BUILT.json`, which +records the build, its directory and record and the base preflight's verdict, +and says how to certify it. A failed certification is its own stage, so a +rerun with `--certify` repeats only it, never the build. After certification +the hand-off file written at the end (`ROUTE_A_DONE.json` or `ROUTE_A_BLOCKED.json`) records the candidate paths and preflight verdicts, plus two manual commands the driver never runs: `publish_command` publishes the build through the emitter into its folder of `microcosm-us-2024-national`, @@ -303,7 +325,8 @@ shell tracing, removes inherited HF credential aliases, calls the configured `agent-secret get HUGGING_FACE_TOKEN_MAX` at run time, refuses a failed/empty lookup, exports `HF_TOKEN` and immediately `exec`s the release. It does not put the returned value into argv, a config or a log. Do not fetch a token before -starting the driver. With `ROUTE_A_STAGING=0`, the release gets `--no-staging`, +starting the driver. The certify stage starts the same way. With +`ROUTE_A_STAGING=0`, the release and certification get `--no-staging`, inherited HF credential variables are removed and the wrapper is not called. The release parser defaults to `policyengine/populace-us-staging` and reads @@ -326,14 +349,19 @@ stride grows past ten only when the run's solves total more than 24,000 epochs. Because each solve's rows start at epoch 1, the epoch falls wherever the refit begins, even when `--epochs` is ten or fewer. The builder emits stages for loading the base, source enrichments, target compilation, -calibration, export/gates, diagnostics and manifests, and uploads attached -diagnostics as they are written. Completion records status `passed`; reported -failures record status `failed`. +calibration, export/gates and diagnostics, and uploads attached diagnostics +as they are written. Completion records status `passed`; reported failures +record status `failed`. Certification opens a staging run of its own, +`-certify`, where its build staged: its stages are the post-export +checks and the manifests, it attaches their files, and a failed certification +records `failed` there. The release's build manifest names that run as its +staging run and the build's inside it, so the publisher's staging check reads +the run that scored what it publishes. Telemetry is written locally under -`/staging/runs//` and uploaded under -`runs//`, with `run_manifest.json`, `latest_staging.json` and -`runs.json` allowing discovery. The base, donor prefetch, offline preflights +`/staging/runs//` and uploaded under `runs//`, +with `run_manifest.json`, `latest_staging.json` and `runs.json` allowing +discovery. The base, donor prefetch, offline preflights and supervisor resource series do not emit these staging records. If uploads fail, dashboard visibility is not guaranteed. A staging upload does not publish the build or change `releases.json` in `policyengine/populace-us`. diff --git a/tools/route_a/route_a.env.example b/tools/route_a/route_a.env.example index 130f33574d..6afecb5586 100644 --- a/tools/route_a/route_a.env.example +++ b/tools/route_a/route_a.env.example @@ -57,6 +57,9 @@ : "${RELEASE_WALL_SECONDS:=345600}" # 0 is the sole opt-out and restores --no-staging without a credential lookup. : "${ROUTE_A_STAGING=1}" +# 0 stops after the build, at ROUTE_A_BUILT.json. 1, like route_a.sh --certify, +# also certifies the build and runs the release-gate and publisher preflights. +: "${ROUTE_A_CERTIFY=0}" # Retain d122 whole-base dense national/state settings and the published run's # export-mass reference. Review the historical tail waiver against the new export. diff --git a/tools/route_a/route_a.sh b/tools/route_a/route_a.sh index 052ea4eda5..f8bcf98b3f 100755 --- a/tools/route_a/route_a.sh +++ b/tools/route_a/route_a.sh @@ -3,11 +3,18 @@ # --base-h5 release candidate on the committed labelled Ledger feed, then the # release-gate preflight and the publisher's offline --preflight-only check. # -# Builds a release candidate, runs offline preflights, and leaves publication -# to Max. Release staging telemetry is enabled unless ROUTE_A_STAGING=0. +# Builds the base and the release's build, and stops there: the build is +# written, checked by its own gates and recorded, and nothing is publishable. +# --certify (or ROUTE_A_CERTIFY=1) on the same RUN_ROOT then certifies that +# build (the release's post-export checks and its manifests, +# tools/certify_us_national_build.py), runs the offline preflights, and leaves +# publication to Max (microcosm#1585 item 11, PR 4a). Release and certification +# staging telemetry is enabled unless ROUTE_A_STAGING=0. # -# Usage: ./route_a.sh [--resolve] +# Usage: ./route_a.sh [--resolve|--certify] # --resolve fetches refs, hashes inputs, and checks commit pins; no stages run. +# --certify runs every stage, certification included; accepted stages are +# skipped, so after a build it certifies that build. # Settings come from ROUTE_A_ENV, defaulting to route_a.env beside this script. # Accepted stages are skipped on restart. Live supervisors are waited for; # failed attempts are moved aside. Releases use fresh IDs and shared caches. @@ -22,11 +29,13 @@ TOKEN_WRAPPER=$SCRIPT_DIR/with_hf_token.sh GIB=1073741824 MODE=run +CERTIFY_FLAG=0 case "${1:-}" in --resolve|--dry-run) MODE=resolve ;; + --certify) CERTIFY_FLAG=1 ;; "") ;; -h|--help) sed -n '2,/^set +x$/p' "$0"; exit 0 ;; - *) echo "usage: $0 [--resolve]" >&2; exit 64 ;; + *) echo "usage: $0 [--resolve|--certify]" >&2; exit 64 ;; esac [ -f "$ROUTE_A_ENV" ] || { echo "missing settings: $ROUTE_A_ENV (copy route_a.env.example)" >&2; exit 64; } @@ -39,6 +48,9 @@ esac : "${LADDER:?set LADDER}" "${SSI:?set SSI}" "${SCF:?set SCF}" : "${AGENT_SECRET:?set AGENT_SECRET}" "${ROUTE_A_STAGING=1}" "${RELEASE_RAM_GIB:=50}" case "$ROUTE_A_STAGING" in 0|1) ;; *) echo "ROUTE_A_STAGING must be 0 or 1" >&2; exit 64 ;; esac +: "${ROUTE_A_CERTIFY=0}" +[ "$CERTIFY_FLAG" = 1 ] && ROUTE_A_CERTIFY=1 +case "$ROUTE_A_CERTIFY" in 0|1) ;; *) echo "ROUTE_A_CERTIFY must be 0 or 1" >&2; exit 64 ;; esac mkdir -p "$RUN_ROOT" LOG=$RUN_ROOT/route_a.log : "${COMMIT:=}" "${REQUIRE_ON_MAIN:=1}" "${REQUIRE_SPM_ROLE:=1}" "${PREFLIGHT_COMMIT:=}" @@ -406,6 +418,26 @@ release_command() { ${staging[@]+"${staging[@]}"} ${extra[@]+"${extra[@]}"}) } +certify_command() { + # Certification stages where its build staged, in a run of its own, so it + # needs the release stage's staging credential. Without staging it runs as + # the release stage does: online, without the HF tokens (microcosm#1585 + # item 11, PR 4a). + local -a staging=() launcher=() + case "${ROUTE_A_STAGING-1}" in + 0) + staging=(--no-staging) + launcher=(/usr/bin/env -u HF_TOKEN -u HUGGING_FACE_HUB_TOKEN -u HUGGINGFACE_HUB_TOKEN -u HUGGING_FACE_TOKEN_MAX) + ;; + 1) + launcher=("$TOKEN_WRAPPER" "$AGENT_SECRET") + ;; + *) fail "ROUTE_A_STAGING must be 0 or 1" ;; + esac + CERTIFY_ARGV=("${launcher[@]}" "$W/.venv/bin/python" -B tools/certify_us_national_build.py + "$REL_OUT" ${staging[@]+"${staging[@]}"}) +} + # --------------------------------------------------------------------------- # Dry run. # --------------------------------------------------------------------------- @@ -447,7 +479,18 @@ log "route A driver start (pid $$)" C=$(git -C "$MAIN" rev-parse --verify --quiet "$COMMIT^{commit}") || fail "COMMIT $COMMIT not found after git fetch origin" PC=$(git -C "$MAIN" rev-parse --verify --quiet "${PREFLIGHT_COMMIT:-$C}^{commit}") || fail "PREFLIGHT_COMMIT $PREFLIGHT_COMMIT not found" refuse_bad_release_args -verify_inputs +# Certifying an accepted build reads none of the raw inputs, which the build +# verified when it ran, so they are not hashed again (microcosm#1585 item 11, +# PR 4a). +CERTIFY_ONLY=0 +if [ "$ROUTE_A_CERTIFY" = 1 ] && [ -f "$RUN_ROOT/run-${C:0:12}/release-sup/ACCEPTED" ]; then + CERTIFY_ONLY=1 +fi +if [ "$CERTIFY_ONLY" = 1 ]; then + log "inputs: not hashed again; the build at ${C:0:12} is accepted and certification reads none of them" +else + verify_inputs +fi check_commit "$C" "$PC" report_resolution "$C" [ ${#INPUT_PROBLEMS[@]} = 0 ] || fail "input problems (see above)" @@ -525,8 +568,10 @@ else *) log "overnight chain process gone without CHAIN DONE or FAIL; proceeding" ;; esac fi -verify_inputs -[ ${#INPUT_PROBLEMS[@]} = 0 ] || { report_resolution "$C"; fail "inputs changed while waiting"; } +if [ "$CERTIFY_ONLY" != 1 ]; then + verify_inputs + [ ${#INPUT_PROBLEMS[@]} = 0 ] || { report_resolution "$C"; fail "inputs changed while waiting"; } +fi # --- helpers for supervised stages --- avail_ram_bytes() { "$PY" -c 'import psutil; print(psutil.virtual_memory().available)'; } @@ -738,9 +783,54 @@ RID=$("$PY" -c 'import json,sys; a=json.load(open(sys.argv[1]))["argv"]; print(a || fail "cannot read the release id from release-sup/COMMAND.json" REL_OUT=$RUN/release-out/$RID # A national run writes its build into the national release's directory; -# $RID is the build ID (microcosm#1570). +# $RID is the build ID (microcosm#1570). The release tool builds and stops: +# its build record is what certification reads (microcosm#1585 item 11, PR 4a). REL_DIR=$REL_OUT/releases/microcosm-us-2024-national -[ -f "$REL_DIR/release_manifest.json" ] || fail "release accepted but $REL_DIR/release_manifest.json is missing" +[ -f "$REL_OUT/build_record.json" ] || fail "release accepted but $REL_OUT/build_record.json is missing" +log "build $RID at $REL_OUT" + +# --- 6b. Certification, only when asked (--certify or ROUTE_A_CERTIFY=1): the +# release's post-export checks on the written H5 and the manifests publication +# requires. Without it the run hands the build over and stops. --- +if [ "$ROUTE_A_CERTIFY" != 1 ]; then + "$PY" - "$RUN_ROOT/ROUTE_A_BUILT.json" "$C" "$PEUS" "$BASE_H5" "$BASE_SHA" "$RID" "$REL_OUT" \ + "$(cat "$RUN/preflight-base-sup/ACCEPTED" 2>/dev/null || echo BLOCKED)" <<'EOF' +import json, sys +(out, commit, peus, base_h5, base_sha, rid, rel_out, pfb) = sys.argv[1:] +json.dump({ + "state": "built", + "certified": False, + "published": False, + "build_commit": commit, + "policyengine_us": peus, + "base_h5": base_h5, + "base_sha256": base_sha, + "release_id": rid, + "build_dir": rel_out, + "build_record": rel_out + "/build_record.json", + "preflight_base": pfb, + "next": ( + "The build is written and checked by its own gates; it is not " + "publishable. To certify it, rerun this driver with --certify on the " + "same RUN_ROOT, or run tools/certify_us_national_build.py on build_dir." + ), +}, open(out, "w"), indent=1) +EOF + if [ "$PF_BLOCKED" = 1 ]; then + log "ROUTE A BUILT, BLOCKED: build $RID at $REL_OUT; the release-gate preflight needs the new-lineage mode; not certified; nothing published" + exit 4 + fi + log "ROUTE A BUILT: build $RID at $REL_OUT; not certified (rerun with --certify to certify it); nothing published" + exit 0 +fi +wait_prior_supervisor certify +if ! stage_done certify; then + certify_command + write_config certify 110 "$RELEASE_RAM_GIB" 45 "${CERTIFY_WALL_SECONDS:-345600}" 2000000 "$W" "$BUILD_ENV" -- \ + "${CERTIFY_ARGV[@]}" + run_stage certify 0 "$RELEASE_RAM_GIB" 45 "Certification scores the written H5; free disk beside the build." +fi +[ -f "$REL_DIR/release_manifest.json" ] || fail "certify accepted but $REL_DIR/release_manifest.json is missing" log "release candidate $RID at $REL_DIR" # --- 7. Release-gate preflight against the built release manifest. ---