Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<run_id>/` in the staging repository.
The build stops once its H5 and its own gates' verdicts are written, at
`<out>/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 <out>`, 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).

Expand Down
1 change: 1 addition & 0 deletions changelog.d/1585-us-build-then-certify.changed.md
Original file line number Diff line number Diff line change
@@ -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.
13 changes: 10 additions & 3 deletions docs/agent-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <repository> <release> <build>`, which sets
its `withdrawn` flag through the same release writer. Each US builder writes its build to
`releases/<release>/`; the national builder and the ACS package stage also
print both commands.
`releases/<release>/`. The national builder builds and stops at
`<out>/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
Expand Down Expand Up @@ -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 <out>` 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`,
Expand Down
96 changes: 94 additions & 2 deletions docs/us-release-build-rule.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
`<out>/releases/microcosm-us-2024-national/` and prints two commands:
`<out>/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 `<out>/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 <out>`) 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
Expand Down Expand Up @@ -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/<build id>/` for an earlier one. The probe reads the target
or `releases/<build id>/` 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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``."""

Expand Down Expand Up @@ -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"
)
Expand Down
133 changes: 133 additions & 0 deletions packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading