From 4d1933583a72901a621abc982f757094e8d9002a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:06:43 +0400 Subject: [PATCH 01/10] Test staging a Modal run's copied-back outputs (failing) A UK build run on Modal records its bundle as local_only, because the runner sets HF_HUB_OFFLINE. These tests describe the workstation side: after modal volume get, the re-stage command takes the stage's receipt (--modal-receipt), checks every output the manifest registers against it, and hands the bundle to the operator's emitter with the re-stage code. They cover the hand-over and its records, refusals of a directory whose outputs do not match the receipt or the manifest, a receipt of an unfinished stage, a directory outside the run's state, a second run on a landed bundle, a retry after a failed first attempt, and HF_HUB_OFFLINE left set on the workstation. The fake Hub, the re-stage emitter and the output-editing helpers move to test_support so both UK test modules share them. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/uk/test_uk_full_build_cli.py | 36 -- .../uk/test_uk_modal_copy_back_staging.py | 398 ++++++++++++++++++ .../microcosm_build/modal_copy_back.py | 83 ++++ .../microcosm_build/uk_full_build_cli.py | 41 ++ 4 files changed, 522 insertions(+), 36 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py create mode 100644 test_support/microcosm_build/modal_copy_back.py diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_full_build_cli.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_full_build_cli.py index b962bf644d..494f792ca9 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_full_build_cli.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_full_build_cli.py @@ -1295,23 +1295,6 @@ def _drive_epochs(args, telemetry, epochs: int = 2) -> None: ) -def _remote_hub(monkeypatch, client_options=None, **kwargs): - """One fake Hub for the run files and the bundle the build's emitter commits.""" - from test_support.microcosm_build.telemetry import share_fake_hub - from test_support.microcosm_build.uk_rowwise_candidate import _FakeHub - - hub = _FakeHub(**kwargs) - share_fake_hub(monkeypatch, hub, **(client_options or {})) - return hub - - -def _bundle_emitter_for(hub): - """The re-stage tool's own short-lived emitter, committing to ``hub``.""" - from test_support.microcosm_build.emitter import FakeEmitterClient - - return lambda: FakeEmitterClient(hub_files=hub.files, hub_api=hub) - - def test_no_staging_records_both_opt_outs(tmp_path, monkeypatch): pytest.importorskip("tables") status, out = run_dense_main(tmp_path, monkeypatch, staging="--no-staging") @@ -1948,25 +1931,6 @@ def _landed_dense_build(tmp_path, monkeypatch): return hub, out -def _edit_an_output(out): - """Change a CSV output after landing, keeping the manifest consistent.""" - manifest_path = out / cli.MANIFEST_FILENAME - manifest = json.loads(manifest_path.read_text()) - key, entry = next( - (key, entry) - for key, entry in manifest["outputs"].items() - if entry and str(entry["path"]).endswith(".csv") - ) - path = out / Path(entry["path"]).name - path.write_bytes(path.read_bytes() + b"edited,after,landing\n") - manifest["outputs"][key] = { - **entry, - "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), - "bytes": path.stat().st_size, - } - manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True)) - - @pytest.mark.parametrize( ("case", "expected_status"), [ diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py new file mode 100644 index 0000000000..e2823979aa --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py @@ -0,0 +1,398 @@ +"""Staging a UK build's outputs once they are copied back from a Modal run. + +The Modal runner runs every tool with ``HF_HUB_OFFLINE=1``, so a build there +uploads nothing: it verifies its bundle, writes the sidecars and records the +bundle as ``local_only``. After ``modal volume get`` copies the run back, +``tools/stage_uk_rowwise_candidate.py --modal-receipt`` checks every output +the manifest registers against the run's receipt, then hands the bundle to the +operator's emitter with the code that re-stages a local build that kept its +bundle local. +""" + +from __future__ import annotations + +import hashlib +import json +import shutil +from pathlib import Path + +import pytest + +from microcosm.build import staging_dataset +from test_support.microcosm_build.emitter import FakeEmitterClient, FakeHandoverQueue +from test_support.microcosm_build.modal_copy_back import ( + copy_back, + rewrite_receipt, + write_receipt, +) +from test_support.microcosm_build.uk_full_build_cli import ( + STEM, + _edit_an_output, + _remote_hub, + load_tool, + run_dense_main, + single_run_id, +) + +PRIVATE_REPOSITORY = "policyengine/populace-uk-private" + + +def _modal_build(tmp_path, monkeypatch): + """A dense build run as the Modal runner runs it, then copied back. + + Returns the Hub, the copied-back run directory and the stage's receipt. + """ + pytest.importorskip("tables") + hub = _remote_hub(monkeypatch) + monkeypatch.setenv("HF_HUB_OFFLINE", "1") + status, out = run_dense_main(tmp_path, monkeypatch, staging=None) + assert status == 0 + monkeypatch.delenv("HF_HUB_OFFLINE") + assert hub.paths(PRIVATE_REPOSITORY) == [] + copied, receipt = copy_back(out, tmp_path / "modal-runs") + return hub, copied, receipt + + +def _workstation_emitters(monkeypatch, stager, **options): + """Every emitter the command starts on the workstation, in order.""" + started: list[FakeEmitterClient] = [] + + def start(): + started.append(FakeEmitterClient(**options)) + return started[-1] + + monkeypatch.setattr(stager, "_start_bundle_emitter", start) + return started + + +def _staging_argv(copied: Path, receipt: Path, *extra: str) -> list[str]: + return [ + "--run-dir", + str(copied), + "--modal-receipt", + str(receipt), + "--wait-seconds", + "60", + *extra, + ] + + +def _manifest(copied: Path) -> dict: + stager = load_tool("stage_uk_rowwise_candidate") + return json.loads((copied / stager.MANIFEST_FILENAME).read_text()) + + +def _files(directory: Path) -> dict[str, bytes]: + return { + path.relative_to(directory).as_posix(): path.read_bytes() + for path in sorted(directory.rglob("*")) + if path.is_file() + } + + +def test_copied_back_outputs_are_handed_over_as_a_local_build_is_restaged( + tmp_path, monkeypatch, capsys +): + """The workstation's emitter stages the bundle the Modal build verified, + under the build's own run id, and its receipt becomes the manifest's + record exactly as when a local build is re-staged.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + at_build = _manifest(copied)["staged_dataset"] + assert (at_build["mode"], at_build["status"]) == ("local_only", "skipped") + stager = load_tool("stage_uk_rowwise_candidate") + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub + ) + handed_over = [] + shared_stage_bundle = stager.stage_bundle + + def stage_bundle(bundle, **options): + handed_over.append((bundle, options)) + return shared_stage_bundle(bundle, **options) + + monkeypatch.setattr(stager, "stage_bundle", stage_bundle) + capsys.readouterr() + + assert stager.main(_staging_argv(copied, receipt)) == 0 + + # One emitter of the command's own, closed when it finished. + (client,) = started + assert client.closed + (request,) = client.bundle_requests + roles = {item.name: item.role for item in request.files} + assert roles[f"{STEM}.h5"] == "dataset" + assert roles[stager.MANIFEST_FILENAME] == "build_manifest" + assert roles["staged_manifest.json"] == "staged_manifest" + assert roles["sha256sums.txt"] == "checksums" + # Through the re-stage command's own hand-over. + ((bundle, options),) = handed_over + assert bundle.run_dir == copied.resolve() + assert options["repository"] == PRIVATE_REPOSITORY + assert options["wait_seconds"] == 60.0 + run_id = single_run_id(copied) + manifest = _manifest(copied) + staged = manifest["staged_dataset"] + assert staged == staging_dataset.validate_staged_dataset_delivery(staged) + assert (staged["status"], staged["error_code"]) == ("uploaded", None) + assert staged["revision"] == hub.sha + assert (staged["repository"], staged["prefix"], staged["run_id"]) == ( + PRIVATE_REPOSITORY, + f"staged/{run_id}", + run_id, + ) + assert staged["files"] == bundle.digests() + assert manifest["staged_dataset_at_build"] == { + "mode": "local_only", + "status": "skipped", + "error_code": None, + } + record = manifest["staged_dataset_handover"] + assert record["run_dir"] == str(copied.resolve()) + assert record["repository"] == PRIVATE_REPOSITORY + captured = capsys.readouterr() + assert json.loads(captured.out) == staged + # The Modal build's staging run and Logbook row keep what it recorded. + assert "still records skipped" in captured.err + assert "phase dataset_stage_skipped" in captured.err + assert len(hub.commits) == 1 + assert sorted(hub.paths(PRIVATE_REPOSITORY)) == sorted( + f"staged/{run_id}/{name}" for name in roles + ) + for line in (copied / "sha256sums.txt").read_text().splitlines(): + digest, name = line.split(" ") + assert hashlib.sha256((copied / name).read_bytes()).hexdigest() == digest + + +def _edit_after_copy_back(copied, run_root, receipt): + _edit_an_output(copied) + + +def _change_without_the_manifest(copied, run_root, receipt): + dataset = copied / f"{STEM}.h5" + dataset.write_bytes(dataset.read_bytes() + b"\0") + + +def _drop_the_dataset_from_the_receipt(copied, run_root, receipt): + rewrite_receipt( + receipt, + lambda content: content.update( + outputs=[ + item + for item in content["outputs"] + if not item["path"].endswith(f"{STEM}.h5") + ] + ), + ) + + +def _unfinished_stage(copied, run_root, receipt): + write_receipt(run_root, status="FAILED") + + +def _stage_stopped_at_its_budget(copied, run_root, receipt): + write_receipt(run_root, status="FAILED", stopped_at_budget=True) + + +def _another_kind_of_file(copied, run_root, receipt): + receipt.write_text(json.dumps({"schema": "microcosm-modal-us-stage-plan/1"})) + + +@pytest.mark.parametrize( + ("change", "refusal"), + [ + pytest.param( + _edit_after_copy_back, + r"is not the file the Modal run wrote", + id="an output edited after the copy-back", + ), + pytest.param( + _change_without_the_manifest, + r"does not match its manifest digest", + id="an output that no longer matches the manifest", + ), + pytest.param( + _drop_the_dataset_from_the_receipt, + rf"the receipt lists no out/{STEM}\.h5", + id="an output the receipt does not list", + ), + pytest.param( + _unfinished_stage, + r"status is 'FAILED', not 'COMPLETED'", + id="a stage that did not finish", + ), + pytest.param( + _stage_stopped_at_its_budget, + r"stopped at its budget", + id="a stage stopped at its budget", + ), + pytest.param( + _another_kind_of_file, + r"is not a microcosm-modal-us-stage-receipt/1", + id="a file that is not a receipt", + ), + ], +) +def test_a_copied_back_directory_that_does_not_verify_is_refused( + tmp_path, monkeypatch, change, refusal +): + """Nothing is handed over, no emitter is started and no file changes + unless every output the manifest registers is the file the finished + stage wrote.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + change(copied, receipt.parent.parent, receipt) + before = _files(copied) + stager = load_tool("stage_uk_rowwise_candidate") + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub + ) + + with pytest.raises(SystemExit, match=refusal): + stager.main(_staging_argv(copied, receipt)) + + assert started == [] + assert _files(copied) == before + assert hub.paths(PRIVATE_REPOSITORY) == [] + + +def test_a_directory_outside_the_receipts_state_is_refused(tmp_path, monkeypatch): + """The receipt describes the run's copied-back state directory, beside + its receipts directory unless ``--modal-state-root`` names it; a copy of + the run directory anywhere else is not what it describes.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + elsewhere = tmp_path / "elsewhere" / "out" + shutil.copytree(copied, elsewhere) + stager = load_tool("stage_uk_rowwise_candidate") + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub + ) + + with pytest.raises(SystemExit, match=r"is not inside the Modal run's state"): + stager.main(_staging_argv(elsewhere, receipt)) + with pytest.raises(SystemExit, match=rf"the receipt lists no {STEM}\.h5"): + stager.main(_staging_argv(copied, receipt, "--modal-state-root", str(copied))) + + assert started == [] + assert hub.paths(PRIVATE_REPOSITORY) == [] + # Naming the state directory itself is the default's equivalent. + assert ( + stager.main( + _staging_argv( + copied, + receipt, + "--modal-state-root", + str(receipt.parent.parent / "state"), + ) + ) + == 0 + ) + + +def test_the_modal_state_root_needs_a_receipt(): + stager = load_tool("stage_uk_rowwise_candidate") + with pytest.raises(SystemExit): + stager._parse_args(["--run-dir", "run", "--modal-state-root", "state"]) + parsed = stager._parse_args(["--run-dir", "run", "--modal-receipt", "receipt.json"]) + assert parsed.modal_receipt == Path("receipt.json") + assert parsed.modal_state_root is None + + +def test_a_copied_back_bundle_that_landed_is_not_handed_over_again( + tmp_path, monkeypatch, capsys +): + """Staging rewrites the manifest and ``sha256sums.txt``, so they no longer + match the receipt; the outputs still do, so a second run with the receipt, + and a re-stage without it, both find the record and change nothing.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + stager = load_tool("stage_uk_rowwise_candidate") + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub + ) + assert stager.main(_staging_argv(copied, receipt)) == 0 + listed = { + item["path"]: item["sha256"] + for item in json.loads(receipt.read_text())["outputs"] + } + manifest_path = copied / stager.MANIFEST_FILENAME + assert ( + hashlib.sha256(manifest_path.read_bytes()).hexdigest() + != listed[f"out/{stager.MANIFEST_FILENAME}"] + ) + landed = _files(copied) + + for argv in ( + _staging_argv(copied, receipt), + ["--run-dir", str(copied), "--wait-seconds", "60"], + ): + capsys.readouterr() + assert stager.main(argv) == 0 + assert "nothing to do" in capsys.readouterr().err + + assert _files(copied) == landed + assert len(hub.commits) == 1 + assert sum(len(client.bundle_requests) for client in started) == 1 + + +def test_a_copied_back_bundle_whose_first_hand_over_failed_is_staged_again( + tmp_path, monkeypatch, capsys +): + """The operator's first attempt finds no credential; the emitter keeps the + bundle queued, and the next attempt with the receipt records it landed. + The Modal build's own record stays the one the note names.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + queue = FakeHandoverQueue() + stager = load_tool("stage_uk_rowwise_candidate") + _workstation_emitters(monkeypatch, stager, hub_files=hub.files, queue=queue) + assert stager.main(_staging_argv(copied, receipt, "--wait-seconds", "0")) == 1 + manifest = _manifest(copied) + assert manifest["staged_dataset"]["error_code"] == "CREDENTIAL_MISSING" + assert manifest["staged_dataset_at_build"]["status"] == "skipped" + _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub, queue=queue + ) + capsys.readouterr() + + assert stager.main(_staging_argv(copied, receipt)) == 0 + + manifest = _manifest(copied) + assert manifest["staged_dataset"]["status"] == "uploaded" + assert manifest["staged_dataset"]["revision"] == hub.sha + assert manifest["staged_dataset_at_build"]["status"] == "skipped" + err = capsys.readouterr().err + assert "still records skipped" in err + assert "CREDENTIAL_MISSING" not in err + assert len(hub.commits) == 1 + + +def test_hf_hub_offline_on_the_workstation_stages_nothing( + tmp_path, monkeypatch, capsys +): + """``HF_HUB_OFFLINE`` left set on the workstation, as the runner sets it + for every tool, means the emitter could never upload: the command refuses + before it starts one. ``--local-only`` still checks the receipt and keeps + the bundle local.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + before = _files(copied) + stager = load_tool("stage_uk_rowwise_candidate") + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub + ) + monkeypatch.setenv("HF_HUB_OFFLINE", "1") + + with pytest.raises(SystemExit, match="HF_HUB_OFFLINE is set"): + stager.main(_staging_argv(copied, receipt)) + assert _files(copied) == before + + capsys.readouterr() + assert stager.main(_staging_argv(copied, receipt, "--local-only")) == 0 + staged = _manifest(copied)["staged_dataset"] + assert (staged["mode"], staged["status"], staged["repository"]) == ( + "local_only", + "skipped", + None, + ) + _edit_an_output(copied) + with pytest.raises(SystemExit, match="is not the file the Modal run wrote"): + stager.main(_staging_argv(copied, receipt, "--local-only")) + + assert started == [] + assert hub.paths(PRIVATE_REPOSITORY) == [] diff --git a/test_support/microcosm_build/modal_copy_back.py b/test_support/microcosm_build/modal_copy_back.py new file mode 100644 index 0000000000..b8a30faa76 --- /dev/null +++ b/test_support/microcosm_build/modal_copy_back.py @@ -0,0 +1,83 @@ +"""A run directory as ``modal volume get`` copies it back from a Modal run. + +The Modal runner (``tools/modal_us_stage.py``) mirrors a stage's state +directory to ``runs//state/`` on its runs volume and writes the +stage's receipt to ``runs//receipts/``. ``modal volume get +microcosm-us-stage-runs runs/ ./modal-runs/`` copies both back, as +``modal-runs//state/`` and ``modal-runs//receipts/``. The +receipts written here list every state file with its SHA-256 and size, as the +runner's do (``push_state``), and carry the fields the re-stage command reads. +""" + +from __future__ import annotations + +import json +import shutil +from collections.abc import Callable +from pathlib import Path +from typing import Any + +from test_support.microcosm_build.us_modal_stage_plan_tool import plan_lib + +MODAL_RUN_ID = "uk-rowwise-modal-20261104" +MODAL_STAGE = "build" + + +def copy_back( + run_directory: Path, + modal_runs: Path, + *, + run_id: str = MODAL_RUN_ID, + name: str = "out", +) -> tuple[Path, Path]: + """Move a finished run directory into a copied-back Modal run. + + The directory becomes ``//state/``, as a tool + run on Modal leaves its output directory in the stage's state, and the + stage's completed receipt describes the state. Returns the copied-back + directory and the receipt's path. + """ + run_root = modal_runs / run_id + state = run_root / "state" + state.mkdir(parents=True) + copied = state / name + shutil.move(str(run_directory), str(copied)) + return copied, write_receipt(run_root, run_id=run_id) + + +def write_receipt( + run_root: Path, + *, + run_id: str = MODAL_RUN_ID, + status: str = "COMPLETED", + stopped_at_budget: bool = False, +) -> Path: + """Write the receipt of a stage whose state is ``/state``.""" + state = run_root / "state" + outputs = [] + for relative in plan_lib.tree_listing(state): + sha256, size = plan_lib.sha256_file(state / relative) + outputs.append({"path": relative, "bytes": size, "sha256": sha256}) + receipt = { + "schema": plan_lib.RECEIPT_SCHEMA, + "status": status, + "stage": MODAL_STAGE, + "run_id": run_id, + "returncode": 0 if status == "COMPLETED" else 1, + "stopped_at_budget": stopped_at_budget, + "finished_at": "2026-11-04T12:00:00Z", + "outputs": outputs, + "outputs_not_mirrored": [], + } + receipts = run_root / "receipts" + receipts.mkdir(exist_ok=True) + path = receipts / f"{MODAL_STAGE}-2026-11-04T110000Z.json" + path.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8") + return path + + +def rewrite_receipt(path: Path, change: Callable[[dict[str, Any]], None]) -> None: + """Apply ``change`` to the receipt at ``path`` and write it back.""" + receipt = json.loads(path.read_text(encoding="utf-8")) + change(receipt) + path.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8") diff --git a/test_support/microcosm_build/uk_full_build_cli.py b/test_support/microcosm_build/uk_full_build_cli.py index ae044786d3..263b3ebebe 100644 --- a/test_support/microcosm_build/uk_full_build_cli.py +++ b/test_support/microcosm_build/uk_full_build_cli.py @@ -1084,4 +1084,45 @@ def prepared( ) +def _remote_hub(monkeypatch, client_options=None, **kwargs): + """One fake Hub for the run files and the bundle the build's emitter commits.""" + from test_support.microcosm_build.telemetry import share_fake_hub + from test_support.microcosm_build.uk_rowwise_candidate import _FakeHub + + hub = _FakeHub(**kwargs) + share_fake_hub(monkeypatch, hub, **(client_options or {})) + return hub + + +def _bundle_emitter_for(hub): + """The re-stage tool's own short-lived emitter, committing to ``hub``.""" + from test_support.microcosm_build.emitter import FakeEmitterClient + + return lambda: FakeEmitterClient(hub_files=hub.files, hub_api=hub) + + +def _edit_an_output(out): + """Change a CSV output, keeping the manifest consistent. + + The directory still verifies against its own manifest, so only a record + of the bytes from elsewhere (a landed bundle, a Modal run's receipt) can + tell that it changed. + """ + manifest_path = out / cli.MANIFEST_FILENAME + manifest = json.loads(manifest_path.read_text()) + key, entry = next( + (key, entry) + for key, entry in manifest["outputs"].items() + if entry and str(entry["path"]).endswith(".csv") + ) + path = out / Path(entry["path"]).name + path.write_bytes(path.read_bytes() + b"edited,after,landing\n") + manifest["outputs"][key] = { + **entry, + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "bytes": path.stat().st_size, + } + manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True)) + + __all__ = [name for name in globals() if not name.startswith("__")] From eac8c18ecc234dc2d0010925c3aec451d1384838 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:15:18 +0400 Subject: [PATCH 02/10] Stage a Modal run's copied-back outputs with the re-stage command A UK build run on Modal records its bundle as local_only, because the runner sets HF_HUB_OFFLINE for every tool. After modal volume get, --modal-receipt names the stage's receipt: the command refuses a receipt of a stage that did not finish, a directory outside the run's copied-back state directory, and any registered output whose SHA-256 or size differs from the receipt's, before it starts an emitter. A directory that matches is staged by the existing re-stage code, so its records, retries and landed-bundle handling are a local directory's. The manifest and sidecars are not compared, because staging rewrites them. An output that does not match its manifest digest is now an error message rather than a traceback. One installed-emitter test runs the command against the stand-in Hub. The UK staging guide and the Modal runbook describe the command; the runbook also says why no US program writes a staged bundle yet. Co-Authored-By: Claude Opus 5.5 --- .../1498-modal-copied-back-staging.added.md | 1 + docs/uk-staging-operations.md | 37 ++++- docs/us-modal-stage-runbook.md | 16 +++ .../uk/test_uk_modal_copy_back_staging.py | 15 +- .../shared/test_installed_emitter_staging.py | 63 ++++++++- tools/stage_uk_rowwise_candidate.py | 133 ++++++++++++++++-- 6 files changed, 242 insertions(+), 23 deletions(-) create mode 100644 changelog.d/1498-modal-copied-back-staging.added.md diff --git a/changelog.d/1498-modal-copied-back-staging.added.md b/changelog.d/1498-modal-copied-back-staging.added.md new file mode 100644 index 0000000000..c54417b069 --- /dev/null +++ b/changelog.d/1498-modal-copied-back-staging.added.md @@ -0,0 +1 @@ +`tools/stage_uk_rowwise_candidate.py --modal-receipt ` stages a UK run directory copied back from a Modal run with `modal volume get`. Before it starts an emitter, it checks that the receipt is of a stage that finished (`COMPLETED`, not stopped at its budget), that the directory is inside the run's copied-back state directory (`state/` beside the receipt's `receipts/` directory, or `--modal-state-root`), and that every output the manifest registers is in the receipt with the same SHA-256 and size; it refuses the directory otherwise. It then hands the bundle over with the re-stage command's existing code, so the records, retries and landed-bundle handling are those of a directory built on the workstation. The command now reports an output that does not match its manifest digest as an error message instead of a traceback. diff --git a/docs/uk-staging-operations.md b/docs/uk-staging-operations.md index 4ae2b75cd9..71f8f4fbcb 100644 --- a/docs/uk-staging-operations.md +++ b/docs/uk-staging-operations.md @@ -383,7 +383,42 @@ chained to the next row). So the dashboard keeps showing such a run without its bundle. An identical remote bundle the manifest does not know about is recorded as `already_staged` with the bundle's own commit; a different bundle -under the same run id is refused (`REMOTE_DIFFERS`). Fetch a bundle for a scorecard, an evaluation leg or the +under the same run id is refused (`REMOTE_DIFFERS`). + +A build run on Modal stages nothing from its container: the runner sets +`HF_HUB_OFFLINE=1` for every tool, so the build records its bundle as +`local_only` (see above). After `modal volume get` has copied the run back +([the Modal runbook](us-modal-stage-runbook.md#commands), step 5), stage it +from the workstation, with your own emitter and Hub credential, by naming the +stage's receipt: + +```bash +uv run python tools/stage_uk_rowwise_candidate.py \ + --run-dir ./modal-runs//state/ \ + --modal-receipt ./modal-runs//receipts/-.json +``` + +Before it starts an emitter, the command checks that the receipt is of a +stage that finished (`COMPLETED`, and not stopped at its budget) and that +every output the manifest registers is in it, at its path under the run's +state directory, with the same SHA-256 and size. It refuses the directory +otherwise, and when the directory is not inside that state directory, which +is `state/` beside the receipt's `receipts/` directory unless +`--modal-state-root` names another. The manifest, `staged_manifest.json` and +`sha256sums.txt` are not compared, because staging rewrites them. Then it +stages the directory as above, under the build's own run id: the hand-over, +the records, a re-stage after a failed attempt and a second run on a landed +bundle work as they do for a directory built on the workstation. Unset +`HF_HUB_OFFLINE` first if your shell sets it: the command refuses to stage +while it is set, and with `--local-only` it checks the receipt and rewrites +the sidecars only. Nothing here submits the bundle to the collector: the +command's emitter runs its Hugging Face module only, and builds do not submit +artifacts to the collector's artifact intake yet +(PolicyEngine/microcosm-collector#12). The Modal runner's registered programs +are all US builds today (`tools/modal_us_stage_plan.py`), and none of them +writes a staged-dataset bundle. + +Fetch a bundle for a scorecard, an evaluation leg or the dashboard's local-directory mode with: ```bash diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index b2060d62f0..32690cd6df 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -288,6 +288,14 @@ python3 tools/modal_us_stage_plan.py verify-receipt \ --state-root ./modal-runs//state ``` +A run directory whose manifest registers a staged-dataset bundle (a UK +rowwise build's `rowwise_candidate_manifest.json`) is staged from the +workstation after step 5, with the operator's own emitter and Hub credential: +`tools/stage_uk_rowwise_candidate.py --modal-receipt` checks its outputs +against the receipt and hands the bundle over as for a local build (see +[Staged datasets](uk-staging-operations.md#staged-datasets)). No program +registered here writes such a bundle yet; see "What this does not cover yet". + To prove the run path on a new commit or workspace for well under a cent, run `docs/us-modal-stage-smoke-plan.json` (tool `runner-smoke`). It is an inline script, so it needs no file in the pinned tree. It imports the synced @@ -1451,6 +1459,14 @@ hold digests, sizes and paths, never file contents. placement avoids preemption (see "Preemption and restarts"). The heavy class sets a memory request but no hard limit. What Modal does with a container killed for memory has not been observed here. +- **Staging a US build's datasets.** Only UK builds write a staged-dataset + bundle (their manifest's `outputs`, staged under `staged//` on a + private repository), and the copied-back staging command reads only their + manifest. The `package` stage writes a release directory with its own + `release_manifest.json` (an `artifacts` list) and `sha256sums.txt`, which is + also the name of the bundle's checksum file. A US bundle needs a private + repository, a manifest that registers its outputs, and a command that reads + it; none exists yet. - **Certification.** A receipt proves which bytes a stage produced. It does not certify a release. Preflight (`tools/preflight_us_release_gates.py`) and certification still run on the output as before. diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py index e2823979aa..cb2ca2df25 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py @@ -202,7 +202,7 @@ def _another_kind_of_file(copied, run_root, receipt): [ pytest.param( _edit_after_copy_back, - r"is not the file the Modal run wrote", + r"is not the file the Modal stage wrote", id="an output edited after the copy-back", ), pytest.param( @@ -335,14 +335,16 @@ def test_a_copied_back_bundle_that_landed_is_not_handed_over_again( def test_a_copied_back_bundle_whose_first_hand_over_failed_is_staged_again( tmp_path, monkeypatch, capsys ): - """The operator's first attempt finds no credential; the emitter keeps the - bundle queued, and the next attempt with the receipt records it landed. + """The operator's first attempt finds no credential, and the emitter keeps + the bundle queued. The next emitter on the workstation uploads it, so the + next attempt reads the earlier hand-over's receipt and records it as + ``already_staged`` with its commit, as for a local build's queued bundle. The Modal build's own record stays the one the note names.""" hub, copied, receipt = _modal_build(tmp_path, monkeypatch) queue = FakeHandoverQueue() stager = load_tool("stage_uk_rowwise_candidate") _workstation_emitters(monkeypatch, stager, hub_files=hub.files, queue=queue) - assert stager.main(_staging_argv(copied, receipt, "--wait-seconds", "0")) == 1 + assert stager.main(_staging_argv(copied, receipt)) == 1 manifest = _manifest(copied) assert manifest["staged_dataset"]["error_code"] == "CREDENTIAL_MISSING" assert manifest["staged_dataset_at_build"]["status"] == "skipped" @@ -354,10 +356,11 @@ def test_a_copied_back_bundle_whose_first_hand_over_failed_is_staged_again( assert stager.main(_staging_argv(copied, receipt)) == 0 manifest = _manifest(copied) - assert manifest["staged_dataset"]["status"] == "uploaded" + assert manifest["staged_dataset"]["status"] == "already_staged" assert manifest["staged_dataset"]["revision"] == hub.sha assert manifest["staged_dataset_at_build"]["status"] == "skipped" err = capsys.readouterr().err + assert "now records the bundle as already_staged" in err assert "still records skipped" in err assert "CREDENTIAL_MISSING" not in err assert len(hub.commits) == 1 @@ -391,7 +394,7 @@ def test_hf_hub_offline_on_the_workstation_stages_nothing( None, ) _edit_an_output(copied) - with pytest.raises(SystemExit, match="is not the file the Modal run wrote"): + with pytest.raises(SystemExit, match="is not the file the Modal stage wrote"): stager.main(_staging_argv(copied, receipt, "--local-only")) assert started == [] diff --git a/packages/microcosm-build/tests/installed_emitter/shared/test_installed_emitter_staging.py b/packages/microcosm-build/tests/installed_emitter/shared/test_installed_emitter_staging.py index e057f20881..96fd868d60 100644 --- a/packages/microcosm-build/tests/installed_emitter/shared/test_installed_emitter_staging.py +++ b/packages/microcosm-build/tests/installed_emitter/shared/test_installed_emitter_staging.py @@ -47,7 +47,9 @@ OutdatedEmitterClient, start_bundle_emitter, ) +from test_support.microcosm_build.modal_copy_back import copy_back from test_support.microcosm_build.stand_in_hub import CommitAttempt, StandInHub +from test_support.microcosm_build.uk_full_build_cli import load_tool REPOSITORY = "microcosm-tests/staged-bundles" RUN_ID = "installed-emitter-20261102T000000Z" @@ -100,7 +102,9 @@ def _sha256(content: bytes) -> str: return hashlib.sha256(content).hexdigest() -def _write_bundle(root: Path, *, dataset_bytes: int = 4096) -> StagedDatasetBundle: +def _write_bundle( + root: Path, *, dataset_bytes: int = 4096, manifest_name: str = MANIFEST +) -> StagedDatasetBundle: """A finished run's directory: a dataset, its diagnostics and a manifest. The bundle has every role a build hands over: ``dataset`` and @@ -133,9 +137,9 @@ def _write_bundle(root: Path, *, dataset_bytes: int = 4096) -> StagedDatasetBund "releasable": False, "outputs": outputs, } - (run_directory / MANIFEST).write_text(json.dumps(manifest, indent=2)) + (run_directory / manifest_name).write_text(json.dumps(manifest, indent=2)) bundle = StagedDatasetBundle.from_manifest( - run_directory, run_id=RUN_ID, manifest_name=MANIFEST + run_directory, run_id=RUN_ID, manifest_name=manifest_name ) write_sidecars(bundle, repository=REPOSITORY) return bundle @@ -379,6 +383,59 @@ def test_the_installed_emitter_uploads_the_bundle_in_one_commit( assert handover.may_rewrite(name) +def test_a_modal_runs_copied_back_outputs_are_staged_by_the_re_stage_command( + tmp_path: Path, stand_in_hub: StandInHub, installed_emitter: InstalledEmitter +) -> None: + """After ``modal volume get``, the UK re-stage command checks the outputs + against the stage's receipt, starts the installed emitter as it does for a + local directory, and records the commit the emitter made of them.""" + stager = load_tool("stage_uk_rowwise_candidate") + bundle = _write_bundle(tmp_path, manifest_name=stager.MANIFEST_FILENAME) + copied, receipt = copy_back(bundle.run_dir, tmp_path / "modal-runs") + + status = stager.main( + [ + "--run-dir", + str(copied), + "--repo-id", + REPOSITORY, + "--run-id", + RUN_ID, + "--modal-receipt", + str(receipt), + "--wait-seconds", + str(UPLOAD_WAIT_SECONDS), + ] + ) + + assert status == 0 + assert len(installed_emitter.processes) == 1 + (commit,) = stand_in_hub.commits(REPOSITORY) + names = { + DATASET, + CALIBRATION_DIAGNOSTICS, + stager.MANIFEST_FILENAME, + STAGED_MANIFEST_FILENAME, + SHA256SUMS_FILENAME, + } + assert set(commit.added) == {f"{PREFIX}/{name}" for name in names} + listed = { + item["path"]: item["sha256"] + for item in json.loads(receipt.read_text())["outputs"] + } + for name in (DATASET, CALIBRATION_DIAGNOSTICS): + assert _sha256(commit.added[f"{PREFIX}/{name}"]) == listed[f"out/{name}"] + manifest = json.loads((copied / stager.MANIFEST_FILENAME).read_text()) + staged = manifest["staged_dataset"] + assert (staged["status"], staged["error_code"]) == ("uploaded", None) + assert (staged["repository"], staged["prefix"], staged["revision"]) == ( + REPOSITORY, + PREFIX, + commit.oid, + ) + assert manifest["staged_dataset_handover"]["run_dir"] == str(copied.resolve()) + + def test_a_commit_on_a_moved_head_is_refused_then_made_on_the_new_head( tmp_path: Path, stand_in_hub: StandInHub, installed_emitter: InstalledEmitter ) -> None: diff --git a/tools/stage_uk_rowwise_candidate.py b/tools/stage_uk_rowwise_candidate.py index 153ee81fef..1ee70d7280 100644 --- a/tools/stage_uk_rowwise_candidate.py +++ b/tools/stage_uk_rowwise_candidate.py @@ -33,6 +33,15 @@ keeps the manifest's records and says so. A directory whose bytes differ from the remote bundle is otherwise refused. +A build run on Modal stages nothing from its container (the runner sets +``HF_HUB_OFFLINE``, so the build records its bundle as ``local_only``). Once +``modal volume get`` has copied the run back, ``--modal-receipt`` names the +stage's receipt: every output the manifest registers must be in it, at its +path under the run's state directory, with the same SHA-256 and size, and the +receipt must be of a stage that finished. Otherwise the command refuses before +it starts an emitter; when they match, it stages the directory as above. The +manifest and the sidecars are not compared, because staging rewrites them. + Staging is not publication: ``releases/`` and ``latest.json`` are untouched. """ @@ -45,7 +54,7 @@ import os import sys from collections.abc import Mapping -from pathlib import Path +from pathlib import Path, PurePosixPath from typing import Any from microcosm.build.staging_dataset import ( @@ -82,6 +91,13 @@ UK_STAGED_DATASET_REPOSITORY, ) +# The Modal runner's receipt format lives beside this command, in tools/. +_TOOLS = Path(__file__).resolve().parent +if str(_TOOLS) not in sys.path: + sys.path.insert(0, str(_TOOLS)) + +import modal_us_stage_plan as modal_plan # noqa: E402 + MANIFEST_FILENAME = "rowwise_candidate_manifest.json" @@ -140,7 +156,28 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "emitter started on this machine retries it." ), ) - return parser.parse_args(argv) + parser.add_argument( + "--modal-receipt", + type=Path, + help=( + "The receipt of the Modal stage that wrote --run-dir, as " + "`modal volume get` copies it back " + "(modal-runs//receipts/-.json). Every output the " + "manifest registers must be in it with the same SHA-256 and size." + ), + ) + parser.add_argument( + "--modal-state-root", + type=Path, + help=( + "The copied-back state directory the receipt describes (default: " + "the state directory beside the receipt's directory)." + ), + ) + args = parser.parse_args(argv) + if args.modal_state_root is not None and args.modal_receipt is None: + parser.error("--modal-state-root needs --modal-receipt") + return args def _default_run_id(run_dir: Path, manifest: dict) -> str: @@ -176,17 +213,30 @@ def main(argv: list[str] | None = None) -> int: repository = None if args.local_only else str(args.repo_id).strip() if repository == "": raise SystemExit("error: --repo-id must be non-empty unless --local-only") - bundle = StagedDatasetBundle.from_manifest( - run_dir, - run_id=run_id, - manifest_name=MANIFEST_FILENAME, - extra_summary={ - "dataset_households": (manifest.get("parameters") or {}).get( - "dataset_households" - ), - "release_posture": manifest.get("release_posture"), - }, - ) + try: + bundle = StagedDatasetBundle.from_manifest( + run_dir, + run_id=run_id, + manifest_name=MANIFEST_FILENAME, + extra_summary={ + "dataset_households": (manifest.get("parameters") or {}).get( + "dataset_households" + ), + "release_posture": manifest.get("release_posture"), + }, + ) + except StagedDatasetError as exc: + raise SystemExit(f"error: {exc}") from exc + if args.modal_receipt is not None: + problems = _modal_receipt_problems( + bundle, args.modal_receipt, state_root=args.modal_state_root + ) + if problems: + raise SystemExit( + f"error: {run_dir} does not hold what the Modal stage wrote, so " + "nothing is staged:\n" + + "\n".join(f" - {problem}" for problem in problems) + ) existing = _valid_record(manifest.get("staged_dataset")) handed_over = ( None @@ -299,6 +349,63 @@ def main(argv: list[str] | None = None) -> int: return 0 if delivery["status"] != "failed" else 1 +def _modal_receipt_problems( + bundle: StagedDatasetBundle, + receipt_path: Path, + *, + state_root: Path | None = None, +) -> list[str]: + """Why the bundle's outputs are not the files a finished Modal stage wrote. + + The receipt lists every file of the stage's state directory by its path + under it; ``state_root`` is that directory as copied back, by default + ``state/`` beside the receipt's ``receipts/`` directory, as ``modal volume + get`` leaves them. The bundle has already verified each output against + the manifest's digest; this compares each with the receipt's. + """ + + receipt_path = receipt_path.expanduser() + try: + receipt = json.loads(receipt_path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + return [f"cannot read the Modal receipt {receipt_path}: {exc}"] + if ( + not isinstance(receipt, Mapping) + or receipt.get("schema") != modal_plan.RECEIPT_SCHEMA + ): + return [f"{receipt_path} is not a {modal_plan.RECEIPT_SCHEMA} receipt"] + problems = modal_plan.receipt_status_problems(receipt) + root = ( + receipt_path.resolve().parent.parent / "state" + if state_root is None + else state_root.expanduser().resolve() + ) + try: + relative = PurePosixPath(*bundle.run_dir.relative_to(root).parts) + except ValueError: + return [ + *problems, + f"{bundle.run_dir} is not inside the Modal run's state directory " + f"{root} (pass --modal-state-root)", + ] + listed = { + str(item.get("path")): item + for item in receipt.get("outputs") or () + if isinstance(item, Mapping) + } + for output in bundle.files: + path = (relative / output.name).as_posix() + entry = listed.get(path) + if entry is None: + problems.append(f"the receipt lists no {path}") + elif entry.get("sha256") != output.sha256 or entry.get("bytes") != output.bytes: + problems.append( + f"{path} is not the file the Modal stage wrote: its SHA-256 or size " + "differs from the receipt's" + ) + return problems + + def _write_sidecars( bundle: StagedDatasetBundle, manifest: dict, *, repository: str | None ) -> None: From 8f0000e17a87de2200e64799a5b75b311b9094f6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:53:45 +0400 Subject: [PATCH 03/10] Test the review's checks of a copied-back Modal run (failing) Review round 1 of #1499. New and changed tests describe what the command does not do yet, each failing on an assertion: - an edited build manifest (a field, another file the stage wrote registered as an output, a renamed role) is refused while its staged_dataset record is still the build's own; - the receipt's status and the run directory's place are checked before any output is hashed; - an output the stage hashed but never copied to the runs volume (outputs_not_mirrored) gets its own message; - the default state root is resolved, so a state directory that is a symbolic link still describes the copied-back files; - a malformed build manifest is an error message, not a traceback. Other new cases pass already and guard the same checks: an output whose receipt entry has other bytes, a run directory named through a link or through .., a link in the state directory that leads outside it, and a --local-only run that leaves the build manifest's bytes unchanged. The installed-emitter test now takes the run id from the build's local_only record instead of --run-id. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_modal_copy_back_staging.py | 293 +++++++++++++++++- .../shared/test_installed_emitter_staging.py | 21 +- 2 files changed, 298 insertions(+), 16 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py index cb2ca2df25..e0fbde67d9 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py @@ -1,12 +1,14 @@ """Staging a UK build's outputs once they are copied back from a Modal run. -The Modal runner runs every tool with ``HF_HUB_OFFLINE=1``, so a build there -uploads nothing: it verifies its bundle, writes the sidecars and records the -bundle as ``local_only``. After ``modal volume get`` copies the run back, -``tools/stage_uk_rowwise_candidate.py --modal-receipt`` checks every output -the manifest registers against the run's receipt, then hands the bundle to the -operator's emitter with the code that re-stages a local build that kept its -bundle local. +No UK program is registered with the Modal runner yet. The runner runs every +tool with ``HF_HUB_OFFLINE=1``, so a UK build run there would upload nothing: +it would verify its bundle, write the sidecars and record the bundle as +``local_only``. These tests run such a build locally with that variable set +and lay it out as ``modal volume get`` copies a run back. Then +``tools/stage_uk_rowwise_candidate.py --modal-receipt`` checks the build +manifest and every output it registers against the stage's receipt, and hands +the bundle to the operator's emitter with the code that re-stages a local +build that kept its bundle local. """ from __future__ import annotations @@ -35,6 +37,7 @@ ) PRIVATE_REPOSITORY = "policyengine/populace-uk-private" +MANIFEST = "rowwise_candidate_manifest.json" def _modal_build(tmp_path, monkeypatch): @@ -82,6 +85,38 @@ def _manifest(copied: Path) -> dict: return json.loads((copied / stager.MANIFEST_FILENAME).read_text()) +def _refusal(stager, argv: list[str]) -> str: + """The error message the command exits with; fails unless it refuses so.""" + try: + status = stager.main(argv) + except SystemExit as stop: + assert isinstance(stop.code, str), f"the command exited with {stop.code!r}" + return stop.code + except Exception as error: + raise AssertionError( + f"the command raised {error!r} instead of exiting with a message" + ) from error + raise AssertionError(f"the command did not refuse; it returned {status}") + + +def _completes(stager, argv: list[str]) -> int: + """The command's exit status; fails if it refuses.""" + try: + return stager.main(argv) + except SystemExit as stop: + raise AssertionError(f"the command refused: {stop.code}") from None + + +def _edit_the_build_manifest(copied: Path, change) -> None: + """Apply ``change`` to the build manifest, written as the build writes it.""" + path = copied / MANIFEST + manifest = json.loads(path.read_text()) + change(manifest) + path.write_text( + json.dumps(manifest, allow_nan=False, indent=2, sort_keys=True) + "\n" + ) + + def _files(directory: Path) -> dict[str, bytes]: return { path.relative_to(directory).as_posix(): path.read_bytes() @@ -167,6 +202,23 @@ def _edit_after_copy_back(copied, run_root, receipt): _edit_an_output(copied) +def _receipt_records_other_bytes(copied, run_root, receipt): + def change(content): + for item in content["outputs"]: + if item["path"] == f"out/{STEM}.h5": + item["sha256"] = "0" * 64 + + rewrite_receipt(receipt, change) + + +def _dataset_never_mirrored(copied, run_root, receipt): + (copied / f"{STEM}.h5").unlink() + rewrite_receipt( + receipt, + lambda content: content.update(outputs_not_mirrored=[f"out/{STEM}.h5"]), + ) + + def _change_without_the_manifest(copied, run_root, receipt): dataset = copied / f"{STEM}.h5" dataset.write_bytes(dataset.read_bytes() + b"\0") @@ -202,9 +254,19 @@ def _another_kind_of_file(copied, run_root, receipt): [ pytest.param( _edit_after_copy_back, - r"is not the file the Modal stage wrote", + rf"out/{MANIFEST} is not the build manifest the Modal stage wrote", id="an output edited after the copy-back", ), + pytest.param( + _receipt_records_other_bytes, + rf"out/{STEM}\.h5 is not the file the Modal stage wrote", + id="an output the receipt records with other bytes", + ), + pytest.param( + _dataset_never_mirrored, + rf"out/{STEM}\.h5 was hashed in the Modal container but never copied", + id="an output the stage never copied to the runs volume", + ), pytest.param( _change_without_the_manifest, r"does not match its manifest digest", @@ -236,8 +298,8 @@ def test_a_copied_back_directory_that_does_not_verify_is_refused( tmp_path, monkeypatch, change, refusal ): """Nothing is handed over, no emitter is started and no file changes - unless every output the manifest registers is the file the finished - stage wrote.""" + unless the build manifest and every output it registers are the files the + finished stage wrote.""" hub, copied, receipt = _modal_build(tmp_path, monkeypatch) change(copied, receipt.parent.parent, receipt) before = _files(copied) @@ -394,8 +456,217 @@ def test_hf_hub_offline_on_the_workstation_stages_nothing( None, ) _edit_an_output(copied) - with pytest.raises(SystemExit, match="is not the file the Modal stage wrote"): + with pytest.raises( + SystemExit, match="is not the build manifest the Modal stage wrote" + ): stager.main(_staging_argv(copied, receipt, "--local-only")) assert started == [] assert hub.paths(PRIVATE_REPOSITORY) == [] + + +def _change_a_field(manifest, copied): + manifest["release_posture"] = "edited after the copy-back" + + +def _register_another_file_the_stage_wrote(manifest, copied): + registered = { + Path(str(entry["path"])).name for entry in manifest["outputs"].values() + } + unregistered = sorted( + path.name + for path in copied.iterdir() + if path.is_file() + and path.name + not in registered | {MANIFEST, "staged_manifest.json", "sha256sums.txt"} + ) + assert unregistered, "the stage wrote no other file in the run directory" + content = (copied / unregistered[0]).read_bytes() + manifest["outputs"]["another_file"] = { + "path": unregistered[0], + "sha256": hashlib.sha256(content).hexdigest(), + "bytes": len(content), + } + + +def _rename_a_role(manifest, copied): + key = next( + key + for key, entry in manifest["outputs"].items() + if str(entry["path"]).endswith(".h5") + ) + manifest["outputs"]["renamed_dataset"] = manifest["outputs"].pop(key) + + +@pytest.mark.parametrize( + "edit", + [ + pytest.param(_change_a_field, id="a field changed"), + pytest.param( + _register_another_file_the_stage_wrote, + id="another file the stage wrote registered as an output", + ), + pytest.param(_rename_a_role, id="an output's role renamed"), + ], +) +def test_a_build_manifest_edited_after_the_copy_back_is_refused( + tmp_path, monkeypatch, edit +): + """The build manifest says which files are staged and with which roles, + and it is uploaded as the build's record. Until a hand-over rewrites it, + it must be the file the stage wrote, even when every output still + matches the receipt.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + _edit_the_build_manifest(copied, lambda manifest: edit(manifest, copied)) + before = _files(copied) + stager = load_tool("stage_uk_rowwise_candidate") + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub + ) + + message = _refusal(stager, _staging_argv(copied, receipt)) + + assert f"out/{MANIFEST} is not the build manifest the Modal stage wrote" in message + assert started == [] + assert _files(copied) == before + assert hub.paths(PRIVATE_REPOSITORY) == [] + + +@pytest.mark.parametrize( + "case", ["a stage that did not finish", "a directory outside the state"] +) +def test_the_receipt_and_the_directory_are_checked_before_any_output_is_hashed( + tmp_path, monkeypatch, case +): + """A UK dataset is about 2.4 GB, so the command refuses a receipt of an + unfinished stage, or a directory the receipt does not describe, before it + reads any output.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + run_dir = copied + if case == "a stage that did not finish": + write_receipt(receipt.parent.parent, status="FAILED") + expected = "status is 'FAILED', not 'COMPLETED'" + else: + run_dir = tmp_path / "elsewhere" / "out" + shutil.copytree(copied, run_dir) + expected = "is not inside the Modal run's state directory" + stager = load_tool("stage_uk_rowwise_candidate") + _workstation_emitters(monkeypatch, stager, hub_files=hub.files, hub_api=hub) + hashed = [] + from_manifest = staging_dataset.StagedDatasetBundle.from_manifest + + def recording_from_manifest(*arguments, **options): + hashed.append(arguments) + return from_manifest(*arguments, **options) + + monkeypatch.setattr( + staging_dataset.StagedDatasetBundle, + "from_manifest", + staticmethod(recording_from_manifest), + ) + + message = _refusal(stager, _staging_argv(run_dir, receipt)) + + assert expected in message + assert hashed == [] + + +def test_a_state_directory_reached_through_a_symbolic_link_is_the_default_root( + tmp_path, monkeypatch +): + """The default state root, ``state/`` beside the receipt's directory, is + resolved as ``--modal-state-root`` is, so a ``state`` directory that is a + symbolic link to where the files were copied still describes them.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + run_root = receipt.parent.parent + volume_copy = tmp_path / "volume-copy" + shutil.move(str(run_root / "state"), str(volume_copy)) + (run_root / "state").symlink_to(volume_copy, target_is_directory=True) + stager = load_tool("stage_uk_rowwise_candidate") + _workstation_emitters(monkeypatch, stager, hub_files=hub.files, hub_api=hub) + + assert _completes(stager, _staging_argv(run_root / "state" / "out", receipt)) == 0 + + staged = _manifest(volume_copy / "out")["staged_dataset"] + assert (staged["status"], staged["revision"]) == ("uploaded", hub.sha) + + +@pytest.mark.parametrize( + "route", + [ + "a symbolic link to the run directory", + "a path through ..", + "a link in the state directory to a copy outside it", + ], +) +def test_the_run_directory_is_checked_where_it_really_is(tmp_path, monkeypatch, route): + """The command compares the run directory's real location with the state + directory, so a link to it or a path through ``..`` stages it, and a link + placed in the state directory that leads outside it is refused.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + if route == "a symbolic link to the run directory": + named = tmp_path / "link-to-the-run" + named.symlink_to(copied, target_is_directory=True) + elif route == "a path through ..": + named = copied / ".." / copied.name + else: + outside = tmp_path / "outside" / "out" + shutil.copytree(copied, outside) + named = copied.parent / "linked-out" + named.symlink_to(outside, target_is_directory=True) + stager = load_tool("stage_uk_rowwise_candidate") + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub + ) + + if route == "a link in the state directory to a copy outside it": + message = _refusal(stager, _staging_argv(named, receipt)) + assert "is not inside the Modal run's state directory" in message + assert started == [] + return + assert _completes(stager, _staging_argv(named, receipt)) == 0 + manifest = _manifest(copied) + assert manifest["staged_dataset"]["status"] == "uploaded" + assert manifest["staged_dataset_handover"]["run_dir"] == str(copied.resolve()) + + +def test_a_local_only_check_keeps_the_build_manifest_the_stage_wrote( + tmp_path, monkeypatch +): + """``--local-only`` writes the build's own ``local_only`` record into the + build manifest again, so the manifest keeps the bytes the receipt lists + and a later run with the receipt still stages it.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + manifest_bytes = (copied / MANIFEST).read_bytes() + stager = load_tool("stage_uk_rowwise_candidate") + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub + ) + + assert _completes(stager, _staging_argv(copied, receipt, "--local-only")) == 0 + assert started == [] + assert (copied / MANIFEST).read_bytes() == manifest_bytes + assert _completes(stager, _staging_argv(copied, receipt)) == 0 + + assert _manifest(copied)["staged_dataset"]["status"] == "uploaded" + + +@pytest.mark.parametrize( + ("content", "says"), + [ + pytest.param("{not json", "is not valid JSON", id="invalid JSON"), + pytest.param("[]", "must be a JSON object", id="JSON that is not an object"), + ], +) +def test_a_malformed_build_manifest_is_an_error_message(tmp_path, content, says): + """Every refusal of the build manifest is an error message, as the + bundle's own checks of it are, never a traceback.""" + stager = load_tool("stage_uk_rowwise_candidate") + run_dir = tmp_path / "run" + run_dir.mkdir() + (run_dir / MANIFEST).write_text(content) + + message = _refusal(stager, ["--run-dir", str(run_dir), "--local-only"]) + + assert message.startswith("error: ") + assert says in message diff --git a/packages/microcosm-build/tests/installed_emitter/shared/test_installed_emitter_staging.py b/packages/microcosm-build/tests/installed_emitter/shared/test_installed_emitter_staging.py index 96fd868d60..3186f66dd2 100644 --- a/packages/microcosm-build/tests/installed_emitter/shared/test_installed_emitter_staging.py +++ b/packages/microcosm-build/tests/installed_emitter/shared/test_installed_emitter_staging.py @@ -37,7 +37,9 @@ SHA256SUMS_FILENAME, STAGED_MANIFEST_FILENAME, StagedDatasetBundle, + at_build_record, handover_record, + local_only_staged_dataset, resume_hand_over, stage_bundle, write_access_problem, @@ -386,11 +388,21 @@ def test_the_installed_emitter_uploads_the_bundle_in_one_commit( def test_a_modal_runs_copied_back_outputs_are_staged_by_the_re_stage_command( tmp_path: Path, stand_in_hub: StandInHub, installed_emitter: InstalledEmitter ) -> None: - """After ``modal volume get``, the UK re-stage command checks the outputs - against the stage's receipt, starts the installed emitter as it does for a - local directory, and records the commit the emitter made of them.""" + """After ``modal volume get``, the UK re-stage command checks the build + manifest and the outputs against the stage's receipt, starts the installed + emitter as it does for a local directory, and records the commit the + emitter made of them, under the run id the build recorded.""" stager = load_tool("stage_uk_rowwise_candidate") bundle = _write_bundle(tmp_path, manifest_name=stager.MANIFEST_FILENAME) + # A build run with HF_HUB_OFFLINE, as on Modal, records its bundle as + # local_only under its run id, and the command stages it under that id. + manifest_path = bundle.run_dir / stager.MANIFEST_FILENAME + manifest = json.loads(manifest_path.read_text()) + record = local_only_staged_dataset(bundle, prefix="staged") + manifest.update( + staged_dataset=record, staged_dataset_at_build=at_build_record(record) + ) + manifest_path.write_text(json.dumps(manifest, indent=2)) copied, receipt = copy_back(bundle.run_dir, tmp_path / "modal-runs") status = stager.main( @@ -399,8 +411,6 @@ def test_a_modal_runs_copied_back_outputs_are_staged_by_the_re_stage_command( str(copied), "--repo-id", REPOSITORY, - "--run-id", - RUN_ID, "--modal-receipt", str(receipt), "--wait-seconds", @@ -433,6 +443,7 @@ def test_a_modal_runs_copied_back_outputs_are_staged_by_the_re_stage_command( PREFIX, commit.oid, ) + assert staged["run_id"] == RUN_ID assert manifest["staged_dataset_handover"]["run_dir"] == str(copied.resolve()) From 0450f5d304c27c209881dbf2e5c2f69e2bc83976 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:58:55 +0400 Subject: [PATCH 04/10] Check a copied-back build manifest and the receipt before hashing Review round 1 of #1499. - The build manifest must have the receipt's SHA-256 and size while its staged_dataset record is still the build's own (anything but a local_and_remote record), so an edited manifest cannot register another file the stage wrote, rename a role or change other fields. A --local-only re-stage writes the same record in the build's own JSON rendering, so the bytes stay the receipt's; after a hand-over the manifest is not compared, so a second run on a landed bundle works. - The receipt's status, the run directory's place under the state directory, and the receipt's listing of the manifest and of every registered output are checked before any output is hashed. An output in the receipt's outputs_not_mirrored that the copy-back lacks gets its own message. The default state root is resolved, as --modal-state-root is. - A build manifest that is not valid JSON or not a JSON object is an error message rather than a traceback. - Docs: a UK build on Modal is described as a possible future case, the US release manifest's artifacts is a mapping, and --local-only also rewrites the build manifest. Co-Authored-By: Claude Opus 5.5 --- .../1498-modal-copied-back-staging.added.md | 2 +- docs/uk-staging-operations.md | 56 +++-- docs/us-modal-stage-runbook.md | 14 +- tools/stage_uk_rowwise_candidate.py | 214 +++++++++++++----- 4 files changed, 203 insertions(+), 83 deletions(-) diff --git a/changelog.d/1498-modal-copied-back-staging.added.md b/changelog.d/1498-modal-copied-back-staging.added.md index c54417b069..2ca0f5abba 100644 --- a/changelog.d/1498-modal-copied-back-staging.added.md +++ b/changelog.d/1498-modal-copied-back-staging.added.md @@ -1 +1 @@ -`tools/stage_uk_rowwise_candidate.py --modal-receipt ` stages a UK run directory copied back from a Modal run with `modal volume get`. Before it starts an emitter, it checks that the receipt is of a stage that finished (`COMPLETED`, not stopped at its budget), that the directory is inside the run's copied-back state directory (`state/` beside the receipt's `receipts/` directory, or `--modal-state-root`), and that every output the manifest registers is in the receipt with the same SHA-256 and size; it refuses the directory otherwise. It then hands the bundle over with the re-stage command's existing code, so the records, retries and landed-bundle handling are those of a directory built on the workstation. The command now reports an output that does not match its manifest digest as an error message instead of a traceback. +`tools/stage_uk_rowwise_candidate.py --modal-receipt ` stages a UK run directory copied back from a Modal run with `modal volume get`, for when a UK build is registered with the Modal runner. Before it reads any output, it checks that the receipt is of a stage that finished (`COMPLETED`, not stopped at its budget) and that the directory is inside the run's copied-back state directory (`state/` beside the receipt's `receipts/` directory, or `--modal-state-root`, both resolved). The receipt must list the build manifest and every output it registers; an output the stage never copied to the runs volume (`outputs_not_mirrored`) is named as such. While the build manifest still holds the build's own staged-dataset record it must have the receipt's SHA-256 and size, and every output must. The command refuses the directory otherwise, before it starts an emitter. It then hands the bundle over with the re-stage command's existing code, so the records, retries and landed-bundle handling are those of a directory built on the workstation. The command now reports a build manifest that is not valid JSON or not a JSON object, and an output that does not match its manifest digest, as an error message instead of a traceback. diff --git a/docs/uk-staging-operations.md b/docs/uk-staging-operations.md index 71f8f4fbcb..d57c0191ef 100644 --- a/docs/uk-staging-operations.md +++ b/docs/uk-staging-operations.md @@ -385,12 +385,15 @@ does not know about is recorded as `already_staged` with the bundle's own commit; a different bundle under the same run id is refused (`REMOTE_DIFFERS`). -A build run on Modal stages nothing from its container: the runner sets -`HF_HUB_OFFLINE=1` for every tool, so the build records its bundle as -`local_only` (see above). After `modal volume get` has copied the run back -([the Modal runbook](us-modal-stage-runbook.md#commands), step 5), stage it -from the workstation, with your own emitter and Hub credential, by naming the -stage's receipt: +No UK program is registered with the Modal runner yet; the runner's +programs are all US builds today (`tools/modal_us_stage_plan.py`), and none of +them writes a staged-dataset bundle. A UK build run there would stage nothing +from its container: the runner sets `HF_HUB_OFFLINE=1` for every tool, so the +build would record its bundle as `local_only` (see above). After `modal volume +get` has copied such a run back +([the Modal runbook](us-modal-stage-runbook.md#commands), step 5), you would +stage it from the workstation, with your own emitter and Hub credential, by +naming the stage's receipt: ```bash uv run python tools/stage_uk_rowwise_candidate.py \ @@ -398,25 +401,32 @@ uv run python tools/stage_uk_rowwise_candidate.py \ --modal-receipt ./modal-runs//receipts/-.json ``` -Before it starts an emitter, the command checks that the receipt is of a -stage that finished (`COMPLETED`, and not stopped at its budget) and that -every output the manifest registers is in it, at its path under the run's -state directory, with the same SHA-256 and size. It refuses the directory -otherwise, and when the directory is not inside that state directory, which -is `state/` beside the receipt's `receipts/` directory unless -`--modal-state-root` names another. The manifest, `staged_manifest.json` and -`sha256sums.txt` are not compared, because staging rewrites them. Then it -stages the directory as above, under the build's own run id: the hand-over, -the records, a re-stage after a failed attempt and a second run on a landed -bundle work as they do for a directory built on the workstation. Unset -`HF_HUB_OFFLINE` first if your shell sets it: the command refuses to stage -while it is set, and with `--local-only` it checks the receipt and rewrites -the sidecars only. Nothing here submits the bundle to the collector: the +Before it reads any output, the command checks that the receipt is of a +stage that finished (`COMPLETED`, and not stopped at its budget) and that the +run directory, wherever a link or `..` in its path leads, is inside the run's +state directory: `state/` beside the receipt's `receipts/` directory, or the +directory `--modal-state-root` names, either resolved the same way. The +receipt must list the build manifest and every output it registers, at their +paths under the state directory. An output the stage hashed but never copied +to the runs volume (the receipt's `outputs_not_mirrored`) is named as such. +While the build manifest's `staged_dataset` record is still the build's own +`local_only` one, the manifest must have the receipt's SHA-256 and size, so a +manifest edited to register another file, rename a role or change any other +field is refused. Then every output must have the receipt's SHA-256 and size. +Every refusal comes before an emitter starts. `staged_manifest.json` and +`sha256sums.txt` are not compared, because staging writes them again, and the +build manifest is not compared once a hand-over has replaced its record. Then +the command stages the directory as above, under the build's own run id: the +hand-over, the records, a re-stage after a failed attempt and a second run on +a landed bundle work as they do for a directory built on the workstation. +Unset `HF_HUB_OFFLINE` first if your shell sets it: the command refuses to +stage while it is set. With `--local-only` it checks the receipt and rewrites +the sidecars and the build manifest; the manifest gets the build's own +`local_only` record again, in the build's own JSON rendering, so it keeps the +bytes the receipt lists. Nothing here submits the bundle to the collector: the command's emitter runs its Hugging Face module only, and builds do not submit artifacts to the collector's artifact intake yet -(PolicyEngine/microcosm-collector#12). The Modal runner's registered programs -are all US builds today (`tools/modal_us_stage_plan.py`), and none of them -writes a staged-dataset bundle. +(PolicyEngine/microcosm-collector#12). Fetch a bundle for a scorecard, an evaluation leg or the dashboard's local-directory mode with: diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index 32690cd6df..612050bfff 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -288,13 +288,13 @@ python3 tools/modal_us_stage_plan.py verify-receipt \ --state-root ./modal-runs//state ``` -A run directory whose manifest registers a staged-dataset bundle (a UK -rowwise build's `rowwise_candidate_manifest.json`) is staged from the +No program registered here writes a staged-dataset bundle yet; see "What +this does not cover yet". A UK rowwise build's run directory, whose +`rowwise_candidate_manifest.json` registers one, would be staged from the workstation after step 5, with the operator's own emitter and Hub credential: -`tools/stage_uk_rowwise_candidate.py --modal-receipt` checks its outputs -against the receipt and hands the bundle over as for a local build (see -[Staged datasets](uk-staging-operations.md#staged-datasets)). No program -registered here writes such a bundle yet; see "What this does not cover yet". +`tools/stage_uk_rowwise_candidate.py --modal-receipt` checks the build +manifest and its outputs against the receipt and hands the bundle over as for +a local build (see [Staged datasets](uk-staging-operations.md#staged-datasets)). To prove the run path on a new commit or workspace for well under a cent, run `docs/us-modal-stage-smoke-plan.json` (tool `runner-smoke`). It is an @@ -1463,7 +1463,7 @@ hold digests, sizes and paths, never file contents. bundle (their manifest's `outputs`, staged under `staged//` on a private repository), and the copied-back staging command reads only their manifest. The `package` stage writes a release directory with its own - `release_manifest.json` (an `artifacts` list) and `sha256sums.txt`, which is + `release_manifest.json` (an `artifacts` mapping) and `sha256sums.txt`, which is also the name of the bundle's checksum file. A US bundle needs a private repository, a manifest that registers its outputs, and a command that reads it; none exists yet. diff --git a/tools/stage_uk_rowwise_candidate.py b/tools/stage_uk_rowwise_candidate.py index 1ee70d7280..8713a52980 100644 --- a/tools/stage_uk_rowwise_candidate.py +++ b/tools/stage_uk_rowwise_candidate.py @@ -33,14 +33,19 @@ keeps the manifest's records and says so. A directory whose bytes differ from the remote bundle is otherwise refused. -A build run on Modal stages nothing from its container (the runner sets -``HF_HUB_OFFLINE``, so the build records its bundle as ``local_only``). Once -``modal volume get`` has copied the run back, ``--modal-receipt`` names the -stage's receipt: every output the manifest registers must be in it, at its -path under the run's state directory, with the same SHA-256 and size, and the -receipt must be of a stage that finished. Otherwise the command refuses before -it starts an emitter; when they match, it stages the directory as above. The -manifest and the sidecars are not compared, because staging rewrites them. +No UK program is registered with the Modal runner yet. A UK build run there +would stage nothing from its container: the runner sets ``HF_HUB_OFFLINE``, +so the build would record its bundle as ``local_only``. Once ``modal volume +get`` has copied such a run back, ``--modal-receipt`` names the stage's +receipt. The receipt must be of a stage that finished, and the run directory +must be inside the run's copied-back state directory; both are checked before +any output is read. The build manifest, while its ``staged_dataset`` record is +still the build's own, and every output it registers must then be in the +receipt, at their paths under the state directory, with the same SHA-256 and +size. Otherwise the command refuses before it starts an emitter; when they +match, it stages the directory as above. The staged manifest and the checksum +file are not compared, because staging writes them again, and neither is the +build manifest once a hand-over has replaced its record. Staging is not publication: ``releases/`` and ``latest.json`` are untouched. """ @@ -49,6 +54,7 @@ import argparse import glob +import hashlib import json import math import os @@ -208,11 +214,28 @@ def main(argv: list[str] | None = None) -> int: manifest_path = run_dir / MANIFEST_FILENAME if not manifest_path.is_file(): raise SystemExit(f"error: {manifest_path} is missing") - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + manifest_bytes = manifest_path.read_bytes() + try: + manifest = json.loads(manifest_bytes) + except ValueError: + raise SystemExit(f"error: {manifest_path} is not valid JSON") from None + if not isinstance(manifest, dict): + raise SystemExit(f"error: {manifest_path} must be a JSON object") run_id = args.run_id or _default_run_id(run_dir, manifest) repository = None if args.local_only else str(args.repo_id).strip() if repository == "": raise SystemExit("error: --repo-id must be non-empty unless --local-only") + copied_back = ( + None + if args.modal_receipt is None + else _copied_back_stage( + args.modal_receipt, + state_root=args.modal_state_root, + run_dir=run_dir, + manifest=manifest, + manifest_bytes=manifest_bytes, + ) + ) try: bundle = StagedDatasetBundle.from_manifest( run_dir, @@ -227,16 +250,10 @@ def main(argv: list[str] | None = None) -> int: ) except StagedDatasetError as exc: raise SystemExit(f"error: {exc}") from exc - if args.modal_receipt is not None: - problems = _modal_receipt_problems( - bundle, args.modal_receipt, state_root=args.modal_state_root - ) + if copied_back is not None: + problems = copied_back.output_problems(bundle) if problems: - raise SystemExit( - f"error: {run_dir} does not hold what the Modal stage wrote, so " - "nothing is staged:\n" - + "\n".join(f" - {problem}" for problem in problems) - ) + raise _copy_back_refusal(run_dir, problems) existing = _valid_record(manifest.get("staged_dataset")) handed_over = ( None @@ -349,61 +366,154 @@ def main(argv: list[str] | None = None) -> int: return 0 if delivery["status"] != "failed" else 1 -def _modal_receipt_problems( - bundle: StagedDatasetBundle, +class _CopiedBackStage: + """A finished Modal stage's receipt, and where the run directory sits in it. + + ``relative`` is the run directory's path under the copied-back state + directory, where the receipt lists each file by its path. (A plain class: + the tests load this command without registering it as a module, which a + dataclass needs.) + """ + + def __init__(self, receipt: Mapping[str, Any], relative: PurePosixPath) -> None: + self.receipt = receipt + self.relative = relative + + def path(self, name: str) -> str: + return (self.relative / name).as_posix() + + def listed(self) -> dict[str, Mapping[str, Any]]: + return { + str(item.get("path")): item + for item in self.receipt.get("outputs") or () + if isinstance(item, Mapping) + } + + def output_problems(self, bundle: StagedDatasetBundle) -> list[str]: + """Outputs whose measured SHA-256 or size differ from the receipt's. + + ``bundle`` has already measured each output; the receipt lists every + one of them (``_copied_back_stage`` checked). + """ + listed = self.listed() + problems = [] + for output in bundle.files: + path = self.path(output.name) + entry = listed.get(path, {}) + if ( + entry.get("sha256") != output.sha256 + or entry.get("bytes") != output.bytes + ): + problems.append( + f"{path} is not the file the Modal stage wrote: its SHA-256 or " + "size differs from the receipt's" + ) + return problems + + +def _copied_back_stage( receipt_path: Path, *, - state_root: Path | None = None, -) -> list[str]: - """Why the bundle's outputs are not the files a finished Modal stage wrote. - - The receipt lists every file of the stage's state directory by its path - under it; ``state_root`` is that directory as copied back, by default + state_root: Path | None, + run_dir: Path, + manifest: Mapping[str, Any], + manifest_bytes: bytes, +) -> _CopiedBackStage: + """Read the receipt and check what can be checked without reading outputs. + + The receipt must be of a stage that finished, and ``run_dir`` (resolved) + must be inside the stage's state directory as copied back: by default ``state/`` beside the receipt's ``receipts/`` directory, as ``modal volume - get`` leaves them. The bundle has already verified each output against - the manifest's digest; this compares each with the receipt's. + get`` leaves them, resolved as ``--modal-state-root`` is. The receipt must + list the build manifest and every output it registers; the build manifest + must also have the receipt's bytes while its record is still the build's + (:func:`_record_is_the_builds`). The command refuses otherwise, before any + output is hashed. """ receipt_path = receipt_path.expanduser() try: receipt = json.loads(receipt_path.read_text(encoding="utf-8")) except (OSError, ValueError) as exc: - return [f"cannot read the Modal receipt {receipt_path}: {exc}"] + raise _copy_back_refusal( + run_dir, [f"cannot read the Modal receipt {receipt_path}: {exc}"] + ) from None if ( not isinstance(receipt, Mapping) or receipt.get("schema") != modal_plan.RECEIPT_SCHEMA ): - return [f"{receipt_path} is not a {modal_plan.RECEIPT_SCHEMA} receipt"] + raise _copy_back_refusal( + run_dir, [f"{receipt_path} is not a {modal_plan.RECEIPT_SCHEMA} receipt"] + ) problems = modal_plan.receipt_status_problems(receipt) root = ( receipt_path.resolve().parent.parent / "state" if state_root is None - else state_root.expanduser().resolve() - ) + else state_root.expanduser() + ).resolve() try: - relative = PurePosixPath(*bundle.run_dir.relative_to(root).parts) + relative = PurePosixPath(*run_dir.relative_to(root).parts) except ValueError: - return [ - *problems, - f"{bundle.run_dir} is not inside the Modal run's state directory " - f"{root} (pass --modal-state-root)", - ] - listed = { - str(item.get("path")): item - for item in receipt.get("outputs") or () - if isinstance(item, Mapping) - } - for output in bundle.files: - path = (relative / output.name).as_posix() - entry = listed.get(path) - if entry is None: - problems.append(f"the receipt lists no {path}") - elif entry.get("sha256") != output.sha256 or entry.get("bytes") != output.bytes: + problems.append( + f"{run_dir} is not inside the Modal run's state directory {root} " + "(pass --modal-state-root)" + ) + raise _copy_back_refusal(run_dir, problems) from None + stage = _CopiedBackStage(receipt, relative) + listed = stage.listed() + manifest_path = stage.path(MANIFEST_FILENAME) + manifest_entry = listed.get(manifest_path) + if manifest_entry is None: + problems.append(f"the receipt lists no {manifest_path}") + elif _record_is_the_builds(manifest) and ( + manifest_entry.get("sha256") != hashlib.sha256(manifest_bytes).hexdigest() + or manifest_entry.get("bytes") != len(manifest_bytes) + ): + problems.append( + f"{manifest_path} is not the build manifest the Modal stage wrote: its " + "SHA-256 or size differs from the receipt's" + ) + not_mirrored = set(receipt.get("outputs_not_mirrored") or ()) + outputs = manifest.get("outputs") + for entry in outputs.values() if isinstance(outputs, Mapping) else (): + recorded = entry.get("path") if isinstance(entry, Mapping) else None + name = PurePosixPath(str(recorded or "")).name + if not name: + continue # The bundle refuses it. + path = stage.path(name) + if path in not_mirrored and not (run_dir / name).is_file(): problems.append( - f"{path} is not the file the Modal stage wrote: its SHA-256 or size " - "differs from the receipt's" + f"{path} was hashed in the Modal container but never copied to the " + "runs volume (the receipt's outputs_not_mirrored), so no copy-back " + "holds it" ) - return problems + elif path not in listed: + problems.append(f"the receipt lists no {path}") + if problems: + raise _copy_back_refusal(run_dir, problems) + return stage + + +def _record_is_the_builds(manifest: Mapping[str, Any]) -> bool: + """Whether the build manifest still holds the build's own staged record. + + A build run with ``HF_HUB_OFFLINE``, as the Modal runner runs every tool, + records its bundle as ``local_only`` (``disabled`` with staging off). Only + a hand-over replaces that with a ``local_and_remote`` record, rewriting + the manifest when the emitter copied it. A ``--local-only`` re-stage writes + the same ``local_only`` record again, in the build's own JSON rendering, so + the manifest keeps the bytes the receipt lists. + """ + + record = manifest.get("staged_dataset") + return not isinstance(record, Mapping) or record.get("mode") != "local_and_remote" + + +def _copy_back_refusal(run_dir: Path, problems: list[str]) -> SystemExit: + return SystemExit( + f"error: {run_dir} does not hold what the Modal stage wrote, so nothing is " + "staged:\n" + "\n".join(f" - {problem}" for problem in problems) + ) def _write_sidecars( From a5ea5db763df7d62d5cf29e775c5fba6d05fd765 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:24:08 +0400 Subject: [PATCH 05/10] Test that --local-only with a Modal receipt leaves the build manifest (failing) Review round 2 of #1499 found two gaps in the copied-back staging tests. - A --local-only run with --modal-receipt writes a new local_only record into the build manifest. When that record differs from the build's own, every later run with the receipt refuses the unedited directory. The new parametrized test covers the build's own local_only record, a build that disabled its staged dataset, another --run-id and a run after a failed hand-over. A new national test covers a build that rewrites its build record after it records its staged dataset. The case where the build wrote its own local_only record passes already; the other four fail on the manifest-bytes assertion. - No test reached the comparison of each output with its receipt entry through an edited output, because _edit_an_output also changes the build manifest and the manifest comparison refused it first. The refusal case now edits an output under a record edited to say it was handed over, where the manifest is not compared. A new test edits an output after a real failed hand-over. Both pass already; they pin which edits the checks catch once the manifest is no longer compared. - The landed-bundle test also runs --local-only with the receipt, and a new test checks that --local-only without the receipt still records the bundle in the build manifest. Both pass already. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_modal_copy_back_staging.py | 176 +++++++++++++++--- .../uk/test_uk_rowwise_national_role.py | 60 ++++++ 2 files changed, 214 insertions(+), 22 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py index e0fbde67d9..3e83180245 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py @@ -5,16 +5,18 @@ it would verify its bundle, write the sidecars and record the bundle as ``local_only``. These tests run such a build locally with that variable set and lay it out as ``modal volume get`` copies a run back. Then -``tools/stage_uk_rowwise_candidate.py --modal-receipt`` checks the build -manifest and every output it registers against the stage's receipt, and hands -the bundle to the operator's emitter with the code that re-stages a local -build that kept its bundle local. +``tools/stage_uk_rowwise_candidate.py --modal-receipt`` checks every output +the build manifest registers against the stage's receipt, and the build +manifest itself while its ``staged_dataset`` record is not +``local_and_remote``, and hands the bundle to the operator's emitter with the +code that re-stages a local build that kept its bundle local. """ from __future__ import annotations import hashlib import json +import re import shutil from pathlib import Path @@ -38,17 +40,21 @@ PRIVATE_REPOSITORY = "policyengine/populace-uk-private" MANIFEST = "rowwise_candidate_manifest.json" +#: The refusal of the CSV output ``_edit_an_output`` changes, by its receipt entry. +EDITED_OUTPUT_REFUSAL = r"out/[^/\s]+\.csv is not the file the Modal stage wrote" -def _modal_build(tmp_path, monkeypatch): +def _modal_build(tmp_path, monkeypatch, *, staging=None): """A dense build run as the Modal runner runs it, then copied back. - Returns the Hub, the copied-back run directory and the stage's receipt. + ``staging`` is the build's staging switch (none: the remote mode, which + ``HF_HUB_OFFLINE`` makes ``local_only``). Returns the Hub, the copied-back + run directory and the stage's receipt. """ pytest.importorskip("tables") hub = _remote_hub(monkeypatch) monkeypatch.setenv("HF_HUB_OFFLINE", "1") - status, out = run_dense_main(tmp_path, monkeypatch, staging=None) + status, out = run_dense_main(tmp_path, monkeypatch, staging=staging) assert status == 0 monkeypatch.delenv("HF_HUB_OFFLINE") assert hub.paths(PRIVATE_REPOSITORY) == [] @@ -198,7 +204,17 @@ def stage_bundle(bundle, **options): assert hashlib.sha256((copied / name).read_bytes()).hexdigest() == digest -def _edit_after_copy_back(copied, run_root, receipt): +def _edit_under_a_record_that_says_it_was_handed_over(copied, run_root, receipt): + """Edit an output, its manifest digest and the record's mode. + + With ``staged_dataset.mode`` set to ``local_and_remote``, the build manifest + is not compared with the receipt: the command cannot tell such an edit from + a record a hand-over wrote. Each output still is. + """ + _edit_the_build_manifest( + copied, + lambda manifest: manifest["staged_dataset"].update(mode="local_and_remote"), + ) _edit_an_output(copied) @@ -253,9 +269,9 @@ def _another_kind_of_file(copied, run_root, receipt): ("change", "refusal"), [ pytest.param( - _edit_after_copy_back, - rf"out/{MANIFEST} is not the build manifest the Modal stage wrote", - id="an output edited after the copy-back", + _edit_under_a_record_that_says_it_was_handed_over, + EDITED_OUTPUT_REFUSAL, + id="an output edited under a record edited to say it was handed over", ), pytest.param( _receipt_records_other_bytes, @@ -363,7 +379,8 @@ def test_a_copied_back_bundle_that_landed_is_not_handed_over_again( ): """Staging rewrites the manifest and ``sha256sums.txt``, so they no longer match the receipt; the outputs still do, so a second run with the receipt, - and a re-stage without it, both find the record and change nothing.""" + a re-stage without it and a ``--local-only`` run with it all find the + record and change nothing.""" hub, copied, receipt = _modal_build(tmp_path, monkeypatch) stager = load_tool("stage_uk_rowwise_candidate") started = _workstation_emitters( @@ -388,6 +405,9 @@ def test_a_copied_back_bundle_that_landed_is_not_handed_over_again( capsys.readouterr() assert stager.main(argv) == 0 assert "nothing to do" in capsys.readouterr().err + capsys.readouterr() + assert stager.main(_staging_argv(copied, receipt, "--local-only")) == 0 + assert "--local-only does not replace it" in capsys.readouterr().err assert _files(copied) == landed assert len(hub.commits) == 1 @@ -428,6 +448,39 @@ def test_a_copied_back_bundle_whose_first_hand_over_failed_is_staged_again( assert len(hub.commits) == 1 +def test_an_output_edited_after_a_failed_hand_over_is_refused_by_its_receipt_entry( + tmp_path, monkeypatch +): + """A hand-over replaces the build manifest's ``local_only`` record, so the + manifest is no longer compared with the receipt, and comparing each output + with its receipt entry is the only check left. An output edited after a + failed hand-over, with its manifest digest updated, is refused before an + emitter starts, and nothing reaches the Hub.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + queue = FakeHandoverQueue() + stager = load_tool("stage_uk_rowwise_candidate") + _workstation_emitters(monkeypatch, stager, hub_files=hub.files, queue=queue) + assert stager.main(_staging_argv(copied, receipt)) == 1 + staged = _manifest(copied)["staged_dataset"] + assert (staged["mode"], staged["error_code"]) == ( + "local_and_remote", + "CREDENTIAL_MISSING", + ) + _edit_an_output(copied) + before = _files(copied) + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub, queue=queue + ) + + message = _refusal(stager, _staging_argv(copied, receipt)) + + assert re.search(EDITED_OUTPUT_REFUSAL, message), message + assert "is not the build manifest the Modal stage wrote" not in message + assert started == [] + assert _files(copied) == before + assert hub.paths(PRIVATE_REPOSITORY) == [] + + def test_hf_hub_offline_on_the_workstation_stages_nothing( tmp_path, monkeypatch, capsys ): @@ -630,25 +683,104 @@ def test_the_run_directory_is_checked_where_it_really_is(tmp_path, monkeypatch, assert manifest["staged_dataset_handover"]["run_dir"] == str(copied.resolve()) -def test_a_local_only_check_keeps_the_build_manifest_the_stage_wrote( - tmp_path, monkeypatch +@pytest.mark.parametrize( + "case", + [ + "the build's own local_only record", + "a build that disabled its staged dataset", + "another --run-id", + "after a failed hand-over", + ], +) +def test_a_local_only_check_with_the_receipt_leaves_the_build_manifest( + tmp_path, monkeypatch, case ): - """``--local-only`` writes the build's own ``local_only`` record into the - build manifest again, so the manifest keeps the bytes the receipt lists - and a later run with the receipt still stages it.""" - hub, copied, receipt = _modal_build(tmp_path, monkeypatch) - manifest_bytes = (copied / MANIFEST).read_bytes() + """With ``--modal-receipt``, ``--local-only`` checks the directory and + writes the sidecars but leaves the build manifest as it is. The + ``local_only`` record it would write differs from the manifest's when the + build disabled its staged dataset, when ``--run-id`` names another run id, + and once a hand-over has replaced the record; a later run with the receipt + then still finds the manifest the stage wrote, or the hand-over's record, + and stages the directory.""" + hub, copied, receipt = _modal_build( + tmp_path, + monkeypatch, + staging=( + "--no-staged-dataset" + if case == "a build that disabled its staged dataset" + else None + ), + ) stager = load_tool("stage_uk_rowwise_candidate") + queue = FakeHandoverQueue() + if case == "after a failed hand-over": + _workstation_emitters(monkeypatch, stager, hub_files=hub.files, queue=queue) + assert stager.main(_staging_argv(copied, receipt)) == 1 + run_id = ("--run-id", "another-run") if case == "another --run-id" else () + manifest_bytes = (copied / MANIFEST).read_bytes() started = _workstation_emitters( - monkeypatch, stager, hub_files=hub.files, hub_api=hub + monkeypatch, stager, hub_files=hub.files, hub_api=hub, queue=queue + ) + + assert ( + _completes(stager, _staging_argv(copied, receipt, "--local-only", *run_id)) == 0 ) - assert _completes(stager, _staging_argv(copied, receipt, "--local-only")) == 0 assert started == [] assert (copied / MANIFEST).read_bytes() == manifest_bytes + # The sidecars describe the directory as it now is. + staged_manifest = json.loads((copied / "staged_manifest.json").read_text()) + assert staged_manifest["repository"] is None + assert staged_manifest["manifest"]["sha256"] == ( + hashlib.sha256(manifest_bytes).hexdigest() + ) + for line in (copied / "sha256sums.txt").read_text().splitlines(): + digest, name = line.split(" ") + assert hashlib.sha256((copied / name).read_bytes()).hexdigest() == digest assert _completes(stager, _staging_argv(copied, receipt)) == 0 + assert _manifest(copied)["staged_dataset"]["status"] in ( + "uploaded", + "already_staged", + ) + assert len(hub.commits) == 1 - assert _manifest(copied)["staged_dataset"]["status"] == "uploaded" + +def test_a_local_only_run_without_the_receipt_records_the_bundle_as_before( + tmp_path, monkeypatch +): + """Without ``--modal-receipt``, ``--local-only`` records the bundle as + ``local_only`` in the build manifest, as for a directory built on the + workstation, keeps what the build recorded in ``staged_dataset_at_build`` + and lists the rewritten manifest in ``sha256sums.txt``.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + at_build = _manifest(copied)["staged_dataset_at_build"] + stager = load_tool("stage_uk_rowwise_candidate") + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub + ) + + assert ( + _completes( + stager, + ["--run-dir", str(copied), "--run-id", "another-run", "--local-only"], + ) + == 0 + ) + + manifest = _manifest(copied) + staged = manifest["staged_dataset"] + assert (staged["mode"], staged["status"], staged["run_id"], staged["prefix"]) == ( + "local_only", + "skipped", + "another-run", + "staged/another-run", + ) + assert manifest["staged_dataset_at_build"] == at_build + for line in (copied / "sha256sums.txt").read_text().splitlines(): + digest, name = line.split(" ") + assert hashlib.sha256((copied / name).read_bytes()).hexdigest() == digest + assert started == [] + assert hub.paths(PRIVATE_REPOSITORY) == [] @pytest.mark.parametrize( diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_rowwise_national_role.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_rowwise_national_role.py index b507e72b3c..42341a7fa2 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_rowwise_national_role.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_rowwise_national_role.py @@ -810,6 +810,66 @@ def test_restaging_a_national_build_records_the_bundle_its_emitter_delivered( _sums_verify(out) +def test_a_local_only_check_of_a_copied_back_national_build_leaves_its_manifest( + monkeypatch, tmp_path +): + """A national build changes its outputs after it records its staged + dataset: it rewrites its build record, and registers its score receipt + when it has one. So the ``local_only`` record a ``--local-only`` run + would write differs from the build's. With ``--modal-receipt`` the command + leaves the build manifest as the Modal stage wrote it, and a later run + with the receipt stages the directory.""" + pytest.importorskip("tables") + from test_support.microcosm_build.emitter import FakeEmitterClient + from test_support.microcosm_build.modal_copy_back import copy_back + from test_support.microcosm_build.uk_full_build_cli import load_tool + + hub = candidate._FakeHub() + # As the Modal runner runs every tool, so the build keeps its bundle local. + monkeypatch.setenv("HF_HUB_OFFLINE", "1") + builder, out = _national_build(monkeypatch, tmp_path, hub) + monkeypatch.delenv("HF_HUB_OFFLINE") + manifest = json.loads((out / builder.MANIFEST_FILENAME).read_text()) + staged = manifest["staged_dataset"] + assert (staged["mode"], staged["status"]) == ("local_only", "skipped") + registered = { + Path(entry["path"]).name: entry["sha256"] + for entry in manifest["outputs"].values() + } + assert {name: entry["sha256"] for name, entry in staged["files"].items()} != ( + registered + ) + copied, receipt = copy_back(out, tmp_path / "modal-runs") + manifest_path = copied / builder.MANIFEST_FILENAME + manifest_bytes = manifest_path.read_bytes() + stager = load_tool("stage_uk_rowwise_candidate") + started: list[FakeEmitterClient] = [] + + def start() -> FakeEmitterClient: + started.append(FakeEmitterClient(hub_files=hub.files, hub_api=hub)) + return started[-1] + + monkeypatch.setattr(stager, "_start_bundle_emitter", start) + argv = [ + "--run-dir", + str(copied), + "--modal-receipt", + str(receipt), + "--wait-seconds", + "60", + ] + + assert stager.main([*argv, "--local-only"]) == 0 + + assert started == [] + assert manifest_path.read_bytes() == manifest_bytes + assert stager.main(argv) == 0 + restaged = json.loads(manifest_path.read_text())["staged_dataset"] + assert (restaged["status"], restaged["revision"]) == ("uploaded", hub.sha) + assert len(hub.commits) == 1 + _sums_verify(copied) + + def test_a_national_re_stage_never_replaces_a_landed_record(monkeypatch, tmp_path): """On another machine the emitter does not hold the build's hand-over, and the directory's outputs changed after it. A record that says the From 9e508a4fc394e6bb0b98928ca6db6eb2c5100f21 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:27:06 +0400 Subject: [PATCH 06/10] Leave the build manifest alone on --local-only with a Modal receipt A --local-only run wrote a new local_only record into the build manifest. That record differs from the build's own when the build disabled its staged dataset, when --run-id names another run id, when a national build changed its outputs after recording its staged dataset, and after a hand-over. The manifest then still counted as the build's, so it was compared with the receipt, but no longer had the receipt's bytes, and every later run with --modal-receipt refused the unedited directory. With --modal-receipt, --local-only now checks the directory, writes staged_manifest.json and sha256sums.txt, prints the local_only record and leaves the build manifest as it is. Without --modal-receipt it records the bundle in the build manifest as before. The manifest comparison reads staged_dataset.mode from the manifest itself, so a manifest edited to say local_and_remote is not compared either; the outputs still are. No condition read from the manifest can tell such an edit from a record a hand-over wrote. The command's docstring and help text, the UK staging guide, the Modal runbook's pointer and the changelog fragment now say which edits the checks catch and which they do not, and the --local-only help text says what it writes in each case. Co-Authored-By: Claude Opus 5.5 --- .../1498-modal-copied-back-staging.added.md | 2 +- docs/uk-staging-operations.md | 37 ++++---- docs/us-modal-stage-runbook.md | 7 +- tools/stage_uk_rowwise_candidate.py | 86 ++++++++++++++----- 4 files changed, 92 insertions(+), 40 deletions(-) diff --git a/changelog.d/1498-modal-copied-back-staging.added.md b/changelog.d/1498-modal-copied-back-staging.added.md index 2ca0f5abba..509ae7d2c4 100644 --- a/changelog.d/1498-modal-copied-back-staging.added.md +++ b/changelog.d/1498-modal-copied-back-staging.added.md @@ -1 +1 @@ -`tools/stage_uk_rowwise_candidate.py --modal-receipt ` stages a UK run directory copied back from a Modal run with `modal volume get`, for when a UK build is registered with the Modal runner. Before it reads any output, it checks that the receipt is of a stage that finished (`COMPLETED`, not stopped at its budget) and that the directory is inside the run's copied-back state directory (`state/` beside the receipt's `receipts/` directory, or `--modal-state-root`, both resolved). The receipt must list the build manifest and every output it registers; an output the stage never copied to the runs volume (`outputs_not_mirrored`) is named as such. While the build manifest still holds the build's own staged-dataset record it must have the receipt's SHA-256 and size, and every output must. The command refuses the directory otherwise, before it starts an emitter. It then hands the bundle over with the re-stage command's existing code, so the records, retries and landed-bundle handling are those of a directory built on the workstation. The command now reports a build manifest that is not valid JSON or not a JSON object, and an output that does not match its manifest digest, as an error message instead of a traceback. +`tools/stage_uk_rowwise_candidate.py --modal-receipt ` stages a UK run directory copied back from a Modal run with `modal volume get`, for when a UK build is registered with the Modal runner. Before it reads any output, it checks that the receipt is of a stage that finished (`COMPLETED`, not stopped at its budget) and that the directory is inside the run's copied-back state directory (`state/` beside the receipt's `receipts/` directory, or `--modal-state-root`, both resolved). The receipt must list the build manifest and every output it registers; an output the stage never copied to the runs volume (`outputs_not_mirrored`) is named as such. Every output must have the receipt's SHA-256 and size. So must the build manifest unless its `staged_dataset` record is `local_and_remote`, as a hand-over from the workstation leaves it; the command reads that mode from the manifest, so a manifest edited to say `local_and_remote` is not compared either, while its outputs still are. The command refuses the directory otherwise, before it starts an emitter. With `--local-only` it checks the directory and writes the staged manifest and the checksum file, but leaves the build manifest as it is, so later runs with the receipt can still compare it. It then hands the bundle over with the re-stage command's existing code, so the records, retries and landed-bundle handling are those of a directory built on the workstation. The command now reports a build manifest that is not valid JSON or not a JSON object, and an output that does not match its manifest digest, as an error message instead of a traceback. diff --git a/docs/uk-staging-operations.md b/docs/uk-staging-operations.md index d57c0191ef..735076a379 100644 --- a/docs/uk-staging-operations.md +++ b/docs/uk-staging-operations.md @@ -409,21 +409,28 @@ directory `--modal-state-root` names, either resolved the same way. The receipt must list the build manifest and every output it registers, at their paths under the state directory. An output the stage hashed but never copied to the runs volume (the receipt's `outputs_not_mirrored`) is named as such. -While the build manifest's `staged_dataset` record is still the build's own -`local_only` one, the manifest must have the receipt's SHA-256 and size, so a -manifest edited to register another file, rename a role or change any other -field is refused. Then every output must have the receipt's SHA-256 and size. -Every refusal comes before an emitter starts. `staged_manifest.json` and -`sha256sums.txt` are not compared, because staging writes them again, and the -build manifest is not compared once a hand-over has replaced its record. Then -the command stages the directory as above, under the build's own run id: the -hand-over, the records, a re-stage after a failed attempt and a second run on -a landed bundle work as they do for a directory built on the workstation. -Unset `HF_HUB_OFFLINE` first if your shell sets it: the command refuses to -stage while it is set. With `--local-only` it checks the receipt and rewrites -the sidecars and the build manifest; the manifest gets the build's own -`local_only` record again, in the build's own JSON rendering, so it keeps the -bytes the receipt lists. Nothing here submits the bundle to the collector: the +Unless the build manifest's `staged_dataset` record is `local_and_remote`, +the manifest must have the receipt's SHA-256 and size, so a manifest edited to +register another file the stage wrote, rename a role or change any other field +is refused. A hand-over from the workstation writes a `local_and_remote` +record and rewrites the manifest, so after one, even one that failed, the +manifest is not compared. The command reads that mode from the manifest +itself, so it cannot tell a record a hand-over wrote from one edited to say +`local_and_remote`: such an edit also ends the manifest's comparison, and the +edits above are then not caught. Every output must have the receipt's SHA-256 +and size whatever the record says, so an output whose bytes differ from the +receipt's is always refused. Every refusal comes before an emitter starts. +`staged_manifest.json` and `sha256sums.txt` are not compared, because staging +writes them again. Then the command stages the directory as above, under the +build's own run id: the hand-over, the records, a re-stage after a failed +attempt and a second run on a landed bundle work as they do for a directory +built on the workstation. Unset `HF_HUB_OFFLINE` first if your shell sets it: +the command refuses to stage while it is set. With `--local-only` it checks +the directory against the receipt and writes `staged_manifest.json` and +`sha256sums.txt`, but leaves the build manifest as it is, so later runs with +the receipt still compare it. (Without `--modal-receipt`, `--local-only` also +records the bundle as `local_only` in the build manifest.) Nothing here +submits the bundle to the collector: the command's emitter runs its Hugging Face module only, and builds do not submit artifacts to the collector's artifact intake yet (PolicyEngine/microcosm-collector#12). diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index 612050bfff..18831dbc0d 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -292,9 +292,10 @@ No program registered here writes a staged-dataset bundle yet; see "What this does not cover yet". A UK rowwise build's run directory, whose `rowwise_candidate_manifest.json` registers one, would be staged from the workstation after step 5, with the operator's own emitter and Hub credential: -`tools/stage_uk_rowwise_candidate.py --modal-receipt` checks the build -manifest and its outputs against the receipt and hands the bundle over as for -a local build (see [Staged datasets](uk-staging-operations.md#staged-datasets)). +`tools/stage_uk_rowwise_candidate.py --modal-receipt` checks the outputs the +build manifest registers against the receipt, and the manifest itself until +its record says a hand-over happened, then hands the bundle over as for a +local build (see [Staged datasets](uk-staging-operations.md#staged-datasets)). To prove the run path on a new commit or workspace for well under a cent, run `docs/us-modal-stage-smoke-plan.json` (tool `runner-smoke`). It is an diff --git a/tools/stage_uk_rowwise_candidate.py b/tools/stage_uk_rowwise_candidate.py index 8713a52980..be2f39d3d3 100644 --- a/tools/stage_uk_rowwise_candidate.py +++ b/tools/stage_uk_rowwise_candidate.py @@ -39,13 +39,20 @@ get`` has copied such a run back, ``--modal-receipt`` names the stage's receipt. The receipt must be of a stage that finished, and the run directory must be inside the run's copied-back state directory; both are checked before -any output is read. The build manifest, while its ``staged_dataset`` record is -still the build's own, and every output it registers must then be in the -receipt, at their paths under the state directory, with the same SHA-256 and -size. Otherwise the command refuses before it starts an emitter; when they -match, it stages the directory as above. The staged manifest and the checksum -file are not compared, because staging writes them again, and neither is the -build manifest once a hand-over has replaced its record. +any output is read. The receipt must list the build manifest and every output +it registers, at their paths under the state directory. Every output must have +the receipt's SHA-256 and size. So must the build manifest, unless its +``staged_dataset`` record is ``local_and_remote``, as a hand-over from the +workstation leaves it. The command reads that mode from the manifest itself, +so an edit that sets it also ends the manifest's comparison. Edits to the +manifest's other fields, including which files the stage wrote it registers +as outputs and under which roles, are then not caught; an output whose bytes +differ from the receipt's is still refused. Otherwise the command refuses before it starts an emitter; when everything +compared matches, it stages the directory as above. The staged manifest and +the checksum file are not compared, because staging writes them again. With +``--local-only`` the command checks the directory and writes those two files, +but leaves the build manifest as it is, so later runs with the receipt can +still compare it. Staging is not publication: ``releases/`` and ``latest.json`` are untouched. """ @@ -149,7 +156,13 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser.add_argument( "--local-only", action="store_true", - help="Verify the bundle and write the sidecars without uploading.", + help=( + "Verify the bundle and write the sidecars (staged_manifest.json and " + "sha256sums.txt) without uploading. Without --modal-receipt, also " + "record the bundle as local_only in the build manifest; with it, " + "leave the build manifest as it is. A directory whose manifest " + "records a landed bundle is left unchanged." + ), ) parser.add_argument( "--wait-seconds", @@ -169,7 +182,9 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "The receipt of the Modal stage that wrote --run-dir, as " "`modal volume get` copies it back " "(modal-runs//receipts/-.json). Every output the " - "manifest registers must be in it with the same SHA-256 and size." + "manifest registers must be in it with the same SHA-256 and size, " + "and so must the build manifest unless its staged_dataset record " + "is local_and_remote." ), ) parser.add_argument( @@ -273,9 +288,10 @@ def main(argv: list[str] | None = None) -> int: if _landed(existing): return _keep_landed(existing, "--local-only does not replace it", 0) _write_sidecars(bundle, manifest, repository=None) - staged = StagedBundleHandOver( - local_only_staged_dataset(bundle, prefix=UK_STAGED_DATASET_PREFIX) - ) + local_only = local_only_staged_dataset(bundle, prefix=UK_STAGED_DATASET_PREFIX) + if copied_back is not None: + return _leave_the_copied_back_manifest(local_only) + staged = StagedBundleHandOver(local_only) else: if hub_offline(): raise SystemExit( @@ -426,9 +442,9 @@ def _copied_back_stage( ``state/`` beside the receipt's ``receipts/`` directory, as ``modal volume get`` leaves them, resolved as ``--modal-state-root`` is. The receipt must list the build manifest and every output it registers; the build manifest - must also have the receipt's bytes while its record is still the build's - (:func:`_record_is_the_builds`). The command refuses otherwise, before any - output is hashed. + must also have the receipt's bytes unless its ``staged_dataset`` record is + ``local_and_remote`` (:func:`_record_is_the_builds`). The command refuses + otherwise, before any output is hashed. """ receipt_path = receipt_path.expanduser() @@ -495,20 +511,48 @@ def _copied_back_stage( def _record_is_the_builds(manifest: Mapping[str, Any]) -> bool: - """Whether the build manifest still holds the build's own staged record. + """Whether the build manifest is to be compared with the receipt. A build run with ``HF_HUB_OFFLINE``, as the Modal runner runs every tool, - records its bundle as ``local_only`` (``disabled`` with staging off). Only - a hand-over replaces that with a ``local_and_remote`` record, rewriting - the manifest when the emitter copied it. A ``--local-only`` re-stage writes - the same ``local_only`` record again, in the build's own JSON rendering, so - the manifest keeps the bytes the receipt lists. + records its bundle as ``local_only`` (``disabled`` with staging off), so + any record but a ``local_and_remote`` one counts as the build's own. A + hand-over from the workstation replaces it with a ``local_and_remote`` + record and rewrites the manifest; ``--local-only`` with ``--modal-receipt`` + leaves the manifest as it is (:func:`_leave_the_copied_back_manifest`). + + This reads only ``staged_dataset.mode``, from the manifest itself, so a + manifest edited to say ``local_and_remote`` is not compared either. No + condition read from the manifest can tell such an edit from a record a + hand-over wrote; every output it registers is still compared. """ record = manifest.get("staged_dataset") return not isinstance(record, Mapping) or record.get("mode") != "local_and_remote" +def _leave_the_copied_back_manifest(local_only: Mapping[str, Any]) -> int: + """``--local-only`` with ``--modal-receipt``: the sidecars are written, and + the build manifest stays as it is. + + The ``local_only`` record differs from the manifest's whenever the build + disabled its staged dataset, ``--run-id`` names another run id, a + national build changed its outputs after recording its staged dataset, + or a hand-over replaced the record. Writing it would leave a manifest + that still counts as the build's (:func:`_record_is_the_builds`) without + the receipt's bytes, which every later run with the receipt refuses. + """ + print( + "the build manifest stays as it is, so later runs with --modal-receipt " + "can still compare it with the receipt; staged_manifest.json and " + f"{SHA256SUMS_FILENAME} are written. The local_only record of the bundle, " + "which the manifest does not get:", + file=sys.stderr, + flush=True, + ) + print(json.dumps(local_only, indent=2, sort_keys=True)) + return 0 + + def _copy_back_refusal(run_dir: Path, problems: list[str]) -> SystemExit: return SystemExit( f"error: {run_dir} does not hold what the Modal stage wrote, so nothing is " From 6adad928fee09d43256c28a6d22ea5f3bbaa5ba9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:32:45 +0400 Subject: [PATCH 07/10] Say when a hand-over takes the build manifest out of the comparison A hand-over from the workstation writes its local_and_remote record into the build manifest only when the emitter copied the manifest; a manifest the emitter uploads from disk stays as handed over, keeps the receipt's bytes and is still compared. The command's docstrings, the UK staging guide and the changelog fragment now say so. Co-Authored-By: Claude Opus 5.5 --- changelog.d/1498-modal-copied-back-staging.added.md | 2 +- docs/uk-staging-operations.md | 6 ++++-- tools/stage_uk_rowwise_candidate.py | 8 +++++--- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/changelog.d/1498-modal-copied-back-staging.added.md b/changelog.d/1498-modal-copied-back-staging.added.md index 509ae7d2c4..b8a483f318 100644 --- a/changelog.d/1498-modal-copied-back-staging.added.md +++ b/changelog.d/1498-modal-copied-back-staging.added.md @@ -1 +1 @@ -`tools/stage_uk_rowwise_candidate.py --modal-receipt ` stages a UK run directory copied back from a Modal run with `modal volume get`, for when a UK build is registered with the Modal runner. Before it reads any output, it checks that the receipt is of a stage that finished (`COMPLETED`, not stopped at its budget) and that the directory is inside the run's copied-back state directory (`state/` beside the receipt's `receipts/` directory, or `--modal-state-root`, both resolved). The receipt must list the build manifest and every output it registers; an output the stage never copied to the runs volume (`outputs_not_mirrored`) is named as such. Every output must have the receipt's SHA-256 and size. So must the build manifest unless its `staged_dataset` record is `local_and_remote`, as a hand-over from the workstation leaves it; the command reads that mode from the manifest, so a manifest edited to say `local_and_remote` is not compared either, while its outputs still are. The command refuses the directory otherwise, before it starts an emitter. With `--local-only` it checks the directory and writes the staged manifest and the checksum file, but leaves the build manifest as it is, so later runs with the receipt can still compare it. It then hands the bundle over with the re-stage command's existing code, so the records, retries and landed-bundle handling are those of a directory built on the workstation. The command now reports a build manifest that is not valid JSON or not a JSON object, and an output that does not match its manifest digest, as an error message instead of a traceback. +`tools/stage_uk_rowwise_candidate.py --modal-receipt ` stages a UK run directory copied back from a Modal run with `modal volume get`, for when a UK build is registered with the Modal runner. Before it reads any output, it checks that the receipt is of a stage that finished (`COMPLETED`, not stopped at its budget) and that the directory is inside the run's copied-back state directory (`state/` beside the receipt's `receipts/` directory, or `--modal-state-root`, both resolved). The receipt must list the build manifest and every output it registers; an output the stage never copied to the runs volume (`outputs_not_mirrored`) is named as such. Every output must have the receipt's SHA-256 and size. So must the build manifest unless its `staged_dataset` record is `local_and_remote`, as a hand-over from the workstation leaves it when it rewrites the manifest; the command reads that mode from the manifest, so a manifest edited to say `local_and_remote` is not compared either, while its outputs still are. The command refuses the directory otherwise, before it starts an emitter. With `--local-only` it checks the directory and writes the staged manifest and the checksum file, but leaves the build manifest as it is, so later runs with the receipt can still compare it. It then hands the bundle over with the re-stage command's existing code, so the records, retries and landed-bundle handling are those of a directory built on the workstation. The command now reports a build manifest that is not valid JSON or not a JSON object, and an output that does not match its manifest digest, as an error message instead of a traceback. diff --git a/docs/uk-staging-operations.md b/docs/uk-staging-operations.md index 735076a379..2ec9cd20b9 100644 --- a/docs/uk-staging-operations.md +++ b/docs/uk-staging-operations.md @@ -413,8 +413,10 @@ Unless the build manifest's `staged_dataset` record is `local_and_remote`, the manifest must have the receipt's SHA-256 and size, so a manifest edited to register another file the stage wrote, rename a role or change any other field is refused. A hand-over from the workstation writes a `local_and_remote` -record and rewrites the manifest, so after one, even one that failed, the -manifest is not compared. The command reads that mode from the manifest +record into the manifest when the emitter copied the manifest, so after such +a hand-over, even one that failed, the manifest is not compared; a manifest +the emitter uploads from disk stays as handed over, with the receipt's bytes, +and is still compared. The command reads that mode from the manifest itself, so it cannot tell a record a hand-over wrote from one edited to say `local_and_remote`: such an edit also ends the manifest's comparison, and the edits above are then not caught. Every output must have the receipt's SHA-256 diff --git a/tools/stage_uk_rowwise_candidate.py b/tools/stage_uk_rowwise_candidate.py index be2f39d3d3..d44192a862 100644 --- a/tools/stage_uk_rowwise_candidate.py +++ b/tools/stage_uk_rowwise_candidate.py @@ -43,7 +43,7 @@ it registers, at their paths under the state directory. Every output must have the receipt's SHA-256 and size. So must the build manifest, unless its ``staged_dataset`` record is ``local_and_remote``, as a hand-over from the -workstation leaves it. The command reads that mode from the manifest itself, +workstation leaves it when it rewrites the manifest. The command reads that mode from the manifest itself, so an edit that sets it also ends the manifest's comparison. Edits to the manifest's other fields, including which files the stage wrote it registers as outputs and under which roles, are then not caught; an output whose bytes @@ -517,8 +517,10 @@ def _record_is_the_builds(manifest: Mapping[str, Any]) -> bool: records its bundle as ``local_only`` (``disabled`` with staging off), so any record but a ``local_and_remote`` one counts as the build's own. A hand-over from the workstation replaces it with a ``local_and_remote`` - record and rewrites the manifest; ``--local-only`` with ``--modal-receipt`` - leaves the manifest as it is (:func:`_leave_the_copied_back_manifest`). + record when the emitter copied the manifest, rewriting it; a manifest the + emitter uploads from disk stays as handed over, with the receipt's bytes. + ``--local-only`` with ``--modal-receipt`` leaves the manifest as it is + (:func:`_leave_the_copied_back_manifest`). This reads only ``staged_dataset.mode``, from the manifest itself, so a manifest edited to say ``local_and_remote`` is not compared either. No From 40ff74fe39adcf14d5706127565514466cb32689 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:50:06 +0400 Subject: [PATCH 08/10] Re-push so the pull request picks up this branch after GitHub's 2026-11-04 incident Co-Authored-By: Claude Opus 5.5 From 71e8d7bd99f85db9a4d46f21a0d7e50a2d59c9f8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:30:05 +0400 Subject: [PATCH 09/10] Test a copied-back build manifest the emitter did not copy Review round 3 of #1499 (code-quality point 4): no test covered a hand-over whose emitter queues the bundle without copying the build manifest. The command then leaves the manifest as handed over, with the receipt's bytes and the build's local_only record, so the next run with the receipt still compares it. The new test edits the manifest after such a hand-over and checks that the next run refuses it before an emitter starts. It guards existing behaviour, so it passes before and after the documentation changes that follow. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_modal_copy_back_staging.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py index 3e83180245..fbd16b5050 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py @@ -481,6 +481,45 @@ def test_an_output_edited_after_a_failed_hand_over_is_refused_by_its_receipt_ent assert hub.paths(PRIVATE_REPOSITORY) == [] +def test_a_build_manifest_the_emitter_did_not_copy_is_still_compared( + tmp_path, monkeypatch, capsys +): + """An emitter that queues the bundle without copying the build manifest + uploads it from disk later, so the command leaves the manifest as handed + over: it keeps the receipt's bytes and the build's ``local_only`` record. + The next run with the receipt still compares it, so an edit made after + that hand-over is refused before an emitter starts.""" + hub, copied, receipt = _modal_build(tmp_path, monkeypatch) + manifest_bytes = (copied / MANIFEST).read_bytes() + queue = FakeHandoverQueue() + stager = load_tool("stage_uk_rowwise_candidate") + _workstation_emitters( + monkeypatch, + stager, + hub_files=hub.files, + queue=queue, + never_copy={MANIFEST}, + deliver=False, + answer_receipts=False, + ) + capsys.readouterr() + assert stager.main(_staging_argv(copied, receipt, "--wait-seconds", "0")) == 1 + assert f"{MANIFEST} stays as handed over" in capsys.readouterr().err + assert (copied / MANIFEST).read_bytes() == manifest_bytes + _edit_the_build_manifest(copied, lambda manifest: _change_a_field(manifest, copied)) + before = _files(copied) + started = _workstation_emitters( + monkeypatch, stager, hub_files=hub.files, hub_api=hub, queue=queue + ) + + message = _refusal(stager, _staging_argv(copied, receipt)) + + assert f"out/{MANIFEST} is not the build manifest the Modal stage wrote" in message + assert started == [] + assert _files(copied) == before + assert hub.paths(PRIVATE_REPOSITORY) == [] + + def test_hf_hub_offline_on_the_workstation_stages_nothing( tmp_path, monkeypatch, capsys ): From dce6e1e5d7fc5d30d5bf494ee6729bf31868931d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:30:05 +0400 Subject: [PATCH 10/10] Correct the copied-back staging texts after review round 3 Review round 3 of #1499 (code-quality points 1 and 2): - The --modal-receipt help and the Modal runbook's pointer now say that the build manifest's record is read from the manifest itself, so an edit that says a hand-over happened is not caught. - "Later runs with the receipt still compare it" now holds only for a manifest that still has the build's record. - Any attempt that records its outcome in the manifest writes a local_and_remote record, refused attempts included; a bundle queued without a copy of the manifest leaves the manifest as handed over. - The module docstring is wrapped again, and its refusal sentence no longer reads as the reverse of the one before it. - The changelog fragment describes the hand-over before --local-only. - The UK staging guide and the --local-only help warn that --local-only without --modal-receipt writes a local_only record, which on a copied-back directory can make every later run with the receipt refuse it, and say to pass the receipt. - The note --local-only prints with the receipt no longer says later runs compare the manifest. Co-Authored-By: Claude Opus 5.5 --- .../1498-modal-copied-back-staging.added.md | 2 +- docs/uk-staging-operations.md | 29 +++++--- docs/us-modal-stage-runbook.md | 4 +- tools/stage_uk_rowwise_candidate.py | 66 +++++++++++-------- 4 files changed, 61 insertions(+), 40 deletions(-) diff --git a/changelog.d/1498-modal-copied-back-staging.added.md b/changelog.d/1498-modal-copied-back-staging.added.md index b8a483f318..f06c2adadf 100644 --- a/changelog.d/1498-modal-copied-back-staging.added.md +++ b/changelog.d/1498-modal-copied-back-staging.added.md @@ -1 +1 @@ -`tools/stage_uk_rowwise_candidate.py --modal-receipt ` stages a UK run directory copied back from a Modal run with `modal volume get`, for when a UK build is registered with the Modal runner. Before it reads any output, it checks that the receipt is of a stage that finished (`COMPLETED`, not stopped at its budget) and that the directory is inside the run's copied-back state directory (`state/` beside the receipt's `receipts/` directory, or `--modal-state-root`, both resolved). The receipt must list the build manifest and every output it registers; an output the stage never copied to the runs volume (`outputs_not_mirrored`) is named as such. Every output must have the receipt's SHA-256 and size. So must the build manifest unless its `staged_dataset` record is `local_and_remote`, as a hand-over from the workstation leaves it when it rewrites the manifest; the command reads that mode from the manifest, so a manifest edited to say `local_and_remote` is not compared either, while its outputs still are. The command refuses the directory otherwise, before it starts an emitter. With `--local-only` it checks the directory and writes the staged manifest and the checksum file, but leaves the build manifest as it is, so later runs with the receipt can still compare it. It then hands the bundle over with the re-stage command's existing code, so the records, retries and landed-bundle handling are those of a directory built on the workstation. The command now reports a build manifest that is not valid JSON or not a JSON object, and an output that does not match its manifest digest, as an error message instead of a traceback. +`tools/stage_uk_rowwise_candidate.py --modal-receipt ` stages a UK run directory copied back from a Modal run with `modal volume get`, for when a UK build is registered with the Modal runner. Before it reads any output, it checks that the receipt is of a stage that finished (`COMPLETED`, not stopped at its budget) and that the directory is inside the run's copied-back state directory (`state/` beside the receipt's `receipts/` directory, or `--modal-state-root`, both resolved). The receipt must list the build manifest and every output it registers; an output the stage never copied to the runs volume (`outputs_not_mirrored`) is named as such. Every output must have the receipt's SHA-256 and size. So must the build manifest unless its `staged_dataset` record is `local_and_remote`, as an attempt to hand the directory over from the workstation leaves it whenever it records its outcome in the manifest; the command reads that mode from the manifest, so a manifest edited to say `local_and_remote` is not compared either, while its outputs still are. Every refusal comes before the command starts an emitter. A directory that passes is handed over with the re-stage command's existing code, so the records, retries and landed-bundle handling are those of a directory built on the workstation. With `--local-only` and `--modal-receipt`, the command hands nothing over: it checks the directory and writes the staged manifest and the checksum file, but leaves the build manifest as it is, so a manifest that still holds the build's record is still compared by later runs with the receipt. On a copied-back directory, pass the receipt with `--local-only`: without it, `--local-only` writes a `local_only` record into the build manifest, which can make every later run with the receipt refuse the directory. The command now reports a build manifest that is not valid JSON or not a JSON object, and an output that does not match its manifest digest, as an error message instead of a traceback. diff --git a/docs/uk-staging-operations.md b/docs/uk-staging-operations.md index 2ec9cd20b9..0296a94707 100644 --- a/docs/uk-staging-operations.md +++ b/docs/uk-staging-operations.md @@ -412,11 +412,12 @@ to the runs volume (the receipt's `outputs_not_mirrored`) is named as such. Unless the build manifest's `staged_dataset` record is `local_and_remote`, the manifest must have the receipt's SHA-256 and size, so a manifest edited to register another file the stage wrote, rename a role or change any other field -is refused. A hand-over from the workstation writes a `local_and_remote` -record into the manifest when the emitter copied the manifest, so after such -a hand-over, even one that failed, the manifest is not compared; a manifest -the emitter uploads from disk stays as handed over, with the receipt's bytes, -and is still compared. The command reads that mode from the manifest +is refused. An attempt to hand the directory over from the workstation that +records its outcome in the manifest writes a `local_and_remote` record, +whether the bundle landed, failed or was refused, so after such an attempt the +manifest is not compared. A bundle the emitter queued without copying the +manifest leaves the manifest as handed over, with the receipt's bytes and the +build's record, and it is then still compared. The command reads that mode from the manifest itself, so it cannot tell a record a hand-over wrote from one edited to say `local_and_remote`: such an edit also ends the manifest's comparison, and the edits above are then not caught. Every output must have the receipt's SHA-256 @@ -429,11 +430,19 @@ attempt and a second run on a landed bundle work as they do for a directory built on the workstation. Unset `HF_HUB_OFFLINE` first if your shell sets it: the command refuses to stage while it is set. With `--local-only` it checks the directory against the receipt and writes `staged_manifest.json` and -`sha256sums.txt`, but leaves the build manifest as it is, so later runs with -the receipt still compare it. (Without `--modal-receipt`, `--local-only` also -records the bundle as `local_only` in the build manifest.) Nothing here -submits the bundle to the collector: the -command's emitter runs its Hugging Face module only, and builds do not submit +`sha256sums.txt`, but leaves the build manifest as it is, so a manifest that +still holds the build's record is still compared by later runs with the +receipt. + +> **Warning:** on a copied-back directory, always pass `--modal-receipt` with +> `--local-only`. Without the receipt, `--local-only` writes a `local_only` +> record into the build manifest. Whenever that record differs from the +> build's own (a build that disabled its staged dataset, another `--run-id`, a +> national build, or a hand-over that did not land), every later run with the +> receipt refuses the directory as "not the build manifest the Modal stage +> wrote". If that has happened, fetch the run again with `modal volume get`. + +Nothing here submits the bundle to the collector: the command's emitter runs its Hugging Face module only, and builds do not submit artifacts to the collector's artifact intake yet (PolicyEngine/microcosm-collector#12). diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index ce86520f7f..d045ce2339 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -421,7 +421,9 @@ workstation after step 5, with the operator's own emitter and Hub credential: `tools/stage_uk_rowwise_candidate.py --modal-receipt` checks the outputs the build manifest registers against the receipt, and the manifest itself until its record says a hand-over happened, then hands the bundle over as for a -local build (see [Staged datasets](uk-staging-operations.md#staged-datasets)). +local build. It reads that record from the manifest itself, so an edit that +says a hand-over happened is not caught; the outputs are still compared (see +[Staged datasets](uk-staging-operations.md#staged-datasets)). To prove the run path on a new commit or workspace for well under a cent, run `docs/us-modal-stage-smoke-plan.json` (tool `runner-smoke`). It is an diff --git a/tools/stage_uk_rowwise_candidate.py b/tools/stage_uk_rowwise_candidate.py index d44192a862..83d27ba7b3 100644 --- a/tools/stage_uk_rowwise_candidate.py +++ b/tools/stage_uk_rowwise_candidate.py @@ -34,25 +34,29 @@ the remote bundle is otherwise refused. No UK program is registered with the Modal runner yet. A UK build run there -would stage nothing from its container: the runner sets ``HF_HUB_OFFLINE``, -so the build would record its bundle as ``local_only``. Once ``modal volume -get`` has copied such a run back, ``--modal-receipt`` names the stage's -receipt. The receipt must be of a stage that finished, and the run directory -must be inside the run's copied-back state directory; both are checked before -any output is read. The receipt must list the build manifest and every output -it registers, at their paths under the state directory. Every output must have -the receipt's SHA-256 and size. So must the build manifest, unless its -``staged_dataset`` record is ``local_and_remote``, as a hand-over from the -workstation leaves it when it rewrites the manifest. The command reads that mode from the manifest itself, -so an edit that sets it also ends the manifest's comparison. Edits to the -manifest's other fields, including which files the stage wrote it registers -as outputs and under which roles, are then not caught; an output whose bytes -differ from the receipt's is still refused. Otherwise the command refuses before it starts an emitter; when everything -compared matches, it stages the directory as above. The staged manifest and -the checksum file are not compared, because staging writes them again. With -``--local-only`` the command checks the directory and writes those two files, -but leaves the build manifest as it is, so later runs with the receipt can -still compare it. +would stage nothing from its container: the runner sets ``HF_HUB_OFFLINE``, so +the build would record its bundle as ``local_only``. Once ``modal volume get`` +has copied such a run back, ``--modal-receipt`` names the stage's receipt. The +receipt must be of a stage that finished, and the run directory must be inside +the run's copied-back state directory; both are checked before any output is +read. The receipt must list the build manifest and every output it registers, +at their paths under the state directory. Every output must have the receipt's +SHA-256 and size. So must the build manifest, unless its ``staged_dataset`` +record is ``local_and_remote``, as an attempt to hand the directory over from +the workstation leaves it whenever it records its outcome in the manifest. The +command reads that mode from the manifest itself, so an edit that sets it also +ends the manifest's comparison. Edits to the manifest's other fields, +including which files the stage wrote it registers as outputs and under which +roles, are then not caught; an output whose bytes differ from the receipt's is +still refused. Every refusal comes before the command starts an emitter, and a +directory that passes is staged as above. The staged manifest and the checksum +file are not compared, because staging writes them again. With +``--local-only`` the command checks the directory and writes those two files +but leaves the build manifest as it is, so a manifest that still holds the +build's record is still compared by later runs with the receipt. Without +``--modal-receipt``, ``--local-only`` writes a ``local_only`` record into the +build manifest, which on a copied-back directory can make every later run with +the receipt refuse it; pass the receipt with ``--local-only`` there. Staging is not publication: ``releases/`` and ``latest.json`` are untouched. """ @@ -161,7 +165,9 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "sha256sums.txt) without uploading. Without --modal-receipt, also " "record the bundle as local_only in the build manifest; with it, " "leave the build manifest as it is. A directory whose manifest " - "records a landed bundle is left unchanged." + "records a landed bundle is left unchanged. On a directory copied " + "back from Modal, pass --modal-receipt too: the local_only record " + "can make every later run with the receipt refuse the directory." ), ) parser.add_argument( @@ -184,7 +190,9 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "(modal-runs//receipts/-.json). Every output the " "manifest registers must be in it with the same SHA-256 and size, " "and so must the build manifest unless its staged_dataset record " - "is local_and_remote." + "is local_and_remote. That mode is read from the manifest itself, " + "so an edit that sets it is not caught; the outputs are still " + "compared." ), ) parser.add_argument( @@ -515,11 +523,13 @@ def _record_is_the_builds(manifest: Mapping[str, Any]) -> bool: A build run with ``HF_HUB_OFFLINE``, as the Modal runner runs every tool, records its bundle as ``local_only`` (``disabled`` with staging off), so - any record but a ``local_and_remote`` one counts as the build's own. A - hand-over from the workstation replaces it with a ``local_and_remote`` - record when the emitter copied the manifest, rewriting it; a manifest the - emitter uploads from disk stays as handed over, with the receipt's bytes. - ``--local-only`` with ``--modal-receipt`` leaves the manifest as it is + any record but a ``local_and_remote`` one counts as the build's own. An + attempt to hand the directory over from the workstation that records its + outcome in the manifest writes a ``local_and_remote`` record, whether the + bundle landed, failed or was refused. A bundle the emitter queued without + copying the manifest leaves the manifest as handed over, with the + receipt's bytes and the build's record. ``--local-only`` with + ``--modal-receipt`` leaves the manifest as it is (:func:`_leave_the_copied_back_manifest`). This reads only ``staged_dataset.mode``, from the manifest itself, so a @@ -544,8 +554,8 @@ def _leave_the_copied_back_manifest(local_only: Mapping[str, Any]) -> int: the receipt's bytes, which every later run with the receipt refuses. """ print( - "the build manifest stays as it is, so later runs with --modal-receipt " - "can still compare it with the receipt; staged_manifest.json and " + "the build manifest is left unchanged for later runs with " + "--modal-receipt; staged_manifest.json and " f"{SHA256SUMS_FILENAME} are written. The local_only record of the bundle, " "which the manifest does not get:", file=sys.stderr,