From a2bff1f841bc0875512d4aed5e5e1af3bd61953b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 16:53:09 -0500 Subject: [PATCH 1/5] Route A driver: name main's pins, pin the sync interpreter, check the emitter check_commit's feed and crosswalk blockers now name the commit's own pinned feed digest and crosswalk digest, so a build from a newer main commit can copy them into its settings. The published run's defaults are unchanged. ensure_worktree passes `uv sync --python "$UV_SYNC_PYTHON"` (default 3.14): uv otherwise takes the newest installed CPython, and the lock's torch wheels stop at cp314. check_emitter reports the microcosm-emitter the release would start against the commit's minimum_emitter_version.json. With MICROCOSM_TELEMETRY_REQUIRED=1 a missing or older emitter is a blocker; otherwise a note. A value the release refuses (not 1, 0 or unset) is a blocker. The driver exports both settings when the settings file sets them, so the stages see what --resolve checked. The README gains "A build from main"; the build rule records that the four September causes are answered on the --base-h5 arm. Co-Authored-By: Claude Opus 5.5 --- .../route-a-driver-main-pins.changed.md | 1 + docs/us-release-build-rule.md | 23 +- .../engine_free/us/test_route_a_driver.py | 282 ++++++++++++++++++ tools/route_a/README.md | 25 ++ tools/route_a/route_a.env.example | 11 +- tools/route_a/route_a.sh | 71 ++++- 6 files changed, 405 insertions(+), 8 deletions(-) create mode 100644 changelog.d/route-a-driver-main-pins.changed.md diff --git a/changelog.d/route-a-driver-main-pins.changed.md b/changelog.d/route-a-driver-main-pins.changed.md new file mode 100644 index 0000000000..ba7214b6fc --- /dev/null +++ b/changelog.d/route-a-driver-main-pins.changed.md @@ -0,0 +1 @@ +The Route A driver (`tools/route_a/route_a.sh`) now says what a build from a newer main commit needs. Its feed and crosswalk blockers name the commit's own pinned feed digest and crosswalk digest, so a rerun's settings can copy them; the published run's defaults are unchanged. A fresh worktree syncs with `uv sync --python "$UV_SYNC_PYTHON"` (default `3.14`), because uv otherwise takes the newest installed CPython and the lock's torch wheels stop at 3.14. `--resolve` reports the `microcosm-emitter` the release would start against the commit's `minimum_emitter_version.json`: with `MICROCOSM_TELEMETRY_REQUIRED=1` a missing or older emitter is a blocker, otherwise a note. The driver exports `MICROCOSM_TELEMETRY_REQUIRED` and `MICROCOSM_EMITTER_COMMAND` when the settings file sets them, so the stages see what `--resolve` checked. `tools/route_a/README.md` gains a section on building from main, and `docs/us-release-build-rule.md` records that the four September causes are answered on the `--base-h5` arm. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 25c405f7ed..d5753db860 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -5,8 +5,11 @@ Main must demonstrably build the certified US default from raw sources and pass its preflight and certification gates (decided 15 September 2026). -The last from-scratch build is Build P (28 July 2026, policyengine-us 1.764.6). -Every later default is a supplied-parent enrichment of that file. A pull request +The last from-scratch build made the default is Build P (28 July 2026, +policyengine-us 1.764.6). Every later default is a supplied-parent enrichment of +that file. Route A's 30 September and 24 October builds came from raw sources +on main (a fresh base, then a `--base-h5` release) and were published by tag +only, not made the default. A pull request large enough to change how the dataset is built carries a from-scratch build and certification receipt from its own tree before it merges. Main carries the same build as a standing check afterwards. @@ -38,6 +41,22 @@ and reached no release. The causes below were re-read on main at `d1196af10`. The engine lock that also blocked it is fixed: main resolves policyengine-us 2.2.1, policyengine-core 3.32.5 and spm-calculator 1.0.0. +**16 November 2026:** all four causes are answered on the `--base-h5` arm, +which route A (`tools/route_a/route_a.sh`) drives: + +1. The labelled feed pin landed in #955 (section 1). +2. The SPM independence role stage is `us_runtime/spm_independence_role.py`, + and the driver blocks a commit without it (section 2). +3. The preflight has a `--new-lineage` mode (section 3). +4. The three ASEC files are mirrored to `policyengine/microcosm-us-sources` + and pinned by upload revision in `us_runtime/asec_sources.py`. The base + refuses a command-line ASEC digest that differs from its year's pin + (section 4). + +The `--exact-k` arm still waits on chronicle#277. A build from a newer main +commit needs settings beyond the commit; "A build from main" in +`tools/route_a/README.md` lists them. + ### 1. No Chronicle feed on the build machine carries dimension labels `_validate_chronicle_hierarchy_labels` diff --git a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py index 79555604b1..8fa937c9d7 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py +++ b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py @@ -209,6 +209,288 @@ def test_overridden_feed_pin_still_verifies_digest_and_size( ) +def _tiny_main(tmp_path: Path, files: dict[str, str]) -> tuple[Path, str]: + """A throwaway local repository standing in for ``$MAIN`` at one commit.""" + + main = tmp_path / "main-repo" + for relative, text in files.items(): + path = main / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + git = [ + "git", + "-C", + str(main), + "-c", + "user.name=fixture", + "-c", + "user.email=fixture@example.invalid", + "-c", + "commit.gpgsign=false", + "-c", + "core.hooksPath=/dev/null", + ] + for args in ( + ["init", "-q"], + ["add", "-A"], + ["commit", "-q", "-m", "fixture"], + # check_commit looks for the commit on origin's branches. + ["update-ref", "refs/remotes/origin/main", "HEAD"], + ): + subprocess.run([*git, *args], check=True, capture_output=True, timeout=20) + sha = subprocess.run( + [*git, "rev-parse", "HEAD"], + check=True, + capture_output=True, + text=True, + timeout=20, + ).stdout.strip() + return main, sha + + +_FEED_PIN_REL = "packages/microcosm-build/src/microcosm/build/us/chronicle_feed.json" +_CROSSWALK_REL = ( + "packages/microcosm-build/src/microcosm/build/us_runtime/data/" + "congressional_district_vintage_crosswalk.csv" +) +_EMITTER_FLOOR_REL = ( + "packages/microcosm-build/src/microcosm/build/minimum_emitter_version.json" +) + + +def _report_lines(commands: str) -> str: + return ( + commands + + """ +for x in ${COMMIT_NOTES[@]+"${COMMIT_NOTES[@]}"}; do printf 'NOTE %s\\n' "$x"; done +for x in ${COMMIT_BLOCKERS[@]+"${COMMIT_BLOCKERS[@]}"}; do printf 'BLOCKER %s\\n' "$x"; done +""" + ) + + +def test_stale_feed_and_crosswalk_blockers_name_the_commits_pins( + tmp_path: Path, +) -> None: + """The driver keeps the published run's pins by default; a commit that + moved them gets blockers naming the commit's own values, so a rerun's + settings can copy them.""" + + crosswalk = "state,district\nCT,1\n" + main, sha = _tiny_main( + tmp_path, + { + _FEED_PIN_REL: json.dumps({"facts_sha256": "c" * 64}, indent=2) + "\n", + _CROSSWALK_REL: crosswalk, + }, + ) + result = _input_settings_result( + tmp_path, + {"MAIN": str(main), "FEED_SHA": "a" * 64, "CROSSWALK_SHA": "b" * 64}, + _report_lines(f"\ncheck_commit {sha} {sha}\n"), + ) + assert result.returncode == 0, result.stderr.decode() + lines = result.stdout.decode().splitlines() + digest = hashlib.sha256(crosswalk.encode()).hexdigest() + assert any( + line.startswith("BLOCKER ") + and f"does not pin facts_sha256 {'a' * 64}" in line + and f"it pins {'c' * 64}" in line + for line in lines + ), lines + assert any( + line.startswith("BLOCKER ") + and f"crosswalk at {sha} is {digest}, not {'b' * 64}" in line + for line in lines + ), lines + + +def test_matching_feed_and_crosswalk_pins_are_notes_not_blockers( + tmp_path: Path, +) -> None: + crosswalk = "state,district\nCT,1\n" + digest = hashlib.sha256(crosswalk.encode()).hexdigest() + main, sha = _tiny_main( + tmp_path, + { + _FEED_PIN_REL: json.dumps({"facts_sha256": "c" * 64}, indent=2) + "\n", + _CROSSWALK_REL: crosswalk, + }, + ) + result = _input_settings_result( + tmp_path, + {"MAIN": str(main), "FEED_SHA": "c" * 64, "CROSSWALK_SHA": digest}, + _report_lines(f"\ncheck_commit {sha} {sha}\n"), + ) + assert result.returncode == 0, result.stderr.decode() + lines = result.stdout.decode().splitlines() + assert f"NOTE us/chronicle_feed.json at {sha} pins facts_sha256 {'c' * 64}" in lines + assert f"NOTE packaged CD vintage crosswalk at {sha} = {digest}" in lines + blockers = [line for line in lines if line.startswith("BLOCKER ")] + assert not [line for line in blockers if "chronicle_feed.json" in line], blockers + assert not [line for line in blockers if "CD vintage crosswalk" in line], blockers + + +def _emitter_stub(tmp_path: Path, answer: str) -> Path: + return write_executable( + tmp_path / "emitter-stub", + "#!/bin/bash\n" + '[ "$#" = 1 ] && [ "$1" = version ] || exit 7\n' + f"printf '%s\\n' {shlex.quote(answer)}\n", + ) + + +@pytest.mark.parametrize("required", [False, True]) +@pytest.mark.parametrize( + ("answer", "expected"), + [ + ('{"emitter_version": "0.16.0", "protocol_versions": [1]}', "ok"), + ('{"emitter_version": "0.17.2"}', "ok"), + ('{"emitter_version": "0.13.0"}', "older than the commit's floor 0.16.0"), + ('{"emitter_version": "0.9.10"}', "older than the commit's floor 0.16.0"), + ("not json", "reported no release version"), + ('{"emitter_version": "dev"}', "reported no release version"), + (None, "no microcosm-emitter found"), + ], +) +def test_emitter_is_held_to_the_commits_floor( + tmp_path: Path, answer: str | None, expected: str, required: bool +) -> None: + main, sha = _tiny_main( + tmp_path, + {_EMITTER_FLOOR_REL: '{\n "minimum_emitter_version": "0.16.0"\n}\n'}, + ) + overrides = {"MAIN": str(main)} + if answer is None: + # No command configured and none on this PATH (system tools only). + overrides.update(MICROCOSM_EMITTER_COMMAND="", PATH="/usr/bin:/bin") + else: + overrides["MICROCOSM_EMITTER_COMMAND"] = str(_emitter_stub(tmp_path, answer)) + if required: + overrides["MICROCOSM_TELEMETRY_REQUIRED"] = "1" + result = _input_settings_result( + tmp_path, + overrides, + _report_lines(f"\nCOMMIT_NOTES=(); COMMIT_BLOCKERS=()\ncheck_emitter {sha}\n"), + ) + assert result.returncode == 0, result.stderr.decode() + lines = result.stdout.decode().splitlines() + assert len(lines) == 1, lines + if expected == "ok": + assert lines[0].startswith("NOTE microcosm-emitter "), lines + assert "meets the commit's floor 0.16.0" in lines[0] + return + assert expected in lines[0], lines + if required: + assert lines[0].startswith("BLOCKER "), lines + assert "would stop before any work" in lines[0] + else: + assert lines[0].startswith("NOTE "), lines + assert "without collector telemetry" in lines[0] + + +def test_emitter_settings_reach_the_stages_and_bad_values_block( + tmp_path: Path, +) -> None: + """The release reads both settings from its environment, so a value set + in the settings file is exported, and a value the release would refuse is + a blocker however the emitter looks.""" + + main, sha = _tiny_main( + tmp_path, + {_EMITTER_FLOOR_REL: '{"minimum_emitter_version": "0.16.0"}\n'}, + ) + emitter = str(_emitter_stub(tmp_path, '{"emitter_version": "0.16.0"}')) + exported = _input_settings_result( + tmp_path, + { + "MAIN": str(main), + "MICROCOSM_TELEMETRY_REQUIRED": "1", + "MICROCOSM_EMITTER_COMMAND": f" {emitter} ", + }, + "\nprintenv MICROCOSM_TELEMETRY_REQUIRED\nprintenv MICROCOSM_EMITTER_COMMAND\n" + + _report_lines(f"COMMIT_NOTES=(); COMMIT_BLOCKERS=()\ncheck_emitter {sha}\n"), + ) + assert exported.returncode == 0, exported.stderr.decode() + assert exported.stdout.decode().splitlines() == [ + "1", + f" {emitter} ", + f"NOTE microcosm-emitter 0.16.0 at {emitter} meets the commit's floor 0.16.0", + ] + refused = _input_settings_result( + tmp_path, + { + "MAIN": str(main), + "MICROCOSM_TELEMETRY_REQUIRED": "yes", + "MICROCOSM_EMITTER_COMMAND": emitter, + }, + _report_lines(f"\nCOMMIT_NOTES=(); COMMIT_BLOCKERS=()\ncheck_emitter {sha}\n"), + ) + assert refused.returncode == 0, refused.stderr.decode() + assert refused.stdout.decode().splitlines() == [ + "BLOCKER MICROCOSM_TELEMETRY_REQUIRED is 'yes'; the release accepts only " + "1, 0 or unset and refuses anything else" + ] + + +def test_emitter_check_skips_a_commit_without_a_floor(tmp_path: Path) -> None: + main, sha = _tiny_main(tmp_path, {"README.md": "fixture\n"}) + result = _input_settings_result( + tmp_path, + {"MAIN": str(main), "MICROCOSM_EMITTER_COMMAND": str(tmp_path / "never-run")}, + _report_lines(f"\nCOMMIT_NOTES=(); COMMIT_BLOCKERS=()\ncheck_emitter {sha}\n"), + ) + assert result.returncode == 0, result.stderr.decode() + assert result.stdout.decode().splitlines() == [ + f"NOTE no readable {_EMITTER_FLOOR_REL} at {sha}; emitter not checked" + ] + + +@pytest.mark.parametrize("setting", [None, "3.13"]) +def test_worktree_sync_names_its_interpreter( + tmp_path: Path, setting: str | None +) -> None: + """A fresh worktree's uv sync names an interpreter the lock has wheels + for; without one uv takes the newest installed CPython.""" + + recorded = tmp_path / "uv-args" + uv = write_executable( + tmp_path / "uv-stub", + "#!/bin/bash\n" + f'printf "%s\\n" "$@" > {shlex.quote(str(recorded))}\n' + "mkdir -p .venv/bin\n" + "printf '#!/bin/bash\\nexit 0\\n' > .venv/bin/python\n" + "chmod +x .venv/bin/python\n", + ) + commands = ( + "\ngit() {\n" + ' case "$3" in\n' + ' worktree) mkdir -p "$6" ;;\n' + " status) : ;;\n" + ' rev-parse) printf "%s\\n" "$FIXTURE_SHA" ;;\n' + " esac\n" + "}\n" + f"FIXTURE_SHA={'d' * 40}\n" + + _function("ensure_worktree") + + '\nensure_worktree "$FIXTURE_SHA"\n' + ) + run_root = tmp_path / "run-root" + run_root.mkdir() + overrides = {"UV": str(uv), "RUN_ROOT": str(run_root)} + if setting is not None: + overrides["UV_SYNC_PYTHON"] = setting + result = _input_settings_result(tmp_path, overrides, commands) + assert result.returncode == 0, result.stderr.decode() + assert recorded.read_text(encoding="utf-8").splitlines() == [ + "sync", + "--python", + setting or "3.14", + "--all-packages", + "--locked", + "--extra", + "us", + ] + + def test_shell_scripts_are_valid_bash() -> None: scripts = _shell_sources() assert scripts diff --git a/tools/route_a/README.md b/tools/route_a/README.md index b3e00828f3..0b828b3f6e 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -59,6 +59,31 @@ nonzero for failed fetches or input problems; commit blockers are reported in `resolve.log` and do not alone change that mode's exit status. A real run refuses both input problems and commit blockers. +### A build from main + +The feed and crosswalk defaults are the published run's, so a build from a +newer main commit usually needs settings beyond `COMMIT`. Run `--resolve` +first and set what its blockers name: + +- **Feed.** When `us/chronicle_feed.json` at the commit pins another + `facts_sha256`, the blocker names it. Set `FEED` to that feed's file, + `FEED_SHA` to the digest and `FEED_BYTES` to the file's size. +- **Crosswalk.** When the packaged congressional-district vintage crosswalk + changed, the blocker gives the commit's digest. Set `CROSSWALK_SHA` to it + once the change is reviewed. +- **Interpreter.** A fresh worktree syncs with + `uv sync --python "$UV_SYNC_PYTHON"` (default `3.14`). Without it uv takes + the newest installed CPython, and the lock's torch wheels stop at 3.14. +- **Emitter.** `--resolve` reports the `microcosm-emitter` the release would + start (`MICROCOSM_EMITTER_COMMAND`, then `PATH`) against the commit's + `minimum_emitter_version.json`. With `MICROCOSM_TELEMETRY_REQUIRED=1` a + missing or older emitter is a blocker, because the release would stop + before any work. Otherwise it is a note: the release would run without + collector telemetry or staging hand-overs. A value other than `1`, `0` or + unset is a blocker, because the release refuses it. The driver exports both + settings when the settings file sets them. Publisher preflight starts no + emitter. + The example retains the historical d122 dense whole-base national/state settings, batch size 2000, export-mass reference and d490 tail register from the published run. Those are operator settings, not a new waiver. The driver permits diff --git a/tools/route_a/route_a.env.example b/tools/route_a/route_a.env.example index 89788a6078..d83973a0bd 100644 --- a/tools/route_a/route_a.env.example +++ b/tools/route_a/route_a.env.example @@ -18,7 +18,8 @@ : "${FEED:=$PE/_buildh-runtime/inputs/consumer_facts_us_c5e5bf8.jsonl}" # The driver preserves the published feed/crosswalk pins by default. If the # chosen commit changed them, set FEED_SHA, FEED_BYTES and CROSSWALK_SHA here -# alongside FEED, after checking that commit's packaged pins. +# alongside FEED, after checking that commit's packaged pins; --resolve names +# the commit's own feed digest and crosswalk digest in its blockers. # d713: CT-fixed ladder; route_a.sh verifies its digest and size. : "${LADDER:=$PE/_build_artifacts/us-ct-cbsa/us_block_ladder_2020.npz}" : "${SSI:=$PE/_buildo-runtime/inputs/attempt6_basis_schema3_seed.json}" @@ -34,6 +35,14 @@ : "${PRUNE_BASE_CHECKPOINTS:=1}" : "${RELEASE_DESPITE_PREFLIGHT_FAIL:=0}" : "${RESOURCE_WAIT_HOURS:=12}" +# uv sync in a fresh worktree; the lock's torch wheels stop at CPython 3.14. +: "${UV_SYNC_PYTHON:=3.14}" +# The release starts microcosm-emitter (MICROCOSM_EMITTER_COMMAND, then PATH) +# and refuses one older than the commit's minimum_emitter_version.json. +# PolicyEngine builds set MICROCOSM_TELEMETRY_REQUIRED=1, and --resolve then +# blocks on a missing or old emitter; unset or 0 runs without telemetry. The +# driver exports either setting made here. +# : "${MICROCOSM_TELEMETRY_REQUIRED:=1}" : "${RELEASE_RAM_GIB:=50}" : "${RELEASE_WALL_SECONDS:=345600}" # 0 is the sole opt-out and restores --no-staging without a credential lookup. diff --git a/tools/route_a/route_a.sh b/tools/route_a/route_a.sh index 351c24de20..77ddb2ecd3 100755 --- a/tools/route_a/route_a.sh +++ b/tools/route_a/route_a.sh @@ -45,6 +45,13 @@ LOG=$RUN_ROOT/route_a.log : "${PREFLIGHT_NEW_LINEAGE_ARGS:=}" "${EARLY_START_AFTER_HEAVY:=0}" "${PRUNE_BASE_CHECKPOINTS:=0}" : "${RELEASE_DESPITE_PREFLIGHT_FAIL:=0}" "${RELEASE_EXTRA_ARGS:=}" "${EXPORT_MASS_REF_H5:=}" : "${RESOURCE_WAIT_HOURS:=12}" +# uv sync takes the newest installed CPython unless told otherwise, and the +# lock's torch wheels stop at cp314; a fresh worktree on 3.15 fails to sync. +: "${UV_SYNC_PYTHON:=3.14}" +# The release reads these two from its environment. Export a settings-file +# value so the stages see what --resolve checked. +[ -z "${MICROCOSM_TELEMETRY_REQUIRED+set}" ] || export MICROCOSM_TELEMETRY_REQUIRED +[ -z "${MICROCOSM_EMITTER_COMMAND+set}" ] || export MICROCOSM_EMITTER_COMMAND # --------------------------------------------------------------------------- # Inputs, resolved and hashed on this machine on 2026-09-23 (see status.md). @@ -79,6 +86,7 @@ CROSSWALK_REL=packages/microcosm-build/src/microcosm/build/us_runtime/data/congr FEED_PIN_REL=packages/microcosm-build/src/microcosm/build/us/chronicle_feed.json ASEC_PIN_REL=packages/microcosm-build/src/microcosm/build/us_runtime/asec_sources.py SPM_ROLE_REL=packages/microcosm-build/src/microcosm/build/us_runtime/spm_independence_role.py +EMITTER_FLOOR_REL=packages/microcosm-build/src/microcosm/build/minimum_emitter_version.json BASE_FLAGS="--stage --checkpoint-dir --asec-h5 --asec-h5-sha256 --puf-h5 --puf-source-year-csv --acs-h5 --asec-education-source --target-year --seed --n-estimators --ledger-facts --assign-congressional-districts --congressional-district-vintage-crosswalk --congressional-district-seed --block-ladder-artifact --out" RELEASE_FLAGS="--base-h5 --ledger-facts --ledger-facts-sha256 --qrf-tail-concentration-exclusions --ssi-take-up-prior-weight-basis --ssi-take-up-prior-weight-basis-sha256 --scf-summary-extract --out --release-id --checkpoint-root --seed" [ "$ROUTE_A_STAGING" = 0 ] && RELEASE_FLAGS="$RELEASE_FLAGS --no-staging" @@ -168,17 +176,22 @@ check_commit() { # $1 = build ref, $2 = preflight ref; fills COMMIT_BLOCKERS/CO if git -C "$MAIN" show "$full:$FEED_PIN_REL" 2>/dev/null | grep -q "\"facts_sha256\": \"$FEED_SHA\""; then COMMIT_NOTES+=("us/chronicle_feed.json at $full pins facts_sha256 $FEED_SHA") else - COMMIT_BLOCKERS+=("us/chronicle_feed.json at $full does not pin facts_sha256 $FEED_SHA (the release tool would refuse the feed)") + local pinned_feed + pinned_feed=$(git -C "$MAIN" show "$full:$FEED_PIN_REL" 2>/dev/null | \ + "$PYTHON" -c 'import json, sys; print(json.load(sys.stdin).get("facts_sha256") or "")' 2>/dev/null) + COMMIT_BLOCKERS+=("us/chronicle_feed.json at $full does not pin facts_sha256 $FEED_SHA (the release tool would refuse the feed); it pins ${pinned_feed:-no readable facts_sha256}: set FEED to that feed's file, FEED_SHA to its digest and FEED_BYTES to its size") fi local s for s in $ASEC_2024_SHA $ASEC_2023_SHA $ASEC_2022_SHA; do git -C "$MAIN" show "$full:$ASEC_PIN_REL" 2>/dev/null | grep -q "$s" \ || COMMIT_BLOCKERS+=("asec_sources.py at $full lacks canonical ASEC pin $s (the base would refuse the CLI pin)") done - if [ "$(git -C "$MAIN" show "$full:$CROSSWALK_REL" 2>/dev/null | openssl dgst -sha256 -r | cut -c1-64)" = "$CROSSWALK_SHA" ]; then + local crosswalk + crosswalk=$(git -C "$MAIN" show "$full:$CROSSWALK_REL" 2>/dev/null | openssl dgst -sha256 -r | cut -c1-64) + if [ "$crosswalk" = "$CROSSWALK_SHA" ]; then COMMIT_NOTES+=("packaged CD vintage crosswalk at $full = $CROSSWALK_SHA") else - COMMIT_BLOCKERS+=("packaged CD vintage crosswalk at $full is not $CROSSWALK_SHA") + COMMIT_BLOCKERS+=("packaged CD vintage crosswalk at $full is $crosswalk, not $CROSSWALK_SHA: set CROSSWALK_SHA to it once the change is reviewed") fi if git -C "$MAIN" show "$full:tools/build_us_fiscal_refresh_release.py" 2>/dev/null | grep -q '_check_committed_us_ledger_feed_pin'; then COMMIT_NOTES+=("release tool at $full holds the feed to the committed pin") @@ -228,6 +241,54 @@ check_commit() { # $1 = build ref, $2 = preflight ref; fills COMMIT_BLOCKERS/CO git -C "$MAIN" branch -r --contains "$pfull" 2>/dev/null | grep -qv -- '->' \ || COMMIT_BLOCKERS+=("preflight commit $pfull is on no origin branch") fi + check_emitter "$full" +} + +check_emitter() { # $1 = full build sha; adds to COMMIT_NOTES/COMMIT_BLOCKERS + # The release starts microcosm-emitter (MICROCOSM_EMITTER_COMMAND, then PATH) + # for collector telemetry and staging hand-overs, and never starts one older + # than the commit's minimum_emitter_version.json. With + # MICROCOSM_TELEMETRY_REQUIRED=1 such an emitter stops the release before it + # does any work; otherwise the release runs without telemetry. + local full=$1 floor cmd version verdict problem + case "${MICROCOSM_TELEMETRY_REQUIRED-0}" in + 0|1) ;; + *) COMMIT_BLOCKERS+=("MICROCOSM_TELEMETRY_REQUIRED is '${MICROCOSM_TELEMETRY_REQUIRED}'; the release accepts only 1, 0 or unset and refuses anything else") + return ;; + esac + floor=$(git -C "$MAIN" show "$full:$EMITTER_FLOOR_REL" 2>/dev/null | \ + "$PYTHON" -c 'import json, sys; print(json.load(sys.stdin)["minimum_emitter_version"])' 2>/dev/null) + if [ -z "$floor" ]; then + COMMIT_NOTES+=("no readable $EMITTER_FLOOR_REL at $full; emitter not checked") + return + fi + cmd=${MICROCOSM_EMITTER_COMMAND-} + cmd=${cmd#"${cmd%%[![:space:]]*}"}; cmd=${cmd%"${cmd##*[![:space:]]}"} + [ -n "$cmd" ] || cmd=$(command -v microcosm-emitter 2>/dev/null) + if [ -z "$cmd" ]; then + problem="no microcosm-emitter found (MICROCOSM_EMITTER_COMMAND, then PATH); the release needs $floor or later" + else + version=$("$cmd" version /dev/null | \ + "$PYTHON" -c 'import json, sys; print(json.load(sys.stdin).get("emitter_version") or "")' 2>/dev/null) + verdict=$("$PYTHON" -c ' +import re, sys +def release(text): + found = re.match(r"(\d+)\.(\d+)\.(\d+)", text) + return None if found is None else tuple(int(part) for part in found.groups()) +have, need = release(sys.argv[1]), release(sys.argv[2]) +print("unknown" if have is None or need is None else "ok" if have >= need else "old") +' "$version" "$floor" 2>/dev/null) + case "$verdict" in + ok) COMMIT_NOTES+=("microcosm-emitter $version at $cmd meets the commit's floor $floor"); return ;; + old) problem="microcosm-emitter $version at $cmd is older than the commit's floor $floor (uv tool install --upgrade 'microcosm-emitter>=$floor', or point MICROCOSM_EMITTER_COMMAND at a newer one)" ;; + *) problem="microcosm-emitter at $cmd reported no release version (\`$cmd version\`); the release needs $floor or later" ;; + esac + fi + if [ "${MICROCOSM_TELEMETRY_REQUIRED:-0}" = 1 ]; then + COMMIT_BLOCKERS+=("$problem; MICROCOSM_TELEMETRY_REQUIRED=1, so the release would stop before any work") + else + COMMIT_NOTES+=("$problem; MICROCOSM_TELEMETRY_REQUIRED is not 1, so the release would run without collector telemetry or staging hand-overs") + fi } refuse_bad_release_args() { @@ -342,8 +403,8 @@ ensure_worktree() { # $1 = full sha; sets WT fi [ -z "$(git -C "$WT" status --porcelain)" ] || fail "worktree $WT is dirty" if [ ! -f "$WT/.venv/.route_a_synced" ]; then - log "uv sync --all-packages --locked --extra us in $WT" - (cd "$WT" && "$UV" sync --all-packages --locked --extra us) >>"$LOG" 2>&1 || fail "uv sync in $WT" + log "uv sync --python $UV_SYNC_PYTHON --all-packages --locked --extra us in $WT" + (cd "$WT" && "$UV" sync --python "$UV_SYNC_PYTHON" --all-packages --locked --extra us) >>"$LOG" 2>&1 || fail "uv sync in $WT" "$WT/.venv/bin/python" -c 'import psutil, policyengine_us' >>"$LOG" 2>&1 || fail "venv in $WT lacks psutil/policyengine_us" date '+%F %T' > "$WT/.venv/.route_a_synced" fi From 5e79fa54ca705d328a8e206a698c4ee2f07834b9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 17:10:12 -0500 Subject: [PATCH 2/5] Route A driver: check the emitter as the release does; no digest for a missing crosswalk Review r1 of #1650 (Codex Sol 6.1) found the bash emitter check passed emitters the release refuses. tools/route_a/check_emitter.py now repeats telemetry_emitter._start_emitter's checks without importing microcosm: MICROCOSM_EMITTER_COMMAND stripped as str.strip() does, else microcosm-emitter via shutil.which; `version` must exit 0 within 15 s and print a JSON object; the version must be a release at or above a floor that fully matches X.Y.Z; with telemetry required, protocol_versions must be a list of integers holding 1. A relative command path is refused, because the stages run in the build worktree. check_commit reports a missing packaged crosswalk as a blocker instead of offering the empty input's digest as the commit's pin. Co-Authored-By: Claude Opus 5.5 --- .../route-a-driver-main-pins.changed.md | 2 +- .../engine_free/us/test_route_a_driver.py | 319 +++++++++++++----- tools/route_a/README.md | 25 +- tools/route_a/check_emitter.py | 160 +++++++++ tools/route_a/route_a.sh | 59 +--- 5 files changed, 431 insertions(+), 134 deletions(-) create mode 100644 tools/route_a/check_emitter.py diff --git a/changelog.d/route-a-driver-main-pins.changed.md b/changelog.d/route-a-driver-main-pins.changed.md index ba7214b6fc..21db810d4a 100644 --- a/changelog.d/route-a-driver-main-pins.changed.md +++ b/changelog.d/route-a-driver-main-pins.changed.md @@ -1 +1 @@ -The Route A driver (`tools/route_a/route_a.sh`) now says what a build from a newer main commit needs. Its feed and crosswalk blockers name the commit's own pinned feed digest and crosswalk digest, so a rerun's settings can copy them; the published run's defaults are unchanged. A fresh worktree syncs with `uv sync --python "$UV_SYNC_PYTHON"` (default `3.14`), because uv otherwise takes the newest installed CPython and the lock's torch wheels stop at 3.14. `--resolve` reports the `microcosm-emitter` the release would start against the commit's `minimum_emitter_version.json`: with `MICROCOSM_TELEMETRY_REQUIRED=1` a missing or older emitter is a blocker, otherwise a note. The driver exports `MICROCOSM_TELEMETRY_REQUIRED` and `MICROCOSM_EMITTER_COMMAND` when the settings file sets them, so the stages see what `--resolve` checked. `tools/route_a/README.md` gains a section on building from main, and `docs/us-release-build-rule.md` records that the four September causes are answered on the `--base-h5` arm. +The Route A driver (`tools/route_a/route_a.sh`) now says what a build from a newer main commit needs. Its feed and crosswalk blockers name the commit's own pinned feed digest and crosswalk digest, so a rerun's settings can copy them; the published run's defaults are unchanged. A fresh worktree syncs with `uv sync --python "$UV_SYNC_PYTHON"` (default `3.14`), because uv otherwise takes the newest installed CPython and the lock's torch wheels stop at 3.14. `--resolve` checks the `microcosm-emitter` the release would start against the commit's `minimum_emitter_version.json` with `tools/route_a/check_emitter.py`, which repeats the release's own checks (command lookup, a 15 s `version` call, the release floor and, when telemetry is required, protocol version 1). With `MICROCOSM_TELEMETRY_REQUIRED=1` a failed check is a blocker, otherwise a note. A missing packaged crosswalk is now a blocker that names no digest. The driver exports `MICROCOSM_TELEMETRY_REQUIRED` and `MICROCOSM_EMITTER_COMMAND` when the settings file sets them, so the stages see what `--resolve` checked. `tools/route_a/README.md` gains a section on building from main, and `docs/us-release-build-rule.md` records that the four September causes are answered on the `--base-h5` arm. diff --git a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py index 8fa937c9d7..c799834bea 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py +++ b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py @@ -302,6 +302,26 @@ def test_stale_feed_and_crosswalk_blockers_name_the_commits_pins( and f"crosswalk at {sha} is {digest}, not {'b' * 64}" in line for line in lines ), lines + # check_commit ends with the emitter check (no floor file here). + assert f"NOTE no {_EMITTER_FLOOR_REL} at {sha}; emitter not checked" in lines + + +def test_a_missing_crosswalk_blocks_without_naming_a_digest(tmp_path: Path) -> None: + main, sha = _tiny_main( + tmp_path, + {_FEED_PIN_REL: json.dumps({"facts_sha256": "c" * 64}) + "\n"}, + ) + result = _input_settings_result( + tmp_path, + {"MAIN": str(main), "FEED_SHA": "c" * 64}, + _report_lines(f"\ncheck_commit {sha} {sha}\n"), + ) + assert result.returncode == 0, result.stderr.decode() + lines = result.stdout.decode().splitlines() + assert ( + f"BLOCKER no packaged CD vintage crosswalk at {sha} ({_CROSSWALK_REL})" in lines + ) + assert not [line for line in lines if "set CROSSWALK_SHA" in line] def test_matching_feed_and_crosswalk_pins_are_notes_not_blockers( @@ -330,119 +350,250 @@ def test_matching_feed_and_crosswalk_pins_are_notes_not_blockers( assert not [line for line in blockers if "CD vintage crosswalk" in line], blockers -def _emitter_stub(tmp_path: Path, answer: str) -> Path: +def _emitter_stub( + where: Path, answer: str, status: int = 0, name: str = "emitter-stub" +) -> Path: return write_executable( - tmp_path / "emitter-stub", + where / name, "#!/bin/bash\n" - '[ "$#" = 1 ] && [ "$1" = version ] || exit 7\n' - f"printf '%s\\n' {shlex.quote(answer)}\n", + '[ "$#" = 1 ] && [ "$1" = version ] || exit 64\n' + f"printf '%s\\n' {shlex.quote(answer)}\n" + f"exit {status}\n", + ) + + +_FLOOR = '{"minimum_emitter_version": "0.16.0"}\n' +_GOOD_EMITTER = '{"emitter_version": "0.16.0", "protocol_versions": [1]}' + + +def _emitter_line(floor: str, env: dict[str, str], cwd: Path | None = None) -> str: + """The one line ``tools/route_a/check_emitter.py`` prints.""" + + result = subprocess.run( + [sys.executable, "-I", str(ROUTE_A_TOOLS / "check_emitter.py")], + input=floor, + env={"PATH": "/usr/bin:/bin", **env}, + cwd=cwd, + capture_output=True, + text=True, + timeout=60, + check=False, ) + assert result.returncode == 0, result.stderr + lines = result.stdout.splitlines() + assert len(lines) == 1, lines + return lines[0] + + +def _assert_problem(line: str, problem: str, required: bool) -> None: + assert problem in line, line + if required: + assert line.startswith("BLOCKER "), line + assert "would stop before any work" in line + else: + assert line.startswith("NOTE "), line + assert "without collector telemetry" in line @pytest.mark.parametrize("required", [False, True]) @pytest.mark.parametrize( - ("answer", "expected"), + ("answer", "status", "problem"), [ - ('{"emitter_version": "0.16.0", "protocol_versions": [1]}', "ok"), - ('{"emitter_version": "0.17.2"}', "ok"), - ('{"emitter_version": "0.13.0"}', "older than the commit's floor 0.16.0"), - ('{"emitter_version": "0.9.10"}', "older than the commit's floor 0.16.0"), - ("not json", "reported no release version"), - ('{"emitter_version": "dev"}', "reported no release version"), - (None, "no microcosm-emitter found"), + (_GOOD_EMITTER, 0, None), + ('{"emitter_version": "0.17.2rc1", "protocol_versions": [1, 2]}', 0, None), + ( + '{"emitter_version": "0.13.0", "protocol_versions": [1]}', + 0, + "older than the commit's floor 0.16.0", + ), + ( + '{"emitter_version": "0.9.10", "protocol_versions": [1]}', + 0, + "older than the commit's floor 0.16.0", + ), + ("not json", 0, "printed no JSON object"), + ('["0.16.0"]', 0, "printed no JSON object"), + ('{"emitter_version": "dev"}', 0, "reported no release version"), + ( + '{"emitter_version": "v0.16.0", "protocol_versions": [1]}', + 0, + "reported no release version", + ), + (_GOOD_EMITTER, 7, "exited 7"), ], ) -def test_emitter_is_held_to_the_commits_floor( - tmp_path: Path, answer: str | None, expected: str, required: bool +def test_emitter_check_follows_the_releases_version_rules( + tmp_path: Path, answer: str, status: int, problem: str | None, required: bool ) -> None: - main, sha = _tiny_main( - tmp_path, - {_EMITTER_FLOOR_REL: '{\n "minimum_emitter_version": "0.16.0"\n}\n'}, - ) - overrides = {"MAIN": str(main)} - if answer is None: - # No command configured and none on this PATH (system tools only). - overrides.update(MICROCOSM_EMITTER_COMMAND="", PATH="/usr/bin:/bin") - else: - overrides["MICROCOSM_EMITTER_COMMAND"] = str(_emitter_stub(tmp_path, answer)) + """``check_emitter.py`` repeats ``telemetry_emitter._start_emitter``: the + version command must exit 0 with a JSON object whose ``emitter_version`` + starts with a release at or above the floor.""" + + env = {"MICROCOSM_EMITTER_COMMAND": str(_emitter_stub(tmp_path, answer, status))} if required: - overrides["MICROCOSM_TELEMETRY_REQUIRED"] = "1" - result = _input_settings_result( - tmp_path, - overrides, - _report_lines(f"\nCOMMIT_NOTES=(); COMMIT_BLOCKERS=()\ncheck_emitter {sha}\n"), - ) - assert result.returncode == 0, result.stderr.decode() - lines = result.stdout.decode().splitlines() - assert len(lines) == 1, lines - if expected == "ok": - assert lines[0].startswith("NOTE microcosm-emitter "), lines - assert "meets the commit's floor 0.16.0" in lines[0] + env["MICROCOSM_TELEMETRY_REQUIRED"] = "1" + line = _emitter_line(_FLOOR, env) + if problem is None: + assert line.startswith("NOTE microcosm-emitter 0."), line + assert line.endswith("meets the commit's floor 0.16.0") return - assert expected in lines[0], lines - if required: - assert lines[0].startswith("BLOCKER "), lines - assert "would stop before any work" in lines[0] - else: - assert lines[0].startswith("NOTE "), lines - assert "without collector telemetry" in lines[0] + _assert_problem(line, problem, required) -def test_emitter_settings_reach_the_stages_and_bad_values_block( - tmp_path: Path, +@pytest.mark.parametrize( + ("answer", "problem"), + [ + ('{"emitter_version": "0.17.2"}', "printed no list of protocol versions"), + ( + '{"emitter_version": "0.17.2", "protocol_versions": ["1"]}', + "printed no list of protocol versions", + ), + ( + '{"emitter_version": "0.17.2", "protocol_versions": [2]}', + "not protocol version 1", + ), + ], +) +def test_a_required_build_also_needs_protocol_version_1( + tmp_path: Path, answer: str, problem: str ) -> None: - """The release reads both settings from its environment, so a value set - in the settings file is exported, and a value the release would refuse is - a blocker however the emitter looks.""" - - main, sha = _tiny_main( - tmp_path, - {_EMITTER_FLOOR_REL: '{"minimum_emitter_version": "0.16.0"}\n'}, + command = str(_emitter_stub(tmp_path, answer)) + required = _emitter_line( + _FLOOR, + {"MICROCOSM_EMITTER_COMMAND": command, "MICROCOSM_TELEMETRY_REQUIRED": "1"}, ) - emitter = str(_emitter_stub(tmp_path, '{"emitter_version": "0.16.0"}')) - exported = _input_settings_result( - tmp_path, + _assert_problem(required, problem, True) + # The release reads the protocol list only when telemetry is required. + optional = _emitter_line(_FLOOR, {"MICROCOSM_EMITTER_COMMAND": command}) + assert optional.startswith("NOTE microcosm-emitter 0.17.2 at "), optional + + +def test_emitter_command_lookup_follows_the_release(tmp_path: Path) -> None: + stub = _emitter_stub(tmp_path, _GOOD_EMITTER) + # Padding, Unicode whitespace included, is stripped as str.strip() does. + padded = _emitter_line(_FLOOR, {"MICROCOSM_EMITTER_COMMAND": f"\u0085 {stub}\t"}) + assert ( + padded + == f"NOTE microcosm-emitter 0.16.0 at {stub} meets the commit's floor 0.16.0" + ) + # Unset, the default name on PATH. + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + on_path = _emitter_stub(bin_dir, _GOOD_EMITTER, name="microcosm-emitter") + found = _emitter_line(_FLOOR, {"PATH": f"{bin_dir}:/usr/bin:/bin"}) + assert found.startswith(f"NOTE microcosm-emitter 0.16.0 at {on_path} "), found + missing = _emitter_line(_FLOOR, {}) + _assert_problem( + missing, "no microcosm-emitter found (microcosm-emitter on PATH)", False + ) + # A relative path resolves against the working directory, and the stages + # run in the build worktree, so it is refused even where it resolves. + relative = _emitter_line( + _FLOOR, { - "MAIN": str(main), + "MICROCOSM_EMITTER_COMMAND": "bin/microcosm-emitter", "MICROCOSM_TELEMETRY_REQUIRED": "1", - "MICROCOSM_EMITTER_COMMAND": f" {emitter} ", }, - "\nprintenv MICROCOSM_TELEMETRY_REQUIRED\nprintenv MICROCOSM_EMITTER_COMMAND\n" - + _report_lines(f"COMMIT_NOTES=(); COMMIT_BLOCKERS=()\ncheck_emitter {sha}\n"), - ) - assert exported.returncode == 0, exported.stderr.decode() - assert exported.stdout.decode().splitlines() == [ - "1", - f" {emitter} ", - f"NOTE microcosm-emitter 0.16.0 at {emitter} meets the commit's floor 0.16.0", - ] - refused = _input_settings_result( + cwd=tmp_path, + ) + _assert_problem(relative, "is the relative path 'bin/microcosm-emitter'", True) + + +def test_a_version_command_that_hangs_is_cut_off( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + spec = importlib.util.spec_from_file_location( + "route_a_check_emitter", ROUTE_A_TOOLS / "check_emitter.py" + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + assert module.TIMEOUT_SECONDS == 15.0 # the release's STARTUP_TIMEOUT_SECONDS + monkeypatch.setattr(module, "TIMEOUT_SECONDS", 0.5) + hang = write_executable(tmp_path / "hang", "#!/bin/bash\nexec sleep 30\n") + monkeypatch.setenv("MICROCOSM_EMITTER_COMMAND", str(hang)) + monkeypatch.setenv("MICROCOSM_TELEMETRY_REQUIRED", "1") + _assert_problem(module.check(_FLOOR), "did not answer within 0.5 s", True) + + +@pytest.mark.parametrize( + "floor", + [ + '{"minimum_emitter_version": "0.16.0junk"}', + '{"minimum_emitter_version": "0.16"}', + '{"minimum_emitter_version": ""}', + "{}", + "not json", + ], +) +def test_a_floor_the_release_cannot_read_blocks(tmp_path: Path, floor: str) -> None: + command = str(_emitter_stub(tmp_path, _GOOD_EMITTER)) + line = _emitter_line(floor, {"MICROCOSM_EMITTER_COMMAND": command}) + assert line.startswith("BLOCKER the commit's minimum_emitter_version.json"), line + + +@pytest.mark.parametrize("setting", ["yes", "true", " 1", ""]) +def test_a_telemetry_setting_the_release_refuses_blocks( + tmp_path: Path, setting: str +) -> None: + command = str(_emitter_stub(tmp_path, _GOOD_EMITTER)) + line = _emitter_line( + _FLOOR, + {"MICROCOSM_EMITTER_COMMAND": command, "MICROCOSM_TELEMETRY_REQUIRED": setting}, + ) + assert line == ( + f"BLOCKER MICROCOSM_TELEMETRY_REQUIRED is {setting!r}; the release " + "accepts only 1, 0 or unset and refuses anything else" + ) + + +def _driver_emitter(tmp_path: Path, overrides: dict[str, str], sha: str) -> list[str]: + result = _input_settings_result( tmp_path, - { - "MAIN": str(main), - "MICROCOSM_TELEMETRY_REQUIRED": "yes", - "MICROCOSM_EMITTER_COMMAND": emitter, - }, - _report_lines(f"\nCOMMIT_NOTES=(); COMMIT_BLOCKERS=()\ncheck_emitter {sha}\n"), + overrides, + _report_lines( + f"\nSCRIPT_DIR={shlex.quote(str(ROUTE_A_TOOLS))}\n" + f"COMMIT_NOTES=(); COMMIT_BLOCKERS=()\ncheck_emitter {sha}\n" + ), ) - assert refused.returncode == 0, refused.stderr.decode() - assert refused.stdout.decode().splitlines() == [ - "BLOCKER MICROCOSM_TELEMETRY_REQUIRED is 'yes'; the release accepts only " - "1, 0 or unset and refuses anything else" + assert result.returncode == 0, result.stderr.decode() + return result.stdout.decode().splitlines() + + +def test_driver_settings_reach_the_emitter_check_and_the_stages(tmp_path: Path) -> None: + """Settings-file values are exported, so the check and the stages (which + inherit the driver's environment) see them.""" + + main, sha = _tiny_main(tmp_path, {_EMITTER_FLOOR_REL: _FLOOR}) + old = str(_emitter_stub(tmp_path, '{"emitter_version": "0.13.0"}')) + good = str(_emitter_stub(tmp_path, _GOOD_EMITTER, name="good-emitter")) + required = {"MAIN": str(main), "MICROCOSM_TELEMETRY_REQUIRED": "1"} + assert _driver_emitter( + tmp_path, {**required, "MICROCOSM_EMITTER_COMMAND": old}, sha + ) == [ + f"BLOCKER microcosm-emitter 0.13.0 at {old} is older than the commit's floor " + "0.16.0 (uv tool install --upgrade 'microcosm-emitter>=0.16.0', or point " + "MICROCOSM_EMITTER_COMMAND at a newer one); MICROCOSM_TELEMETRY_REQUIRED=1, " + "so the release would stop before any work" ] + assert _driver_emitter( + tmp_path, {**required, "MICROCOSM_EMITTER_COMMAND": good}, sha + ) == [f"NOTE microcosm-emitter 0.16.0 at {good} meets the commit's floor 0.16.0"] + exported = _input_settings_result( + tmp_path, + {**required, "MICROCOSM_EMITTER_COMMAND": good}, + "\nprintenv MICROCOSM_TELEMETRY_REQUIRED\nprintenv MICROCOSM_EMITTER_COMMAND\n", + ) + assert exported.stdout.decode().splitlines() == ["1", good] def test_emitter_check_skips_a_commit_without_a_floor(tmp_path: Path) -> None: main, sha = _tiny_main(tmp_path, {"README.md": "fixture\n"}) - result = _input_settings_result( + assert _driver_emitter( tmp_path, {"MAIN": str(main), "MICROCOSM_EMITTER_COMMAND": str(tmp_path / "never-run")}, - _report_lines(f"\nCOMMIT_NOTES=(); COMMIT_BLOCKERS=()\ncheck_emitter {sha}\n"), - ) - assert result.returncode == 0, result.stderr.decode() - assert result.stdout.decode().splitlines() == [ - f"NOTE no readable {_EMITTER_FLOOR_REL} at {sha}; emitter not checked" - ] + sha, + ) == [f"NOTE no {_EMITTER_FLOOR_REL} at {sha}; emitter not checked"] @pytest.mark.parametrize("setting", [None, "3.13"]) diff --git a/tools/route_a/README.md b/tools/route_a/README.md index 0b828b3f6e..ad59bfe8de 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -75,14 +75,23 @@ first and set what its blockers name: `uv sync --python "$UV_SYNC_PYTHON"` (default `3.14`). Without it uv takes the newest installed CPython, and the lock's torch wheels stop at 3.14. - **Emitter.** `--resolve` reports the `microcosm-emitter` the release would - start (`MICROCOSM_EMITTER_COMMAND`, then `PATH`) against the commit's - `minimum_emitter_version.json`. With `MICROCOSM_TELEMETRY_REQUIRED=1` a - missing or older emitter is a blocker, because the release would stop - before any work. Otherwise it is a note: the release would run without - collector telemetry or staging hand-overs. A value other than `1`, `0` or - unset is a blocker, because the release refuses it. The driver exports both - settings when the settings file sets them. Publisher preflight starts no - emitter. + start against the commit's `minimum_emitter_version.json`. + `check_emitter.py` repeats the release's checks without importing + microcosm: + - the command is `MICROCOSM_EMITTER_COMMAND`, else `microcosm-emitter` on + `PATH`; + - `version` must exit 0 within 15 s and print a JSON object; + - the version must be a release at or above the floor; + - with telemetry required, the protocol list must hold version 1. + + With `MICROCOSM_TELEMETRY_REQUIRED=1` a failed check is a blocker, because + the release would stop before any work. Otherwise it is a note: the release + would run without collector telemetry or staging hand-overs. A relative + command path is refused, because the stages run in the build worktree. A + `MICROCOSM_TELEMETRY_REQUIRED` other than `1`, `0` or unset is a blocker, and + so is a floor file without an `X.Y.Z` release, because the release refuses + both. The driver exports both settings when the settings file sets them. + Publisher preflight starts no emitter. The example retains the historical d122 dense whole-base national/state settings, batch size 2000, export-mass reference and d490 tail register from the diff --git a/tools/route_a/check_emitter.py b/tools/route_a/check_emitter.py new file mode 100644 index 0000000000..d537057610 --- /dev/null +++ b/tools/route_a/check_emitter.py @@ -0,0 +1,160 @@ +"""Report the emitter a Route A release would start, against a commit's floor. + +The release starts ``microcosm-emitter`` through +``microcosm.build.telemetry_emitter._start_emitter``. This repeats its checks +without importing microcosm, so ``--resolve`` can run before the build +worktree exists: + +* the command is ``MICROCOSM_EMITTER_COMMAND`` (stripped), else + ``microcosm-emitter``, resolved with ``shutil.which``; +* `` version`` must exit 0 within 15 seconds and print a JSON object; +* its ``emitter_version`` must start with a release number at or above the + floor (``minimum_emitter_version.json``, which must hold exactly ``X.Y.Z``); +* a build that requires telemetry (``MICROCOSM_TELEMETRY_REQUIRED=1``) also + needs ``protocol_versions`` to be a list of integers holding 1. + +The stages run in the build worktree, so a relative command path, which +``shutil.which`` resolves against the working directory, is refused here. + +usage: check_emitter.py < minimum_emitter_version.json +Prints one line, ``NOTE `` or ``BLOCKER ``, and exits 0. +""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import sys + +COMMAND_VARIABLE = "MICROCOSM_EMITTER_COMMAND" +REQUIRED_VARIABLE = "MICROCOSM_TELEMETRY_REQUIRED" +DEFAULT_COMMAND = "microcosm-emitter" +PROTOCOL_VERSION = 1 +TIMEOUT_SECONDS = 15.0 +_RELEASE = re.compile(r"(\d+)\.(\d+)\.(\d+)") + + +def _release(text: object) -> tuple[int, ...] | None: + found = _RELEASE.match(text) if isinstance(text, str) else None + return None if found is None else tuple(int(part) for part in found.groups()) + + +def _floor(text: str) -> str | None: + try: + data = json.loads(text) + except ValueError: + return None + floor = data.get("minimum_emitter_version") if isinstance(data, dict) else None + if isinstance(floor, str) and _RELEASE.fullmatch(floor): + return floor + return None + + +def _problem(floor: str, required: bool) -> tuple[str | None, str]: + """Why the release would not start an emitter it accepts (None if it + would), and what the accepted emitter is.""" + + named = os.environ.get(COMMAND_VARIABLE, "").strip() + candidate = named or DEFAULT_COMMAND + if os.sep in candidate and not os.path.isabs(candidate): + return ( + f"{COMMAND_VARIABLE} is the relative path {candidate!r}; the stages " + "run in the build worktree, so give an absolute path" + ), "" + command = shutil.which(candidate) + if command is None: + looked = ( + f"{candidate!r}, named by {COMMAND_VARIABLE}" + if named + else f"{DEFAULT_COMMAND} on PATH" + ) + return ( + f"no microcosm-emitter found ({looked}); the release needs {floor} or later" + ), "" + try: + answer = subprocess.run( + [command, "version"], + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=TIMEOUT_SECONDS, + check=False, + ) + except subprocess.TimeoutExpired: + return f"`{command} version` did not answer within {TIMEOUT_SECONDS:g} s", "" + except OSError as error: + return f"`{command} version` could not be run ({type(error).__name__})", "" + if answer.returncode != 0: + return f"`{command} version` exited {answer.returncode}", "" + try: + description = json.loads(answer.stdout) + except ValueError: + description = None + if not isinstance(description, dict): + return f"`{command} version` printed no JSON object", "" + version = description.get("emitter_version") + installed = _release(version) + if installed is None: + return ( + f"`{command} version` reported no release version ({version!r}); " + f"the release needs {floor} or later" + ), "" + if installed < _release(floor): + return ( + f"microcosm-emitter {version} at {command} is older than the commit's " + f"floor {floor} (uv tool install --upgrade 'microcosm-emitter>={floor}', " + f"or point {COMMAND_VARIABLE} at a newer one)" + ), "" + if required: + versions = description.get("protocol_versions") + if not isinstance(versions, list) or not all(type(v) is int for v in versions): + return f"`{command} version` printed no list of protocol versions", "" + if PROTOCOL_VERSION not in versions: + return ( + f"`{command} version` lists protocol versions {versions}, not " + f"protocol version {PROTOCOL_VERSION}, the one the release sends" + ), "" + return None, f"microcosm-emitter {version} at {command}" + + +def check(floor_text: str) -> str: + """The one line ``check_emitter`` in ``route_a.sh`` reports.""" + + setting = os.environ.get(REQUIRED_VARIABLE) + if setting not in (None, "0", "1"): + return ( + f"BLOCKER {REQUIRED_VARIABLE} is {setting!r}; the release accepts only " + "1, 0 or unset and refuses anything else" + ) + required = setting == "1" + floor = _floor(floor_text) + if floor is None: + return ( + "BLOCKER the commit's minimum_emitter_version.json does not hold " + '{"minimum_emitter_version": "X.Y.Z"}, so the release would fail to ' + "import its telemetry module" + ) + problem, accepted = _problem(floor, required) + if problem is None: + return f"NOTE {accepted} meets the commit's floor {floor}" + if required: + return ( + f"BLOCKER {problem}; {REQUIRED_VARIABLE}=1, so the release would stop " + "before any work" + ) + return ( + f"NOTE {problem}; {REQUIRED_VARIABLE} is not 1, so the release would run " + "without collector telemetry or staging hand-overs" + ) + + +def main() -> int: + print(check(sys.stdin.read())) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/route_a/route_a.sh b/tools/route_a/route_a.sh index 77ddb2ecd3..e2244a7836 100755 --- a/tools/route_a/route_a.sh +++ b/tools/route_a/route_a.sh @@ -187,11 +187,15 @@ check_commit() { # $1 = build ref, $2 = preflight ref; fills COMMIT_BLOCKERS/CO || COMMIT_BLOCKERS+=("asec_sources.py at $full lacks canonical ASEC pin $s (the base would refuse the CLI pin)") done local crosswalk - crosswalk=$(git -C "$MAIN" show "$full:$CROSSWALK_REL" 2>/dev/null | openssl dgst -sha256 -r | cut -c1-64) - if [ "$crosswalk" = "$CROSSWALK_SHA" ]; then - COMMIT_NOTES+=("packaged CD vintage crosswalk at $full = $CROSSWALK_SHA") + if ! git -C "$MAIN" cat-file -e "$full:$CROSSWALK_REL" 2>/dev/null; then + COMMIT_BLOCKERS+=("no packaged CD vintage crosswalk at $full ($CROSSWALK_REL)") else - COMMIT_BLOCKERS+=("packaged CD vintage crosswalk at $full is $crosswalk, not $CROSSWALK_SHA: set CROSSWALK_SHA to it once the change is reviewed") + crosswalk=$(git -C "$MAIN" show "$full:$CROSSWALK_REL" | openssl dgst -sha256 -r | cut -c1-64) + if [ "$crosswalk" = "$CROSSWALK_SHA" ]; then + COMMIT_NOTES+=("packaged CD vintage crosswalk at $full = $CROSSWALK_SHA") + else + COMMIT_BLOCKERS+=("packaged CD vintage crosswalk at $full is $crosswalk, not $CROSSWALK_SHA: set CROSSWALK_SHA to it once the change is reviewed") + fi fi if git -C "$MAIN" show "$full:tools/build_us_fiscal_refresh_release.py" 2>/dev/null | grep -q '_check_committed_us_ledger_feed_pin'; then COMMIT_NOTES+=("release tool at $full holds the feed to the committed pin") @@ -250,45 +254,18 @@ check_emitter() { # $1 = full build sha; adds to COMMIT_NOTES/COMMIT_BLOCKERS # than the commit's minimum_emitter_version.json. With # MICROCOSM_TELEMETRY_REQUIRED=1 such an emitter stops the release before it # does any work; otherwise the release runs without telemetry. - local full=$1 floor cmd version verdict problem - case "${MICROCOSM_TELEMETRY_REQUIRED-0}" in - 0|1) ;; - *) COMMIT_BLOCKERS+=("MICROCOSM_TELEMETRY_REQUIRED is '${MICROCOSM_TELEMETRY_REQUIRED}'; the release accepts only 1, 0 or unset and refuses anything else") - return ;; - esac - floor=$(git -C "$MAIN" show "$full:$EMITTER_FLOOR_REL" 2>/dev/null | \ - "$PYTHON" -c 'import json, sys; print(json.load(sys.stdin)["minimum_emitter_version"])' 2>/dev/null) - if [ -z "$floor" ]; then - COMMIT_NOTES+=("no readable $EMITTER_FLOOR_REL at $full; emitter not checked") + # check_emitter.py repeats the release's checks without importing microcosm. + local full=$1 line + if ! git -C "$MAIN" cat-file -e "$full:$EMITTER_FLOOR_REL" 2>/dev/null; then + COMMIT_NOTES+=("no $EMITTER_FLOOR_REL at $full; emitter not checked") return fi - cmd=${MICROCOSM_EMITTER_COMMAND-} - cmd=${cmd#"${cmd%%[![:space:]]*}"}; cmd=${cmd%"${cmd##*[![:space:]]}"} - [ -n "$cmd" ] || cmd=$(command -v microcosm-emitter 2>/dev/null) - if [ -z "$cmd" ]; then - problem="no microcosm-emitter found (MICROCOSM_EMITTER_COMMAND, then PATH); the release needs $floor or later" - else - version=$("$cmd" version /dev/null | \ - "$PYTHON" -c 'import json, sys; print(json.load(sys.stdin).get("emitter_version") or "")' 2>/dev/null) - verdict=$("$PYTHON" -c ' -import re, sys -def release(text): - found = re.match(r"(\d+)\.(\d+)\.(\d+)", text) - return None if found is None else tuple(int(part) for part in found.groups()) -have, need = release(sys.argv[1]), release(sys.argv[2]) -print("unknown" if have is None or need is None else "ok" if have >= need else "old") -' "$version" "$floor" 2>/dev/null) - case "$verdict" in - ok) COMMIT_NOTES+=("microcosm-emitter $version at $cmd meets the commit's floor $floor"); return ;; - old) problem="microcosm-emitter $version at $cmd is older than the commit's floor $floor (uv tool install --upgrade 'microcosm-emitter>=$floor', or point MICROCOSM_EMITTER_COMMAND at a newer one)" ;; - *) problem="microcosm-emitter at $cmd reported no release version (\`$cmd version\`); the release needs $floor or later" ;; - esac - fi - if [ "${MICROCOSM_TELEMETRY_REQUIRED:-0}" = 1 ]; then - COMMIT_BLOCKERS+=("$problem; MICROCOSM_TELEMETRY_REQUIRED=1, so the release would stop before any work") - else - COMMIT_NOTES+=("$problem; MICROCOSM_TELEMETRY_REQUIRED is not 1, so the release would run without collector telemetry or staging hand-overs") - fi + line=$(git -C "$MAIN" show "$full:$EMITTER_FLOOR_REL" | "$PYTHON" -I "$SCRIPT_DIR/check_emitter.py" 2>&1) + case "$line" in + "NOTE "*) COMMIT_NOTES+=("${line#NOTE }") ;; + "BLOCKER "*) COMMIT_BLOCKERS+=("${line#BLOCKER }") ;; + *) COMMIT_BLOCKERS+=("the emitter check at $full failed: ${line:-no output}") ;; + esac } refuse_bad_release_args() { From 8346839429cf8255213f8637ea63f8523da93f08 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 19:17:34 -0500 Subject: [PATCH 3/5] Answer #1650 review r2: PATH entries, undecodable output, sync marker - check_emitter.py refuses a bare emitter command when PATH reaches a relative or empty entry before a directory that holds it, since the stages resolve PATH from the build worktree. - It treats any exception from `version` as a failed run, as the release does, so undecodable output no longer becomes a traceback blocker. - The sync marker records UV_SYNC_PYTHON; a resumed chain whose setting changed stops instead of keeping the old venv silently. - route_a.env.example says unset or 0 still starts an accepted emitter. - The build-rule note names the remaining --exact-k work: a feed re-pin past Chronicle's chronicle#277 fix (b571381f, merged in 0ca1c0d6). - Tests for each, plus the floor read at the requested commit. Co-Authored-By: Claude Opus 5.5 --- docs/us-release-build-rule.md | 5 +- .../engine_free/us/test_route_a_driver.py | 150 ++++++++++++++++-- tools/route_a/README.md | 4 +- tools/route_a/check_emitter.py | 38 ++++- tools/route_a/route_a.env.example | 5 +- tools/route_a/route_a.sh | 14 +- 6 files changed, 197 insertions(+), 19 deletions(-) diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index d5753db860..340f9ecfc9 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -53,7 +53,10 @@ which route A (`tools/route_a/route_a.sh`) drives: refuses a command-line ASEC digest that differs from its year's pin (section 4). -The `--exact-k` arm still waits on chronicle#277. A build from a newer main +The `--exact-k` arm still waits on a reviewed feed re-pin. Chronicle fixed +chronicle#277 in `b571381f` (merged 28 September 2026 in `0ca1c0d6`), but +`us/chronicle_feed.json` pins Chronicle `41b2fb2b`, which predates the fix. A +build from a newer main commit needs settings beyond the commit; "A build from main" in `tools/route_a/README.md` lists them. diff --git a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py index c799834bea..887c3fe329 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py +++ b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py @@ -499,6 +499,60 @@ def test_emitter_command_lookup_follows_the_release(tmp_path: Path) -> None: _assert_problem(relative, "is the relative path 'bin/microcosm-emitter'", True) +def test_a_relative_path_entry_before_the_emitter_is_refused( + tmp_path: Path, +) -> None: + """``shutil.which`` searches relative and empty PATH entries against the + working directory, and the stages run in the build worktree.""" + + local = tmp_path / "bin" + local.mkdir() + _emitter_stub(local, _GOOD_EMITTER, name="microcosm-emitter") + required = {"MICROCOSM_TELEMETRY_REQUIRED": "1"} + relative = _emitter_line( + _FLOOR, {**required, "PATH": "bin:/usr/bin:/bin"}, cwd=tmp_path + ) + _assert_problem(relative, "the relative PATH entry 'bin' comes before", True) + empty = _emitter_line(_FLOOR, {**required, "PATH": ":/usr/bin:/bin"}, cwd=local) + _assert_problem(empty, "an empty PATH entry (the working directory)", True) + # Found in an absolute entry first: the relative one after it is never + # searched. + absolute = tmp_path / "abs" + absolute.mkdir() + found = _emitter_stub(absolute, _GOOD_EMITTER, name="microcosm-emitter") + line = _emitter_line( + _FLOOR, {**required, "PATH": f"{absolute}:bin:/usr/bin"}, cwd=tmp_path + ) + assert line.startswith(f"NOTE microcosm-emitter 0.16.0 at {found} "), line + # An absolute MICROCOSM_EMITTER_COMMAND does not search PATH. + line = _emitter_line( + _FLOOR, + {**required, "PATH": "bin:/usr/bin", "MICROCOSM_EMITTER_COMMAND": str(found)}, + cwd=tmp_path, + ) + assert line.startswith(f"NOTE microcosm-emitter 0.16.0 at {found} "), line + + +@pytest.mark.parametrize("required", [False, True]) +def test_undecodable_version_output_is_a_failed_run_as_in_the_release( + tmp_path: Path, required: bool +) -> None: + """The release catches any exception from ``version`` (a decoding error + included) and goes on without an emitter unless telemetry is required.""" + + stub = write_executable( + tmp_path / "bytes-emitter", + "#!/bin/bash\n" + f"printf '%s\\n' {shlex.quote(_GOOD_EMITTER)}\n" + "printf '\\377\\n' >&2\n", + ) + env = {"MICROCOSM_EMITTER_COMMAND": str(stub)} + if required: + env["MICROCOSM_TELEMETRY_REQUIRED"] = "1" + line = _emitter_line(_FLOOR, env) + _assert_problem(line, "could not be run (UnicodeDecodeError)", required) + + def test_a_version_command_that_hangs_is_cut_off( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -587,6 +641,35 @@ def test_driver_settings_reach_the_emitter_check_and_the_stages(tmp_path: Path) assert exported.stdout.decode().splitlines() == ["1", good] +def test_the_emitter_floor_is_read_at_the_requested_commit(tmp_path: Path) -> None: + """``--resolve`` reads the floor of the commit it checks, not of the + checkout: an older commit with a lower floor accepts an older emitter.""" + + main, older = _tiny_main( + tmp_path, {_EMITTER_FLOOR_REL: '{"minimum_emitter_version": "0.13.0"}\n'} + ) + (main / _EMITTER_FLOOR_REL).write_text(_FLOOR, encoding="utf-8") + git = ["git", "-C", str(main), "-c", "user.name=fixture"] + git += ["-c", "user.email=fixture@example.invalid", "-c", "commit.gpgsign=false"] + git += ["-c", "core.hooksPath=/dev/null"] + subprocess.run([*git, "commit", "-qam", "raise"], check=True, timeout=20) + old = str( + _emitter_stub( + tmp_path, '{"emitter_version": "0.13.0", "protocol_versions": [1]}' + ) + ) + settings = { + "MAIN": str(main), + "MICROCOSM_TELEMETRY_REQUIRED": "1", + "MICROCOSM_EMITTER_COMMAND": old, + } + assert _driver_emitter(tmp_path, settings, older) == [ + f"NOTE microcosm-emitter 0.13.0 at {old} meets the commit's floor 0.13.0" + ] + line = _driver_emitter(tmp_path, settings, "HEAD") + assert len(line) == 1 and "older than the commit's floor 0.16.0" in line[0] + + def test_emitter_check_skips_a_commit_without_a_floor(tmp_path: Path) -> None: main, sha = _tiny_main(tmp_path, {"README.md": "fixture\n"}) assert _driver_emitter( @@ -596,12 +679,14 @@ def test_emitter_check_skips_a_commit_without_a_floor(tmp_path: Path) -> None: ) == [f"NOTE no {_EMITTER_FLOOR_REL} at {sha}; emitter not checked"] -@pytest.mark.parametrize("setting", [None, "3.13"]) -def test_worktree_sync_names_its_interpreter( - tmp_path: Path, setting: str | None -) -> None: - """A fresh worktree's uv sync names an interpreter the lock has wheels - for; without one uv takes the newest installed CPython.""" +_SYNC_SHA = "d" * 40 + + +def _ensure_worktree( + tmp_path: Path, overrides: dict[str, str], marker: str | None = None +) -> tuple[subprocess.CompletedProcess[bytes], Path]: + """Run ``ensure_worktree`` with stub ``git`` and ``uv``; ``marker`` is an + earlier sync's ``.route_a_synced`` in a worktree that already exists.""" recorded = tmp_path / "uv-args" uv = write_executable( @@ -612,6 +697,10 @@ def test_worktree_sync_names_its_interpreter( "printf '#!/bin/bash\\nexit 0\\n' > .venv/bin/python\n" "chmod +x .venv/bin/python\n", ) + if marker is not None: + venv = tmp_path / "wt_root" / f"microcosm-route-a-{_SYNC_SHA[:12]}" / ".venv" + venv.mkdir(parents=True) + (venv / ".route_a_synced").write_text(marker, encoding="utf-8") commands = ( "\ngit() {\n" ' case "$3" in\n' @@ -620,16 +709,27 @@ def test_worktree_sync_names_its_interpreter( ' rev-parse) printf "%s\\n" "$FIXTURE_SHA" ;;\n' " esac\n" "}\n" - f"FIXTURE_SHA={'d' * 40}\n" + f"FIXTURE_SHA={_SYNC_SHA}\n" + _function("ensure_worktree") + '\nensure_worktree "$FIXTURE_SHA"\n' ) run_root = tmp_path / "run-root" run_root.mkdir() - overrides = {"UV": str(uv), "RUN_ROOT": str(run_root)} - if setting is not None: - overrides["UV_SYNC_PYTHON"] = setting - result = _input_settings_result(tmp_path, overrides, commands) + result = _input_settings_result( + tmp_path, {"UV": str(uv), "RUN_ROOT": str(run_root), **overrides}, commands + ) + return result, recorded + + +@pytest.mark.parametrize("setting", [None, "3.13"]) +def test_worktree_sync_names_its_interpreter( + tmp_path: Path, setting: str | None +) -> None: + """A fresh worktree's uv sync names an interpreter the lock has wheels + for; without one uv takes the newest installed CPython.""" + + overrides = {} if setting is None else {"UV_SYNC_PYTHON": setting} + result, recorded = _ensure_worktree(tmp_path, overrides) assert result.returncode == 0, result.stderr.decode() assert recorded.read_text(encoding="utf-8").splitlines() == [ "sync", @@ -640,6 +740,34 @@ def test_worktree_sync_names_its_interpreter( "--extra", "us", ] + marker = tmp_path / "wt_root" / f"microcosm-route-a-{_SYNC_SHA[:12]}" + synced = (marker / ".venv" / ".route_a_synced").read_text(encoding="utf-8") + assert synced.splitlines()[1] == f"python={setting or '3.14'}" + + +@pytest.mark.parametrize( + ("marker", "setting", "outcome"), + [ + ("2026-11-16 10:00:00\npython=3.14\n", None, "kept"), + ("2026-11-16 10:00:00\npython=3.13\n", "3.13", "kept"), + ("2026-11-16 10:00:00\n", None, "unrecorded"), + ("2026-11-16 10:00:00\npython=3.13\n", None, "refused"), + ], +) +def test_a_resumed_worktree_keeps_its_venv_only_for_the_same_interpreter( + tmp_path: Path, marker: str, setting: str | None, outcome: str +) -> None: + overrides = {} if setting is None else {"UV_SYNC_PYTHON": setting} + result, recorded = _ensure_worktree(tmp_path, overrides, marker) + out = result.stdout.decode() + assert not recorded.exists(), "a synced worktree is not synced again" + if outcome == "refused": + assert result.returncode == 1 + assert "was synced with --python 3.13, not UV_SYNC_PYTHON=3.14" in out + assert (tmp_path / "run-root" / "ROUTE_A_FAILED").exists() + return + assert result.returncode == 0, result.stderr.decode() + assert ("before its interpreter was recorded" in out) == (outcome == "unrecorded") def test_shell_scripts_are_valid_bash() -> None: diff --git a/tools/route_a/README.md b/tools/route_a/README.md index ad59bfe8de..a6ada14bbe 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -73,7 +73,9 @@ first and set what its blockers name: once the change is reviewed. - **Interpreter.** A fresh worktree syncs with `uv sync --python "$UV_SYNC_PYTHON"` (default `3.14`). Without it uv takes - the newest installed CPython, and the lock's torch wheels stop at 3.14. + the newest installed CPython, and the lock's torch wheels stop at 3.14. The + sync marker records the setting, and a resumed chain whose setting changed + stops rather than keep the old venv silently. - **Emitter.** `--resolve` reports the `microcosm-emitter` the release would start against the commit's `minimum_emitter_version.json`. `check_emitter.py` repeats the release's checks without importing diff --git a/tools/route_a/check_emitter.py b/tools/route_a/check_emitter.py index d537057610..aa70c329b8 100644 --- a/tools/route_a/check_emitter.py +++ b/tools/route_a/check_emitter.py @@ -14,7 +14,10 @@ needs ``protocol_versions`` to be a list of integers holding 1. The stages run in the build worktree, so a relative command path, which -``shutil.which`` resolves against the working directory, is refused here. +``shutil.which`` resolves against the working directory, is refused here, and +so is a bare command when ``PATH`` reaches a relative or empty entry (the +working directory) before a directory that holds it: either could find a +different emitter, or none, in the worktree. usage: check_emitter.py < minimum_emitter_version.json Prints one line, ``NOTE `` or ``BLOCKER ``, and exits 0. @@ -53,6 +56,23 @@ def _floor(text: str) -> str | None: return None +def _relative_entry(candidate: str) -> str | None: + """The first relative or empty ``PATH`` entry ``shutil.which`` searches + before an absolute one that holds ``candidate``, or None.""" + + path = os.environ.get("PATH") + if not path: + # Unset: which falls back to CS_PATH or os.defpath, both absolute. + # Empty: which finds nothing. + return None + for entry in path.split(os.pathsep): + if not os.path.isabs(entry): + return entry + if shutil.which(candidate, path=entry) is not None: + return None + return None + + def _problem(floor: str, required: bool) -> tuple[str | None, str]: """Why the release would not start an emitter it accepts (None if it would), and what the accepted emitter is.""" @@ -64,6 +84,20 @@ def _problem(floor: str, required: bool) -> tuple[str | None, str]: f"{COMMAND_VARIABLE} is the relative path {candidate!r}; the stages " "run in the build worktree, so give an absolute path" ), "" + if os.sep not in candidate: + entry = _relative_entry(candidate) + if entry is not None: + where = ( + "an empty PATH entry (the working directory)" + if entry == "" + else f"the relative PATH entry {entry!r}" + ) + return ( + f"{where} comes before any directory holding {candidate}; the " + "stages run in the build worktree, where it could find a " + "different emitter or none, so make PATH's entries absolute or " + f"set {COMMAND_VARIABLE} to an absolute path" + ), "" command = shutil.which(candidate) if command is None: looked = ( @@ -85,7 +119,7 @@ def _problem(floor: str, required: bool) -> tuple[str | None, str]: ) except subprocess.TimeoutExpired: return f"`{command} version` did not answer within {TIMEOUT_SECONDS:g} s", "" - except OSError as error: + except Exception as error: # as the release does: undecodable output too return f"`{command} version` could not be run ({type(error).__name__})", "" if answer.returncode != 0: return f"`{command} version` exited {answer.returncode}", "" diff --git a/tools/route_a/route_a.env.example b/tools/route_a/route_a.env.example index d83973a0bd..948afe3af8 100644 --- a/tools/route_a/route_a.env.example +++ b/tools/route_a/route_a.env.example @@ -40,8 +40,9 @@ # The release starts microcosm-emitter (MICROCOSM_EMITTER_COMMAND, then PATH) # and refuses one older than the commit's minimum_emitter_version.json. # PolicyEngine builds set MICROCOSM_TELEMETRY_REQUIRED=1, and --resolve then -# blocks on a missing or old emitter; unset or 0 runs without telemetry. The -# driver exports either setting made here. +# blocks on a missing or old emitter. Unset or 0 still starts an emitter that +# meets the floor, but lets the release go on without telemetry when none +# does. The driver exports either setting made here. # : "${MICROCOSM_TELEMETRY_REQUIRED:=1}" : "${RELEASE_RAM_GIB:=50}" : "${RELEASE_WALL_SECONDS:=345600}" diff --git a/tools/route_a/route_a.sh b/tools/route_a/route_a.sh index e2244a7836..234204a50b 100755 --- a/tools/route_a/route_a.sh +++ b/tools/route_a/route_a.sh @@ -379,11 +379,21 @@ ensure_worktree() { # $1 = full sha; sets WT log "created worktree $WT at $c" fi [ -z "$(git -C "$WT" status --porcelain)" ] || fail "worktree $WT is dirty" - if [ ! -f "$WT/.venv/.route_a_synced" ]; then + local marker=$WT/.venv/.route_a_synced synced + if [ ! -f "$marker" ]; then log "uv sync --python $UV_SYNC_PYTHON --all-packages --locked --extra us in $WT" (cd "$WT" && "$UV" sync --python "$UV_SYNC_PYTHON" --all-packages --locked --extra us) >>"$LOG" 2>&1 || fail "uv sync in $WT" "$WT/.venv/bin/python" -c 'import psutil, policyengine_us' >>"$LOG" 2>&1 || fail "venv in $WT lacks psutil/policyengine_us" - date '+%F %T' > "$WT/.venv/.route_a_synced" + printf '%s\npython=%s\n' "$(date '+%F %T')" "$UV_SYNC_PYTHON" > "$marker" + else + # A resumed chain keeps its venv; a changed interpreter setting would + # otherwise be ignored without a word. + synced=$(sed -n 's/^python=//p' "$marker") + if [ -z "$synced" ]; then + log "worktree $WT was synced before its interpreter was recorded; keeping its venv" + elif [ "$synced" != "$UV_SYNC_PYTHON" ]; then + fail "worktree $WT was synced with --python $synced, not UV_SYNC_PYTHON=$UV_SYNC_PYTHON: set it back, or remove $marker to re-sync" + fi fi [ -z "$(git -C "$WT" status --porcelain)" ] || fail "worktree $WT dirty after uv sync" } From d69b275a0bd550808b58bf9961778cfc428ecec3 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 19:31:37 -0500 Subject: [PATCH 4/5] Answer #1650 review r3 nits: legacy marker, feed re-pin wording - README: a worktree synced before the marker recorded UV_SYNC_PYTHON keeps its venv whatever the setting, with a log line; remove the marker to re-sync. - Build-rule note: the pinned Chronicle 41b2fb2b does not contain the chronicle#277 fix (a 3 November cherry-pick onto an older base), so --exact-k waits on a reviewed feed re-pin. Co-Authored-By: Claude Opus 5.5 --- docs/us-release-build-rule.md | 6 +++--- tools/route_a/README.md | 5 ++++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 340f9ecfc9..0b0629020f 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -55,9 +55,9 @@ which route A (`tools/route_a/route_a.sh`) drives: The `--exact-k` arm still waits on a reviewed feed re-pin. Chronicle fixed chronicle#277 in `b571381f` (merged 28 September 2026 in `0ca1c0d6`), but -`us/chronicle_feed.json` pins Chronicle `41b2fb2b`, which predates the fix. A -build from a newer main -commit needs settings beyond the commit; "A build from main" in +`us/chronicle_feed.json` pins Chronicle `41b2fb2b`, which does not contain the +fix (a later cherry-pick on an older base). A build from a newer main commit +needs settings beyond the commit; "A build from main" in `tools/route_a/README.md` lists them. ### 1. No Chronicle feed on the build machine carries dimension labels diff --git a/tools/route_a/README.md b/tools/route_a/README.md index a6ada14bbe..3d5d8d70c9 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -75,7 +75,10 @@ first and set what its blockers name: `uv sync --python "$UV_SYNC_PYTHON"` (default `3.14`). Without it uv takes the newest installed CPython, and the lock's torch wheels stop at 3.14. The sync marker records the setting, and a resumed chain whose setting changed - stops rather than keep the old venv silently. + stops rather than keep the old venv silently. A worktree synced before the + marker recorded it keeps its venv whatever the setting, with a log line + saying so, so an in-flight chain is not re-synced under it; remove the + marker to re-sync. - **Emitter.** `--resolve` reports the `microcosm-emitter` the release would start against the commit's `minimum_emitter_version.json`. `check_emitter.py` repeats the release's checks without importing From 4eaec5c376f8f4439479080e5d2458d3a79cc774 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 20:01:00 -0500 Subject: [PATCH 5/5] Drop UV_FROZEN for the driver's worktree sync uv 0.11.7 refuses `--locked` beside UV_FROZEN=1 at argument parsing (exit 2, "the argument `--locked` cannot be used with `UV_FROZEN`"), and fails to parse an empty UV_FROZEN. A driver started from a shell whose profile exports UV_FROZEN=1 therefore stopped at "uv sync in $WT". The sync now unsets it in its subshell, as supervise.py already does for the stages. Raised by the Microcosm hub's F18 run-files check; F18's step 1 removes it the same way. The new test's uv stub refuses --locked whenever UV_FROZEN is set; both cases fail with the unset reverted. Co-Authored-By: Claude Opus 5.5 --- .../route-a-driver-main-pins.changed.md | 2 +- .../engine_free/us/test_route_a_driver.py | 35 +++++++++++++++++-- tools/route_a/README.md | 3 +- tools/route_a/route_a.sh | 4 ++- 4 files changed, 39 insertions(+), 5 deletions(-) diff --git a/changelog.d/route-a-driver-main-pins.changed.md b/changelog.d/route-a-driver-main-pins.changed.md index 21db810d4a..c990f33eae 100644 --- a/changelog.d/route-a-driver-main-pins.changed.md +++ b/changelog.d/route-a-driver-main-pins.changed.md @@ -1 +1 @@ -The Route A driver (`tools/route_a/route_a.sh`) now says what a build from a newer main commit needs. Its feed and crosswalk blockers name the commit's own pinned feed digest and crosswalk digest, so a rerun's settings can copy them; the published run's defaults are unchanged. A fresh worktree syncs with `uv sync --python "$UV_SYNC_PYTHON"` (default `3.14`), because uv otherwise takes the newest installed CPython and the lock's torch wheels stop at 3.14. `--resolve` checks the `microcosm-emitter` the release would start against the commit's `minimum_emitter_version.json` with `tools/route_a/check_emitter.py`, which repeats the release's own checks (command lookup, a 15 s `version` call, the release floor and, when telemetry is required, protocol version 1). With `MICROCOSM_TELEMETRY_REQUIRED=1` a failed check is a blocker, otherwise a note. A missing packaged crosswalk is now a blocker that names no digest. The driver exports `MICROCOSM_TELEMETRY_REQUIRED` and `MICROCOSM_EMITTER_COMMAND` when the settings file sets them, so the stages see what `--resolve` checked. `tools/route_a/README.md` gains a section on building from main, and `docs/us-release-build-rule.md` records that the four September causes are answered on the `--base-h5` arm. +The Route A driver (`tools/route_a/route_a.sh`) now says what a build from a newer main commit needs. Its feed and crosswalk blockers name the commit's own pinned feed digest and crosswalk digest, so a rerun's settings can copy them; the published run's defaults are unchanged. A fresh worktree syncs with `uv sync --python "$UV_SYNC_PYTHON"` (default `3.14`), because uv otherwise takes the newest installed CPython and the lock's torch wheels stop at 3.14. The sync drops `UV_FROZEN`, since uv refuses `--locked` beside `UV_FROZEN=1`. `--resolve` checks the `microcosm-emitter` the release would start against the commit's `minimum_emitter_version.json` with `tools/route_a/check_emitter.py`, which repeats the release's own checks (command lookup, a 15 s `version` call, the release floor and, when telemetry is required, protocol version 1). With `MICROCOSM_TELEMETRY_REQUIRED=1` a failed check is a blocker, otherwise a note. A missing packaged crosswalk is now a blocker that names no digest. The driver exports `MICROCOSM_TELEMETRY_REQUIRED` and `MICROCOSM_EMITTER_COMMAND` when the settings file sets them, so the stages see what `--resolve` checked. `tools/route_a/README.md` gains a section on building from main, and `docs/us-release-build-rule.md` records that the four September causes are answered on the `--base-h5` arm. diff --git a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py index 887c3fe329..ecfd7a4d9c 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py +++ b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py @@ -683,15 +683,29 @@ def test_emitter_check_skips_a_commit_without_a_floor(tmp_path: Path) -> None: def _ensure_worktree( - tmp_path: Path, overrides: dict[str, str], marker: str | None = None + tmp_path: Path, + overrides: dict[str, str], + marker: str | None = None, + environment: str = "", ) -> tuple[subprocess.CompletedProcess[bytes], Path]: """Run ``ensure_worktree`` with stub ``git`` and ``uv``; ``marker`` is an - earlier sync's ``.route_a_synced`` in a worktree that already exists.""" + earlier sync's ``.route_a_synced`` in a worktree that already exists, and + ``environment`` is shell run first (exports a caller's shell would hand + down). The stub refuses ``--locked`` whenever ``UV_FROZEN`` is set; uv + 0.11 refuses it beside a true value and fails to parse an empty one.""" recorded = tmp_path / "uv-args" uv = write_executable( tmp_path / "uv-stub", "#!/bin/bash\n" + 'if [ -n "${UV_FROZEN+set}" ]; then\n' + ' for a in "$@"; do\n' + ' [ "$a" != --locked ] || {\n' + " echo 'error: the argument `--locked` cannot be used with `UV_FROZEN`' >&2\n" + " exit 2\n" + " }\n" + " done\n" + "fi\n" f'printf "%s\\n" "$@" > {shlex.quote(str(recorded))}\n' "mkdir -p .venv/bin\n" "printf '#!/bin/bash\\nexit 0\\n' > .venv/bin/python\n" @@ -710,6 +724,8 @@ def _ensure_worktree( " esac\n" "}\n" f"FIXTURE_SHA={_SYNC_SHA}\n" + + environment + + "\n" + _function("ensure_worktree") + '\nensure_worktree "$FIXTURE_SHA"\n' ) @@ -745,6 +761,21 @@ def test_worktree_sync_names_its_interpreter( assert synced.splitlines()[1] == f"python={setting or '3.14'}" +@pytest.mark.parametrize("frozen", ["1", ""]) +def test_worktree_sync_drops_an_inherited_uv_frozen( + tmp_path: Path, frozen: str +) -> None: + """A driver started from a shell that exports UV_FROZEN=1 (as a profile + may) still syncs: uv refuses --locked beside a true UV_FROZEN and fails on + an empty one, so the sync drops it.""" + + result, recorded = _ensure_worktree( + tmp_path, {}, environment=f"export UV_FROZEN={shlex.quote(frozen)}" + ) + assert result.returncode == 0, result.stdout.decode() + result.stderr.decode() + assert "--locked" in recorded.read_text(encoding="utf-8").splitlines() + + @pytest.mark.parametrize( ("marker", "setting", "outcome"), [ diff --git a/tools/route_a/README.md b/tools/route_a/README.md index 3d5d8d70c9..fdb5abcdf2 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -78,7 +78,8 @@ first and set what its blockers name: stops rather than keep the old venv silently. A worktree synced before the marker recorded it keeps its venv whatever the setting, with a log line saying so, so an in-flight chain is not re-synced under it; remove the - marker to re-sync. + marker to re-sync. The sync drops `UV_FROZEN`: uv refuses `--locked` + beside `UV_FROZEN=1`, which a profile shell may export. - **Emitter.** `--resolve` reports the `microcosm-emitter` the release would start against the commit's `minimum_emitter_version.json`. `check_emitter.py` repeats the release's checks without importing diff --git a/tools/route_a/route_a.sh b/tools/route_a/route_a.sh index 234204a50b..99630b15ed 100755 --- a/tools/route_a/route_a.sh +++ b/tools/route_a/route_a.sh @@ -382,7 +382,9 @@ ensure_worktree() { # $1 = full sha; sets WT local marker=$WT/.venv/.route_a_synced synced if [ ! -f "$marker" ]; then log "uv sync --python $UV_SYNC_PYTHON --all-packages --locked --extra us in $WT" - (cd "$WT" && "$UV" sync --python "$UV_SYNC_PYTHON" --all-packages --locked --extra us) >>"$LOG" 2>&1 || fail "uv sync in $WT" + # uv refuses --locked beside UV_FROZEN=1, which a profile shell may export, + # so the sync drops it, as supervise.py does for the stages. + (cd "$WT" && unset UV_FROZEN && "$UV" sync --python "$UV_SYNC_PYTHON" --all-packages --locked --extra us) >>"$LOG" 2>&1 || fail "uv sync in $WT" "$WT/.venv/bin/python" -c 'import psutil, policyengine_us' >>"$LOG" 2>&1 || fail "venv in $WT lacks psutil/policyengine_us" printf '%s\npython=%s\n' "$(date '+%F %T')" "$UV_SYNC_PYTHON" > "$marker" else