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..f06c2adadf --- /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`, 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 4ae2b75cd9..0296a94707 100644 --- a/docs/uk-staging-operations.md +++ b/docs/uk-staging-operations.md @@ -383,7 +383,70 @@ 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`). + +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 \ + --run-dir ./modal-runs//state/ \ + --modal-receipt ./modal-runs//receipts/-.json +``` + +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. +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. 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 +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 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). + +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 f0eea42e5c..d045ce2339 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -414,6 +414,17 @@ python3 tools/modal_us_stage_plan.py verify-receipt \ --state-root ./modal-runs//state ``` +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 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. 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 inline script, so it needs no file in the pinned tree. It imports the synced @@ -1622,6 +1633,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` 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. - **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_full_build_cli.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_full_build_cli.py index 2b46b239eb..0cb9856441 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..fbd16b5050 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_modal_copy_back_staging.py @@ -0,0 +1,843 @@ +"""Staging a UK build's outputs once they are copied back from a Modal run. + +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 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 + +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" +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, *, staging=None): + """A dense build run as the Modal runner runs it, then copied back. + + ``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=staging) + 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 _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() + 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_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) + + +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") + + +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_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, + 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", + 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 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) + 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, + 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( + 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 + 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 + 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, 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)) == 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"] == "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 + + +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_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 +): + """``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 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()) + + +@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 +): + """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, queue=queue + ) + + assert ( + _completes(stager, _staging_argv(copied, receipt, "--local-only", *run_id)) == 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 + + +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( + ("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/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 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..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, @@ -47,7 +49,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 +104,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 +139,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 +385,68 @@ 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 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( + [ + "--run-dir", + str(copied), + "--repo-id", + REPOSITORY, + "--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 staged["run_id"] == RUN_ID + 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/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("__")] diff --git a/tools/stage_uk_rowwise_candidate.py b/tools/stage_uk_rowwise_candidate.py index 153ee81fef..83d27ba7b3 100644 --- a/tools/stage_uk_rowwise_candidate.py +++ b/tools/stage_uk_rowwise_candidate.py @@ -33,6 +33,31 @@ keeps the manifest's records and says so. A directory whose bytes differ from 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 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. """ @@ -40,12 +65,13 @@ import argparse import glob +import hashlib import json import math 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 +108,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" @@ -127,7 +160,15 @@ 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. 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( "--wait-seconds", @@ -140,7 +181,32 @@ 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, " + "and so must the build manifest unless its staged_dataset record " + "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( + "--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: @@ -171,22 +237,46 @@ 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") - 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"), - }, + 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, + 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 copied_back is not None: + problems = copied_back.output_problems(bundle) + if problems: + raise _copy_back_refusal(run_dir, problems) existing = _valid_record(manifest.get("staged_dataset")) handed_over = ( None @@ -206,9 +296,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( @@ -299,6 +390,188 @@ def main(argv: list[str] | None = None) -> int: return 0 if delivery["status"] != "failed" else 1 +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, + 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, 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 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() + try: + receipt = json.loads(receipt_path.read_text(encoding="utf-8")) + except (OSError, ValueError) as 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 + ): + 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() + try: + relative = PurePosixPath(*run_dir.relative_to(root).parts) + except ValueError: + 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} 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" + ) + 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 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), so + 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 + 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 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, + 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 " + "staged:\n" + "\n".join(f" - {problem}" for problem in problems) + ) + + def _write_sidecars( bundle: StagedDatasetBundle, manifest: dict, *, repository: str | None ) -> None: