diff --git a/README.md b/README.md index 1cf8eb3756..65bdbaf6af 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,8 @@ added `microcosm-emitter status`, which the US Modal stage runner runs after each stage to record how many telemetry events the stage's emitter left undelivered. The release is written once, in `packages/microcosm-build/src/microcosm/build/minimum_emitter_version.json`, -which builds read as package data and the Modal image's install step reads +which builds read as package data and the install steps of the Modal images +(the US stage runner's and the UK launcher's, `tools/modal_uk_cut.py`) read from the launching checkout. Releases before 0.10.0 send telemetry to the collector's Cloud Run address, which changes when the collector moves to another Google Cloud project; from 0.10.0 on, releases send to the diff --git a/changelog.d/1757-uk-modal-launcher-emitter.fixed.md b/changelog.d/1757-uk-modal-launcher-emitter.fixed.md new file mode 100644 index 0000000000..37968a605a --- /dev/null +++ b/changelog.d/1757-uk-modal-launcher-emitter.fixed.md @@ -0,0 +1 @@ +`tools/modal_uk_cut.py`'s image installs the separately installed `microcosm-emitter` (microcosm#1757), so a UK build run on Modal no longer stops at `run_uk_cut.py`'s preflight, which starts the emitter to check write access (#1460). As in the US Modal image, the install step asks for `microcosm-emitter>=` the release `packages/microcosm-build/src/microcosm/build/minimum_emitter_version.json` names in the launching checkout, installs it into `/usr/local/bin` outside the environment the container syncs, and runs its `version` so a command that cannot run fails the image build; `MICROCOSM_EMITTER_COMMAND` points the build at it. Before it downloads anything, the image now also drops the compromised eMudhra (emSign) certificate authorities as the US image does (`emudhra-ca-trust`): it upgrades `ca-certificates`, replaces the base's pip 25.3 with the hash-pinned pip 26.2.2, and installs uv 0.13.4 instead of 0.11.7 and certifi 2026.10.19 or later for the image's own Python; it also sets `UV_PYTHON_DOWNLOADS=never`. The launcher refuses a minimum file it cannot read, its plan names the emitter requirement, and the plan refuses a commit whose tree it cannot read, or whose `minimum_emitter_version.json` names a higher release than the launching checkout's, which the build's preflight would otherwise refuse in the paid container. The emitter's event queue files stay in the container's cache directory, as in the US runner, so hand-overs still queued when the container exits are lost with it. The launcher has still never run on Modal. diff --git a/docs/orrery-publication.md b/docs/orrery-publication.md index 721e9a05aa..60feea124e 100644 --- a/docs/orrery-publication.md +++ b/docs/orrery-publication.md @@ -146,8 +146,13 @@ Hugging Face. (`>=0.16.0,<1`), the dependency-free package of typed calls, which `uv.lock` records with its hashes. The emitter itself, `microcosm-emitter`, is not a workspace dependency: each machine installs it on its own with -`uv tool install microcosm-emitter`, and the Modal image installs the newest -release when it is built for a plan commit. A running build keeps the +`uv tool install microcosm-emitter`. The US Modal stage runner's image +installs the newest release when it is built for a plan commit; the UK +launcher's image (`tools/modal_uk_cut.py`), which clones its commit only at +run time, installs the newest release when Modal first builds that step and +keeps it until the minimum below rises or Modal rebuilds the layer, as it +does when an earlier step of the image or Modal's image builder version +changes. A running build keeps the emitter it started; the next build uses whichever release is installed then. So an emitter release needs no Microcosm change. The socket protocol carries its own version (`PROTOCOL_VERSION`), every emitter release accepts the @@ -155,18 +160,22 @@ versions interfaces still send, and an emitter that lacks a module the build asks for starts without it. A build does not start an emitter older than `MINIMUM_EMITTER_VERSION` in -`microcosm.build.telemetry_emitter`, now 0.17.0, and the Modal image installs -at least the same release (`image_emitter_requirement()` in -`tools/modal_us_stage_plan.py`, `microcosm-emitter>=0.17.0`). The release is +`microcosm.build.telemetry_emitter`, now 0.17.0, and both Modal images install +at least the same release (`microcosm-emitter>=0.17.0`): the US stage +runner's through `image_emitter_requirement()` in +`tools/modal_us_stage_plan.py`, the UK launcher's through +`emitter_requirement()` in `tools/modal_uk_cut.py`. The release is written once, in microcosm-build's package data, `packages/microcosm-build/src/microcosm/build/minimum_emitter_version.json`: -the adapter reads it as package data, and the runner, which imports nothing -from the workspace, reads it by its path in the checkout that launches the -app. The image adds that checkout's file beside the runner's copy of the -plan module, so the check, which runs in the container, reads the same -file. At a Modal launch the install step therefore comes from the launching -checkout and the minimum from the commit the plan pins (see the -[US Modal stage runbook](us-modal-stage-runbook.md)). Releases +the adapter reads it as package data, and both launchers, which import +nothing from the workspace, read it by its path in the checkout that +launches the app. At a Modal launch the install step therefore comes from +the launching checkout and the minimum from the commit the build runs. The +US runner's image adds the launching checkout's file beside its copy of the +plan module, so its check, which runs in the container, reads the same file +(see the [US Modal stage runbook](us-modal-stage-runbook.md)). The UK +launcher's plan reads the commit's file with `git show` and refuses a +commit whose minimum is higher than the launching checkout's. Releases before 0.10.0 send telemetry to the collector's Cloud Run address, which changes when the collector moves to another Google Cloud project. From 0.10.0 on, the emitter's default collector address is the collector's hostname, diff --git a/docs/uk-cut-anyone.md b/docs/uk-cut-anyone.md index ce82d62e4e..c189738d48 100644 --- a/docs/uk-cut-anyone.md +++ b/docs/uk-cut-anyone.md @@ -127,6 +127,14 @@ the Mac is busy, short of disk or asleep. The container: - clones a pushed commit on main; - syncs that commit's own lock with the `uk` extra; +- runs the `microcosm-emitter` its image installs, at or above the release + `minimum_emitter_version.json` names in the checkout you launch from, as + the US Modal image does. The build checks the minimum of the commit it + clones, so the plan refuses a commit whose minimum is higher: launch from + a checkout at or after that commit. Like the US image, the image first + drops the compromised eMudhra certificate authorities (an upgraded CA + store, a hash-pinned pip, uv 0.13.4 and a certifi floor) before it + downloads anything; - keeps the work directory, with its inputs and every step's outputs, on the `microcosm-uk-cuts` volume, so a rerun resumes. diff --git a/packages/microcosm-build/src/microcosm/build/telemetry_emitter.py b/packages/microcosm-build/src/microcosm/build/telemetry_emitter.py index 871633d966..be159157db 100644 --- a/packages/microcosm-build/src/microcosm/build/telemetry_emitter.py +++ b/packages/microcosm-build/src/microcosm/build/telemetry_emitter.py @@ -112,9 +112,10 @@ STARTUP_TIMEOUT_SECONDS = 15.0 #: The package data file that holds the oldest emitter release a build #: starts, ``MINIMUM_EMITTER_VERSION``. It is the one place the release is -#: written: the Modal stage runner (``tools/modal_us_stage_plan.py``), which -#: imports nothing from the workspace, reads the same file by its path in the -#: checkout that launches it, and installs at least that release in its image. +#: written: the US Modal stage runner (``tools/modal_us_stage_plan.py``) and +#: the UK Modal launcher (``tools/modal_uk_cut.py``), which import nothing +#: from the workspace, read the same file by its path in the checkout that +#: launches them, and install at least that release in their images. MINIMUM_EMITTER_VERSION_RESOURCE = "minimum_emitter_version.json" _RELEASE_NUMBER = re.compile(r"(\d+)\.(\d+)\.(\d+)") diff --git a/packages/microcosm-build/tests/engine_free/uk/test_modal_uk_cut.py b/packages/microcosm-build/tests/engine_free/uk/test_modal_uk_cut.py index 3277591051..3b59e02b7e 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_modal_uk_cut.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_modal_uk_cut.py @@ -3,6 +3,8 @@ from __future__ import annotations import importlib.util +import json +import re import shutil import sys from pathlib import Path @@ -59,14 +61,48 @@ def test_without_the_opt_in_no_credential_is_attached(monkeypatch): module.main("a" * 40, "t", run=True) +def _git_answering(module, commit_minimum, *, commit_readable=True): + """``subprocess.run`` for ``plan``: the commit is on main, and its + ``minimum_emitter_version.json`` names ``commit_minimum`` (``None``: the + commit has no such file, as before microcosm#1522). Without + ``commit_readable``, git cannot read the commit's tree, and answers + ``ls-tree`` and ``show`` as it does then.""" + + def run(argv, **kwargs): + unreadable = module.subprocess.CompletedProcess( + argv, 128, stdout="", stderr="fatal: not a tree object" + ) + if argv[:2] == ["git", "ls-tree"]: + if not commit_readable: + return unreadable + listed = "" if commit_minimum is None else f"{argv[-1]}\n" + return module.subprocess.CompletedProcess(argv, 0, stdout=listed, stderr="") + if argv[:2] == ["git", "show"]: + if not commit_readable or commit_minimum is None: + return unreadable + return module.subprocess.CompletedProcess( + argv, + 0, + stdout=json.dumps({"minimum_emitter_version": commit_minimum}), + stderr="", + ) + return module.subprocess.CompletedProcess(argv, 0) + + return run + + +def _launching_minimum(): + from microcosm.build.telemetry_emitter import MINIMUM_EMITTER_VERSION + + return MINIMUM_EMITTER_VERSION + + def test_planning_contacts_no_modal_service(monkeypatch, capsys): monkeypatch.setenv("HF_TOKEN", "hf-test") monkeypatch.delenv(UK_GATE_SIGNING_KEY_ENV, raising=False) module, stub = _load_app(monkeypatch) monkeypatch.setattr( - module.subprocess, - "run", - lambda argv, **kw: module.subprocess.CompletedProcess(argv, 0), + module.subprocess, "run", _git_answering(module, _launching_minimum()) ) stub.reset_mock() assert module.plan("a" * 40, "t") == [UK_GATE_SIGNING_KEY_ENV] @@ -74,16 +110,231 @@ def test_planning_contacts_no_modal_service(monkeypatch, capsys): assert "missing credentials" in capsys.readouterr().out +def _image_steps(stub, step): + """The calls named ``step`` the module made on the stub, in order.""" + + return [entry for entry in stub.mock_calls if entry[0].split(".")[-1] == step] + + +def _image_chain(stub): + """Each image-definition call as (step name, arguments), in order.""" + + return [ + (name.rsplit(".", 1)[-1], args) + for name, args, _ in stub.mock_calls + if name.startswith("Image.debian_slim") + ] + + +def _emitter_installs(stub): + return [ + step.args + for step in _image_steps(stub, "run_commands") + if any("microcosm-emitter" in command for command in step.args) + ] + + +def _load_us_plan(monkeypatch): + """The US Modal stage runner's plan module, loaded by path like the tools.""" + + spec = importlib.util.spec_from_file_location( + "modal_us_stage_plan_beside_uk_launcher", + ROOT / "tools" / "modal_us_stage_plan.py", + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + # dataclasses resolve string annotations through sys.modules. + monkeypatch.setitem(sys.modules, spec.name, module) + spec.loader.exec_module(module) + return module + + def test_the_image_carries_the_registry_for_the_container(monkeypatch): module, stub = _load_app(monkeypatch) - built = stub.Image.debian_slim.return_value.apt_install.return_value - added = built.pip_install.return_value.env.return_value.add_local_file - added.assert_called_once_with(str(module.REGISTRY_SOURCE), module.REGISTRY_REMOTE) + # The registry's copy is the last step, called on the image the emitter's + # install returns: Modal refuses build steps after a local file. + added = [ + entry + for entry in stub.mock_calls + if entry[0] + == ( + "Image.debian_slim().apt_install().run_commands().pip_install()" + ".env().run_commands().add_local_file" + ) + ] + assert [entry.args for entry in added] == [ + (str(module.REGISTRY_SOURCE), module.REGISTRY_REMOTE) + ] + assert _image_chain(stub)[-1][0] == "add_local_file" assert module.REGISTRY_SOURCE.is_file() # Modal places the app module in /root, beside the registry's copy. assert Path(module.REGISTRY_REMOTE).parent == Path("/root") +def test_the_image_trusts_no_compromised_certificate_authority(monkeypatch): + """As the US Modal image does, before anything is downloaded. + + The compromised eMudhra (emSign) roots: uv before 0.13.4 compiles them in, + the cached base's pip 25.3 bundles them, and the base's CA store, which + git and the standard library read, holds them until it is upgraded. + """ + + us_plan = _load_us_plan(monkeypatch) + _, stub = _load_app(monkeypatch) + chain = _image_chain(stub) + assert [name for name, _ in chain] == [ + "debian_slim", + "apt_install", + "run_commands", + "pip_install", + "env", + "run_commands", + "add_local_file", + ] + assert "ca-certificates" in chain[1][1] + assert chain[2][1] == (us_plan.image_pip_bootstrap_command(),) + # certifi for the image's own Python, which Modal's client uses. + assert chain[3][1] == ( + f"uv=={us_plan.IMAGE_UV_VERSION}", + f"certifi>={us_plan.RUNNER_CERTIFI_MINIMUM_VERSION}", + ) + + +def test_the_image_installs_the_emitter_at_the_builds_minimum_release(monkeypatch): + """The pre-flight starts the separately installed emitter (#1410, #1460).""" + + _, stub = _load_app(monkeypatch) + assert _emitter_installs(stub) == [ + ( + "UV_TOOL_BIN_DIR=/usr/local/bin uv tool install " + f"'microcosm-emitter>={_launching_minimum()}'", + "/usr/local/bin/microcosm-emitter version", + ) + ] + + +def test_the_build_is_pointed_at_the_installed_emitter(monkeypatch): + _, stub = _load_app(monkeypatch) + (environment,) = _image_steps(stub, "env") + assert environment.args[0].get("MICROCOSM_EMITTER_COMMAND") == ( + "/usr/local/bin/microcosm-emitter" + ) + + +def test_uv_never_downloads_a_python_in_the_image(monkeypatch): + """The image's 3.13 meets the lock and the emitter, as CI tests the lock.""" + + _, stub = _load_app(monkeypatch) + (environment,) = _image_steps(stub, "env") + assert environment.args[0].get("UV_PYTHON_DOWNLOADS") == "never" + + +def test_the_launchers_agree_on_the_emitter(monkeypatch): + us_plan = _load_us_plan(monkeypatch) + module, _ = _load_app(monkeypatch) + assert module.emitter_requirement() == us_plan.image_emitter_requirement() + assert module.EMITTER_COMMAND == us_plan.IMAGE_EMITTER_COMMAND + assert module.EMITTER_COMMAND_ENV == us_plan.EMITTER_COMMAND_ENV + + +@pytest.mark.parametrize( + "content", + [ + None, + "not json", + "[]", + '{"minimum_emitter_version": 17}', + '{"minimum_emitter_version": "0.17"}', + '{"minimum_emitter_version": "0.17.0 "}', + ], +) +def test_an_unreadable_minimum_release_stops_the_image_definition( + monkeypatch, tmp_path, content +): + module, _ = _load_app(monkeypatch) + version_file = tmp_path / "minimum_emitter_version.json" + if content is not None: + version_file.write_text(content, encoding="utf-8") + monkeypatch.setattr( + module, "MINIMUM_EMITTER_VERSION_FILE", version_file, raising=False + ) + with pytest.raises(SystemExit, match=re.escape(str(version_file))): + module._image() + + +def test_the_container_defines_the_image_without_the_checkout(monkeypatch, tmp_path): + """The container imports the module at /root, with no checkout around it.""" + + module, stub = _load_app(monkeypatch) + monkeypatch.setattr( + module, + "MINIMUM_EMITTER_VERSION_FILE", + tmp_path / "missing" / "minimum_emitter_version.json", + raising=False, + ) + stub.is_local.return_value = False + stub.reset_mock() + module._image() + assert _emitter_installs(stub) == [] + assert _image_steps(stub, "add_local_file") == [] + + +def test_the_plan_names_the_emitter_the_image_installs(monkeypatch, capsys): + module, _ = _load_app(monkeypatch) + monkeypatch.setattr( + module.subprocess, "run", _git_answering(module, _launching_minimum()) + ) + module.plan("a" * 40, "t") + assert f"emitter microcosm-emitter>={_launching_minimum()}" in ( + capsys.readouterr().out + ) + + +def test_the_plan_refuses_a_commit_that_needs_a_newer_emitter(monkeypatch): + """Preflight in the paid container would refuse the image's emitter.""" + + module, _ = _load_app(monkeypatch) + monkeypatch.setattr(module.subprocess, "run", _git_answering(module, "99.0.0")) + with pytest.raises(SystemExit, match=r"99\.0\.0.*checkout at or after"): + module.plan("a" * 40, "t") + + +def test_the_plan_refuses_a_commit_whose_tree_it_cannot_read(monkeypatch): + """git answers a missing commit and a missing path alike (exit 128).""" + + module, _ = _load_app(monkeypatch) + monkeypatch.setattr( + module.subprocess, + "run", + _git_answering(module, _launching_minimum(), commit_readable=False), + ) + with pytest.raises(SystemExit, match="aaaaaaaaa"): + module.plan("a" * 40, "t") + + +def test_the_plan_refuses_a_commit_whose_minimum_it_cannot_read(monkeypatch): + module, _ = _load_app(monkeypatch) + monkeypatch.setattr(module.subprocess, "run", _git_answering(module, "0.17")) + with pytest.raises(SystemExit, match="aaaaaaaaa"): + module.plan("a" * 40, "t") + + +@pytest.mark.parametrize("commit_minimum", ["launching", "0.13.0", None]) +def test_the_plan_accepts_a_commit_the_image_emitter_satisfies( + monkeypatch, commit_minimum +): + """The same minimum, an older one, or none: commits before microcosm#1522 + kept an older minimum in code.""" + + module, _ = _load_app(monkeypatch) + if commit_minimum == "launching": + commit_minimum = _launching_minimum() + monkeypatch.setattr( + module.subprocess, "run", _git_answering(module, commit_minimum) + ) + module.plan("a" * 40, "t") + + def test_the_registry_loads_from_a_bare_copy(monkeypatch, tmp_path): """In the container only the copied file exists, with no microcosm.""" @@ -109,9 +360,7 @@ def test_missing_credentials_are_asked_for_one_command(monkeypatch): monkeypatch.delenv(UK_GATE_SIGNING_KEY_ENV, raising=False) module, _ = _load_app(monkeypatch) monkeypatch.setattr( - module.subprocess, - "run", - lambda argv, **kw: module.subprocess.CompletedProcess(argv, 0), + module.subprocess, "run", _git_answering(module, _launching_minimum()) ) with pytest.raises(SystemExit, match="to this command") as refusal: module.main("a" * 40, "t", run=True) diff --git a/tools/modal_uk_cut.py b/tools/modal_uk_cut.py index 5018101c10..3e71707725 100644 --- a/tools/modal_uk_cut.py +++ b/tools/modal_uk_cut.py @@ -6,6 +6,18 @@ directory on the ``microcosm-uk-cuts`` Modal volume, so fetched inputs and every step's outputs survive the container and a rerun resumes. +The build hands its uploads to the separately installed ``microcosm-emitter`` +(microcosm#1410, #1460), which the runner's preflight starts to check write +access, and the workspace lock pins only its interface. So the image installs +the emitter on its own, at or above the release +``minimum_emitter_version.json`` names in the checkout that launches the app, +as the US Modal image does. The build enforces the minimum of the commit it +clones, so the plan refuses a commit whose minimum is higher than the +launching checkout's; launch from a checkout at or after the commit. As in the +US image, the image first drops the compromised eMudhra certificate +authorities (an upgraded CA store, a hash-pinned pip, uv 0.13.4 and a certifi +floor) before it downloads anything else. + Processing UK Data Service microdata on Modal needs the data owners' OK before first use (``docs/uk-cut-anyone.md``). The volume keeps UKDS inputs and outputs, and anyone in the Modal workspace can read it. @@ -35,8 +47,10 @@ import argparse import importlib.util +import json import os import re +import shlex import subprocess import sys from pathlib import Path @@ -50,7 +64,23 @@ REPO_URL = "https://github.com/PolicyEngine/microcosm.git" CHECKOUT = "/microcosm" PYTHON_VERSION = "3.13" # the version PR CI tests the lock with -UV_VERSION = "0.11.7" +# The compromised eMudhra (emSign) roots, whose intermediate keys were +# disclosed on 2026-10-20, are dropped as in the US Modal image +# (tools/modal_us_stage_plan.py, whose values the tests compare with these). +# uv verifies HTTPS against a CA list compiled into it, and 0.13.4 is the +# first release whose list drops them. +UV_VERSION = "0.13.4" +# Modal's cached debian_slim base carries pip 25.3, whose bundled certifi +# still contains emSign ECC Root CA - G3, so the image replaces it with this +# pip before downloading anything else. The wheel's sha256, as PyPI publishes +# it, not the connection, makes that one download authentic. +PIP_VERSION = "26.2.2" +PIP_WHEEL_SHA256 = "fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70" +PIP_BOOTSTRAP_REQUIREMENTS = "/tmp/pip-bootstrap.txt" +# The first certifi release without emSign ECC Root CA - G3, for the image's +# own Python, which Modal's client in the container runs on. Stated, since +# Modal reuses a cached layer while its definition is unchanged. +CERTIFI_MINIMUM_VERSION = "2026.10.19" SHA = re.compile(r"^[0-9a-f]{40}$") #: The launcher's opt-in for attaching credentials to a ``modal run``. RUN_OPT_IN = "MICROCOSM_UK_CUT_MODAL_RUN" @@ -60,6 +90,23 @@ "packages/microcosm-data/src/microcosm/data/gate_signing_keys.py" ) REGISTRY_REMOTE = "/root/gate_signing_keys.py" +#: The oldest emitter release a build starts, written once in microcosm-build's +#: package data (``MINIMUM_EMITTER_VERSION`` in +#: ``microcosm.build.telemetry_emitter``); read by its path, since the launcher +#: cannot import microcosm. ``plan`` also reads the cloned commit's copy. +MINIMUM_EMITTER_VERSION_PATH = ( + "packages/microcosm-build/src/microcosm/build/minimum_emitter_version.json" +) +MINIMUM_EMITTER_VERSION_FILE = ( + Path(__file__).resolve().parents[1] / MINIMUM_EMITTER_VERSION_PATH +) +EMITTER_RELEASE = re.compile(r"\d+\.\d+\.\d+") +#: Where the image installs the emitter command, outside the environment the +#: container syncs, and the variable through which the build's interface +#: finds it (the interface also searches PATH). +EMITTER_BIN_DIR = "/usr/local/bin" +EMITTER_COMMAND = f"{EMITTER_BIN_DIR}/microcosm-emitter" +EMITTER_COMMAND_ENV = "MICROCOSM_EMITTER_COMMAND" def load_gate_signing_keys(path: Path | None = None) -> ModuleType: @@ -87,6 +134,108 @@ def load_gate_signing_keys(path: Path | None = None) -> ModuleType: registry = load_gate_signing_keys() +def pip_bootstrap_command() -> str: + """The shell step that replaces the base's pip before any package download. + + ``--require-hashes`` refuses any file whose sha256 is not + ``PIP_WHEEL_SHA256``, whatever index or certificate answers the request. + """ + + requirement = f"pip=={PIP_VERSION} --hash=sha256:{PIP_WHEEL_SHA256}" + path = shlex.quote(PIP_BOOTSTRAP_REQUIREMENTS) + return ( + f"printf '%s\\n' {shlex.quote(requirement)} > {path}" + f" && python -m pip install --require-hashes --no-deps -r {path}" + f" && rm {path}" + ) + + +def _minimum_release(text: str, source: str) -> str: + """The release a ``minimum_emitter_version.json`` text names; ``source`` names it.""" + + try: + data = json.loads(text) + except ValueError as error: + raise SystemExit( + f"cannot read the emitter's minimum release from {source} " + f"({type(error).__name__})." + ) from None + version = data.get("minimum_emitter_version") if isinstance(data, dict) else None + if not isinstance(version, str) or EMITTER_RELEASE.fullmatch(version) is None: + raise SystemExit(f'{source} must hold {{"minimum_emitter_version": "X.Y.Z"}}.') + return version + + +def minimum_emitter_version() -> str: + """The oldest emitter release a build starts, as the launching checkout says. + + Refuses a ``MINIMUM_EMITTER_VERSION_FILE`` that is missing or does not + hold ``{"minimum_emitter_version": "X.Y.Z"}``. + """ + + path = MINIMUM_EMITTER_VERSION_FILE + try: + text = path.read_text(encoding="utf-8") + except (OSError, ValueError) as error: + raise SystemExit( + f"cannot read the emitter's minimum release from {path} " + f"({type(error).__name__})." + ) from None + return _minimum_release(text, str(path)) + + +def emitter_requirement() -> str: + """What the image installs: at least the oldest emitter release a build starts.""" + + return f"microcosm-emitter>={minimum_emitter_version()}" + + +def commit_minimum_emitter_version(commit: str) -> str | None: + """The oldest emitter release the build at ``commit`` starts. + + ``None`` when the commit has no ``minimum_emitter_version.json``: commits + before microcosm#1522 kept an older minimum in code. Refuses a commit + whose tree or file git cannot read here: ``git show`` exits 128 alike + for a missing path and an unreadable commit, so ``git ls-tree``, which + lists nothing for a missing path, tells them apart first. + """ + + checkout = Path(__file__).resolve().parents[1] + listed = subprocess.run( + ["git", "ls-tree", "--name-only", commit, "--", MINIMUM_EMITTER_VERSION_PATH], + cwd=checkout, + capture_output=True, + text=True, + check=False, + ) + if listed.returncode != 0: + raise SystemExit( + f"cannot read {commit[:9]}'s tree here (git ls-tree exited " + f"{listed.returncode}); fetch it, then plan again." + ) + if not listed.stdout.strip(): + return None + shown = subprocess.run( + ["git", "show", f"{commit}:{MINIMUM_EMITTER_VERSION_PATH}"], + cwd=checkout, + capture_output=True, + text=True, + check=False, + ) + if shown.returncode != 0: + raise SystemExit( + f"cannot read {MINIMUM_EMITTER_VERSION_PATH} at {commit[:9]} here " + f"(git show exited {shown.returncode}); fetch it, then plan again." + ) + return _minimum_release( + shown.stdout, f"{MINIMUM_EMITTER_VERSION_PATH} at {commit[:9]}" + ) + + +def _release_order(version: str) -> tuple[int, ...]: + return tuple(int(part) for part in version.split(".")) + + def _secrets() -> list[modal.Secret]: # The launcher attaches the credentials only to a deliberate run: modal # run sends the app's secrets before the entrypoint can refuse. In the @@ -105,11 +254,32 @@ def _secrets() -> list[modal.Secret]: def _image() -> modal.Image: image = ( modal.Image.debian_slim(python_version=PYTHON_VERSION) - .apt_install("git", "build-essential", "libhdf5-dev") - .pip_install(f"uv=={UV_VERSION}") - .env({"UV_LINK_MODE": "copy", "PYTHONDONTWRITEBYTECODE": "1"}) + # Naming ca-certificates upgrades the base's CA store, which git and + # the standard library's ssl module read, to the distribution's + # current release, without the eMudhra roots. + .apt_install("git", "build-essential", "libhdf5-dev", "ca-certificates") + # Before the base's pip downloads anything else. + .run_commands(pip_bootstrap_command()) + .pip_install(f"uv=={UV_VERSION}", f"certifi>={CERTIFI_MINIMUM_VERSION}") + .env( + { + "UV_LINK_MODE": "copy", + "PYTHONDONTWRITEBYTECODE": "1", + # The image's Python meets the lock and the emitter. + "UV_PYTHON_DOWNLOADS": "never", + EMITTER_COMMAND_ENV: EMITTER_COMMAND, + } + ) ) if modal.is_local(): + # The newest release at or above the minimum when Modal first builds + # this step; Modal reuses the layer while the minimum is unchanged. + # Running its version fails the image build if the command cannot run. + image = image.run_commands( + f"UV_TOOL_BIN_DIR={EMITTER_BIN_DIR} uv tool install " + f"{shlex.quote(emitter_requirement())}", + f"{EMITTER_COMMAND} version", + ) # Last, because Modal refuses build steps after a local file. image = image.add_local_file(str(REGISTRY_SOURCE), REGISTRY_REMOTE) return image @@ -189,6 +359,20 @@ def plan(commit: str, label: str, *, publish: bool = False) -> list[str]: f"{commit} is not on origin/main here (git fetch first); Modal cuts " "build only from main." ) + # The image installs this checkout's minimum and the build enforces the + # commit's, so a higher one at the commit would stop preflight in the + # paid container, where the emitter's upgrade advice cannot be followed. + image_minimum = minimum_emitter_version() + commit_minimum = commit_minimum_emitter_version(commit) + if commit_minimum is not None and ( + _release_order(commit_minimum) > _release_order(image_minimum) + ): + raise SystemExit( + f"{commit[:9]} needs microcosm-emitter>={commit_minimum}, but this " + f"checkout's image installs microcosm-emitter>={image_minimum}, which " + "the build's preflight would refuse; launch from a checkout at or " + f"after {commit[:9]}." + ) missing = [ name for name in ("HF_TOKEN", registry.UK_GATE_SIGNING_KEY_ENV) @@ -196,7 +380,8 @@ def plan(commit: str, label: str, *, publish: bool = False) -> list[str]: ] print( f"cut {label} at {commit[:9]} on Modal; publish={publish}; " - f"work dir {VOLUME_NAME}:{WORK}; missing credentials: {missing or 'none'}" + f"work dir {VOLUME_NAME}:{WORK}; emitter microcosm-emitter>={image_minimum}; " + f"missing credentials: {missing or 'none'}" ) return missing