From 6b67ee4aff9ac8dbeef45b77f0cd541afbd888fa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:11:17 +0400 Subject: [PATCH 01/12] Add failing tests for reusing the parent's policyengine-us lock-file check Every process that imports microcosm.build.us_runtime derives engine_abi.lock.json afresh from the installed policyengine-us (two tax-benefit system builds and an index of policyengine-us source) and compares bytes. These tests describe a record of a passed check that a process hands its children: - a passed check records the lock file's SHA-256, the installed policyengine-us version and the SHA-256 of the take-up and sources domains, bound to the issuing process ID; - a child that receives its parent's record compares those values instead of deriving the lock, and refuses a lock file, installed policyengine-us or domains that differ, or a malformed record; - a record issued by any process other than the parent is ignored, and a process with no record still runs the full check; - the base tool's step processes, the QRF workers and the QRF worker identity's import trace receive the record; - real step and QRF worker processes refuse to start when the lock file or the installed policyengine-us differs from the record, and start without importing policyengine-us when it matches. Co-Authored-By: Claude Opus 5.5 --- .../test_us_engine_abi_lock_check_record.py | 110 ++++++ ...est_spec_engine_engine_abi_check_record.py | 327 ++++++++++++++++++ .../test_us_engine_abi_lock_check_record.py | 150 ++++++++ 3 files changed, 587 insertions(+) create mode 100644 packages/microcosm-build/tests/engine_contract/us/test_us_engine_abi_lock_check_record.py create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_spec_engine_engine_abi_check_record.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_engine_abi_lock_check_record.py b/packages/microcosm-build/tests/engine_contract/us/test_us_engine_abi_lock_check_record.py new file mode 100644 index 0000000000..3ae0ffcba0 --- /dev/null +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_engine_abi_lock_check_record.py @@ -0,0 +1,110 @@ +"""With their parent's record, US base processes skip the fresh lock derivation. + +The full check of ``engine_abi.lock.json`` imports policyengine-us and builds +two tax-benefit systems. A step process or QRF worker that receives a record of +its parent's passed check compares the lock file's SHA-256, the installed +policyengine-us version and the take-up and sources domains instead, so it +starts without importing policyengine-us at all. +""" + +from __future__ import annotations + +import hashlib +import importlib.metadata +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from microcosm.build.us_runtime import take_up_contract +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") +RECORD_VARIABLE = "MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD" +US_LOCK_PATH = ( + _TEST_PATHS.package / "src" / "microcosm" / "build" / "us" / "engine_abi.lock.json" +) +BASE_TOOL = _TEST_PATHS.repository / "tools" / "build_us_puf_support_base.py" + +_PROCESS_COMMANDS = { + "step process": [str(BASE_TOOL), "--help"], + "QRF worker": ["-m", "microcosm.build.us_runtime.puf_qrf_worker", "--help"], +} + + +def _imported_modules(importtime_stderr: str) -> set[str]: + return { + line.rsplit("|", 1)[1].strip() + for line in importtime_stderr.splitlines() + if line.startswith("import time:") and "|" in line + } + + +def test_this_process_issues_a_record_of_its_us_lock_check() -> None: + environment = take_up_contract.us_engine_abi_lock_check_environment() + + record = json.loads(environment[RECORD_VARIABLE]) + assert record["issuer_pid"] == os.getpid() + assert record["lock_sha256"] == ( + hashlib.sha256(US_LOCK_PATH.read_bytes()).hexdigest() + ) + assert record["engine"] == { + "package": "policyengine-us", + "version": importlib.metadata.version("policyengine-us"), + } + + +@pytest.mark.parametrize("process", sorted(_PROCESS_COMMANDS)) +def test_a_base_process_with_its_parents_record_does_not_import_policyengine_us( + process: str, + tmp_path: Path, +) -> None: + environment = { + **os.environ, + **take_up_contract.us_engine_abi_lock_check_environment(), + } + + completed = subprocess.run( + [sys.executable, "-X", "importtime", *_PROCESS_COMMANDS[process]], + env=environment, + cwd=tmp_path, + capture_output=True, + text=True, + timeout=600, + check=False, + ) + + assert completed.returncode == 0, completed.stderr[-4000:] + imported = _imported_modules(completed.stderr) + assert "microcosm.build.us_runtime" in imported + assert "policyengine_us" not in imported + + +def test_the_full_us_bundle_loader_accepts_the_parents_record( + tmp_path: Path, +) -> None: + """The full loader compares the same take-up and sources domains.""" + + environment = { + **os.environ, + **take_up_contract.us_engine_abi_lock_check_environment(), + } + + completed = subprocess.run( + [ + sys.executable, + "-c", + "from microcosm.build.spec_engine import load_bundle\nload_bundle('us')\n", + ], + env=environment, + cwd=tmp_path, + capture_output=True, + text=True, + timeout=600, + check=False, + ) + + assert completed.returncode == 0, completed.stderr[-4000:] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_engine_abi_check_record.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_engine_abi_check_record.py new file mode 100644 index 0000000000..d39c922f02 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_engine_abi_check_record.py @@ -0,0 +1,327 @@ +"""A child process reuses its parent's lock-file check through a record. + +The full check of ``engine_abi.lock.json`` derives the lock afresh from the +installed policyengine-us and compares bytes. A process that passed it can hand +its children a record of what it compared: the lock file's SHA-256, the +installed policyengine-us version and the SHA-256 of the take-up and sources +domains. A child that receives a record from its parent compares those three +values instead of deriving the lock again, and refuses to run when any of them +differs. A process without a record from its parent still runs the full check. +""" + +# ruff: noqa: F403, F405 +import hashlib +import importlib.metadata +import os + +from microcosm.build.spec_engine.canonical import canonical_json_bytes +from test_support.microcosm_build.spec_engine_engine_abi import * + +RECORD_VARIABLE = "MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD" + + +def _write_fresh_lock(root: Path, domains: dict[str, object]) -> bytes: + lock_bytes = engine_abi_lock_bytes_from_domains(domains) + (root / "engine_abi.lock.json").write_bytes(lock_bytes) + return lock_bytes + + +def _domains_sha256(domains: dict[str, object]) -> str: + return hashlib.sha256( + canonical_json_bytes( + {"take_up": domains["take_up"], "sources": domains["sources"]} + ) + ).hexdigest() + + +def _check(root: Path, domains: dict[str, object]) -> object: + return assert_engine_abi_lock_current( + root, + domains, + schema_registry=load_schema_registry(), + ) + + +def _issued_record(root: Path) -> dict[str, object]: + environment = engine_abi_module.engine_abi_lock_check_environment(root) + assert set(environment) == {RECORD_VARIABLE} + return json.loads(environment[RECORD_VARIABLE]) + + +def _receive_record_from_parent( + monkeypatch: pytest.MonkeyPatch, + record: dict[str, object], +) -> None: + """Make this process look like the child of the record's issuer.""" + + received = {**record, "issuer_pid": os.getppid()} + monkeypatch.setenv(RECORD_VARIABLE, json.dumps(received)) + + +def _refuse_fresh_derivation(monkeypatch: pytest.MonkeyPatch) -> None: + def derivation_must_not_run(*_args: object, **_kwargs: object) -> None: + raise AssertionError("the fresh lock derivation ran despite a record") + + monkeypatch.setattr( + engine_abi_module, + "_fresh_policyengine_us_contract", + derivation_must_not_run, + ) + monkeypatch.setattr( + engine_abi_module, + "_fresh_remaining_stage_input_manifest", + derivation_must_not_run, + ) + + +def test_a_passed_check_issues_a_record_of_what_it_compared( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + domains = _fake_domains() + lock_bytes = _write_fresh_lock(tmp_path, domains) + + _check(tmp_path, domains) + record = _issued_record(tmp_path) + + assert record == { + "schema_version": 1, + "issuer_pid": os.getpid(), + "lock_sha256": hashlib.sha256(lock_bytes).hexdigest(), + "engine": {"package": "policyengine-us", "version": "1.2.3"}, + "domains_sha256": _domains_sha256(domains), + } + + +def test_no_record_is_issued_without_a_passed_check( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + assert engine_abi_module.engine_abi_lock_check_environment(tmp_path) == {} + + # Without policyengine-us the lock is only checked structurally, so there is + # no engine version to record and no record to hand on. + lock_root = tmp_path / "unattested" + lock_root.mkdir() + domains = _fake_domains() + _write_fresh_lock(lock_root, domains) + + def absent(package: str) -> str: + raise importlib.metadata.PackageNotFoundError(package) + + monkeypatch.setattr(engine_abi_module, "_installed_engine_version", absent) + _check(lock_root, domains) + assert engine_abi_module.engine_abi_lock_check_environment(lock_root) == {} + + +def test_a_record_from_the_parent_process_replaces_the_fresh_derivation( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + domains = _fake_domains() + lock_bytes = _write_fresh_lock(tmp_path, domains) + _check(tmp_path, domains) + record = _issued_record(tmp_path) + + _receive_record_from_parent(monkeypatch, record) + _refuse_fresh_derivation(monkeypatch) + + assert _check(tmp_path, domains) == json.loads(lock_bytes) + # The child hands the same comparison on to its own children. + assert _issued_record(tmp_path) == record + + +def test_a_child_refuses_a_lock_file_that_differs_from_the_parents_record( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + domains = _fake_domains() + _write_fresh_lock(tmp_path, domains) + _check(tmp_path, domains) + record = _issued_record(tmp_path) + + # A schema-valid, canonical lock that is not the one the parent checked. + replacement = engine_abi_lock_payload_from_domains(domains) + replacement["programs"]["program_00"]["default"] = False + (tmp_path / "engine_abi.lock.json").write_bytes( + canonical_json_bytes(replacement) + b"\n" + ) + _receive_record_from_parent(monkeypatch, record) + _refuse_fresh_derivation(monkeypatch) + + with pytest.raises(SpecValidationError, match="lock file differs"): + _check(tmp_path, domains) + + +def test_a_child_refuses_an_installed_engine_that_differs_from_the_parents_record( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + domains = _fake_domains() + _write_fresh_lock(tmp_path, domains) + _check(tmp_path, domains) + record = _issued_record(tmp_path) + + _receive_record_from_parent(monkeypatch, record) + _refuse_fresh_derivation(monkeypatch) + monkeypatch.setattr( + engine_abi_module, + "_installed_engine_version", + lambda package: "9.9.9", + ) + + with pytest.raises(SpecValidationError, match="installed policyengine-us"): + _check(tmp_path, domains) + + +def test_a_child_refuses_when_policyengine_us_is_missing_but_the_parent_had_it( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + domains = _fake_domains() + _write_fresh_lock(tmp_path, domains) + _check(tmp_path, domains) + record = _issued_record(tmp_path) + + _receive_record_from_parent(monkeypatch, record) + _refuse_fresh_derivation(monkeypatch) + + def absent(package: str) -> str: + raise importlib.metadata.PackageNotFoundError(package) + + monkeypatch.setattr(engine_abi_module, "_installed_engine_version", absent) + + with pytest.raises(SpecValidationError, match="installed policyengine-us"): + _check(tmp_path, domains) + + +@pytest.mark.parametrize("changed_domain", ["take_up", "sources"]) +def test_a_child_refuses_domains_that_differ_from_the_parents_record( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, + changed_domain: str, +) -> None: + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + domains = _fake_domains() + _write_fresh_lock(tmp_path, domains) + _check(tmp_path, domains) + record = _issued_record(tmp_path) + + changed = copy.deepcopy(domains) + changed[changed_domain]["edited_after_the_parent_checked"] = True + _receive_record_from_parent(monkeypatch, record) + _refuse_fresh_derivation(monkeypatch) + + with pytest.raises(SpecValidationError, match="take-up and sources domains"): + _check(tmp_path, changed) + + +@pytest.mark.parametrize( + "raw_record", + [ + "not json", + json.dumps([]), + json.dumps({"schema_version": 2}), + "with an unexpected field", + "with a malformed digest", + ], +) +def test_a_child_refuses_a_malformed_record( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, + raw_record: str, +) -> None: + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + domains = _fake_domains() + _write_fresh_lock(tmp_path, domains) + _check(tmp_path, domains) + record = {**_issued_record(tmp_path), "issuer_pid": os.getppid()} + if raw_record == "with an unexpected field": + raw_record = json.dumps({**record, "skip": True}) + elif raw_record == "with a malformed digest": + raw_record = json.dumps({**record, "lock_sha256": "ABC"}) + monkeypatch.setenv(RECORD_VARIABLE, raw_record) + _refuse_fresh_derivation(monkeypatch) + + with pytest.raises(SpecValidationError, match="malformed"): + _check(tmp_path, domains) + + +def test_a_record_issued_by_another_process_is_ignored( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A record inherited from further up the process tree is not a parent's. + + Such a process runs the full check, so a stale lock is still refused. + """ + + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + domains = _fake_domains() + _write_fresh_lock(tmp_path, domains) + _check(tmp_path, domains) + record = _issued_record(tmp_path) + # This process issued the record itself, so it is not its own parent. + assert record["issuer_pid"] != os.getppid() + monkeypatch.setenv(RECORD_VARIABLE, json.dumps(record)) + + derivations: list[object] = [] + + def counted_contract() -> dict[str, dict[str, object]]: + derivations.append(None) + return _fake_engine_contract() + + monkeypatch.setattr( + engine_abi_module, + "_fresh_policyengine_us_contract", + counted_contract, + ) + _check(tmp_path, domains) + assert len(derivations) == 1 + + stale = engine_abi_lock_payload_from_domains(domains) + stale["programs"]["program_00"]["default"] = False + (tmp_path / "engine_abi.lock.json").write_bytes(canonical_json_bytes(stale) + b"\n") + with pytest.raises(SpecValidationError, match="stale or non-canonical"): + _check(tmp_path, domains) + + +def test_without_a_record_the_full_check_runs( + tmp_path: Path, + fake_fresh_engine: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + domains = _fake_domains() + _write_fresh_lock(tmp_path, domains) + derivations: list[object] = [] + + def counted_contract() -> dict[str, dict[str, object]]: + derivations.append(None) + return _fake_engine_contract() + + monkeypatch.setattr( + engine_abi_module, + "_fresh_policyengine_us_contract", + counted_contract, + ) + + _check(tmp_path, domains) + _check(tmp_path, domains) + + assert len(derivations) == 2 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py b/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py new file mode 100644 index 0000000000..3e99f303bb --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py @@ -0,0 +1,150 @@ +"""US base processes reuse their parent's check of ``engine_abi.lock.json``. + +``--stage all`` checks the policyengine-us lock file once and passes each step +process a record of that check. A step process passes the record on to the QRF +workers that ``primary_qrf_chain`` starts and to the clean import trace behind +the QRF worker identity. A step process or QRF worker refuses to start when the +lock file or the installed policyengine-us differs from its parent's record. +""" + +from __future__ import annotations + +import hashlib +import importlib.metadata +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from microcosm.build.us_runtime import take_up_contract, worker_identity +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") +RECORD_VARIABLE = "MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD" +US_LOCK_PATH = ( + _TEST_PATHS.package / "src" / "microcosm" / "build" / "us" / "engine_abi.lock.json" +) +BASE_TOOL = _TEST_PATHS.repository / "tools" / "build_us_puf_support_base.py" + + +def _load_support_builder_module(): + spec = importlib.util.spec_from_file_location( + "build_us_puf_support_base", BASE_TOOL + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +def _stub_record_environment(monkeypatch: pytest.MonkeyPatch) -> dict[str, str]: + environment = {RECORD_VARIABLE: '{"stub": "record of this process"}'} + monkeypatch.setattr( + take_up_contract, + "us_engine_abi_lock_check_environment", + lambda: dict(environment), + ) + return environment + + +def test_staged_step_processes_receive_this_processes_lock_check_record( + monkeypatch: pytest.MonkeyPatch, +) -> None: + builder = _load_support_builder_module() + monkeypatch.delenv(RECORD_VARIABLE, raising=False) + expected = _stub_record_environment(monkeypatch) + + environment = builder._staged_subprocess_environment() + + assert environment[RECORD_VARIABLE] == expected[RECORD_VARIABLE] + + +def test_qrf_workers_and_the_import_trace_receive_the_lock_check_record( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """One launch environment serves the QRF workers and the identity trace. + + Both therefore check the lock file the same way, so the worker identity + does not depend on whether the process computing it received a record. + """ + + expected = _stub_record_environment(monkeypatch) + + with worker_identity.primary_qrf_worker_launch_environment() as environment: + assert environment[RECORD_VARIABLE] == expected[RECORD_VARIABLE] + + +def _installed_policyengine_us_version() -> str: + try: + return importlib.metadata.version("policyengine-us") + except importlib.metadata.PackageNotFoundError: + return "not installed" + + +def _record_from_this_process(*, lock_sha256: str, engine_version: str) -> str: + return json.dumps( + { + "schema_version": 1, + "issuer_pid": os.getpid(), + "lock_sha256": lock_sha256, + "engine": {"package": "policyengine-us", "version": engine_version}, + "domains_sha256": "0" * 64, + } + ) + + +_PROCESS_COMMANDS = { + "step process": [sys.executable, str(BASE_TOOL), "--help"], + "QRF worker": [ + sys.executable, + "-m", + "microcosm.build.us_runtime.puf_qrf_worker", + "--help", + ], +} + + +@pytest.mark.parametrize("process", sorted(_PROCESS_COMMANDS)) +@pytest.mark.parametrize( + ("difference", "refusal"), + [ + ("lock file", "lock file differs"), + ("installed policyengine-us", "installed policyengine-us"), + ], +) +def test_a_base_process_refuses_to_start_when_its_parents_check_no_longer_holds( + process: str, + difference: str, + refusal: str, + tmp_path: Path, +) -> None: + lock_sha256 = hashlib.sha256(US_LOCK_PATH.read_bytes()).hexdigest() + engine_version = _installed_policyengine_us_version() + if difference == "lock file": + lock_sha256 = hashlib.sha256(b"a lock file the parent checked").hexdigest() + else: + engine_version = "0.0.0+checked-by-the-parent" + environment = { + **os.environ, + RECORD_VARIABLE: _record_from_this_process( + lock_sha256=lock_sha256, + engine_version=engine_version, + ), + } + + completed = subprocess.run( + _PROCESS_COMMANDS[process], + env=environment, + cwd=tmp_path, + capture_output=True, + text=True, + timeout=600, + check=False, + ) + + assert completed.returncode != 0, completed.stdout + assert refusal in completed.stderr, completed.stderr[-4000:] From e579dec36d737c65002a705470ca239c908fcde3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:26:45 +0400 Subject: [PATCH 02/12] Check the policyengine-us lock file once per base run and hand children a record A process that passes the full check of engine_abi.lock.json now remembers what it compared: the lock file's SHA-256, the installed policyengine-us version and the SHA-256 of the take-up and sources domains. engine_abi_lock_check_environment() hands that record, bound to the issuing process ID, to the processes it starts through MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD. A process holding a record issued by its own parent reads the lock file and compares the three values instead of deriving the lock afresh (two tax-benefit system builds and an index of policyengine-us source). It refuses to run when the lock file, the installed policyengine-us or the domains differ, or the record is malformed. A process with no record, or one issued by any other process, runs the full check as before. The base tool's --stage all process passes its record to each step process. primary_qrf_worker_launch_environment() passes the calling process's record to the QRF workers and to the clean import trace behind the QRF worker identity, so that trace opens the same files however the process computing the identity was started. The identity digest changes once: the trace no longer opens gate_shadow.py, multispine_pool.py or us_late_overlap_ownership.py. Measured on a 10-core Mac at load average 5-6, median of 3 starts: a step process start fell from 37.8 s and 1.54 GB peak RSS to 9.0 s and 0.47 GB, and a QRF worker start from 36.6 s and 1.75 GB to 9.1 s and 0.46 GB. Co-Authored-By: Claude Opus 5.5 --- .../us-base-engine-lock-check-once.changed.md | 1 + docs/spec-engine.md | 10 +- .../src/microcosm/build/country_spec.py | 19 ++ .../microcosm/build/spec_engine/engine_abi.py | 267 ++++++++++++++++-- .../build/us_runtime/take_up_contract.py | 19 ++ .../build/us_runtime/worker_identity.py | 13 + tools/build_us_puf_support_base.py | 7 + 7 files changed, 308 insertions(+), 28 deletions(-) create mode 100644 changelog.d/us-base-engine-lock-check-once.changed.md diff --git a/changelog.d/us-base-engine-lock-check-once.changed.md b/changelog.d/us-base-engine-lock-check-once.changed.md new file mode 100644 index 0000000000..927b43abfd --- /dev/null +++ b/changelog.d/us-base-engine-lock-check-once.changed.md @@ -0,0 +1 @@ +The US base stage checks the policyengine-us lock file (`engine_abi.lock.json`) once in the `--stage all` process instead of in every step process and QRF worker. The parent hands each step process a record of its check (lock file SHA-256, installed policyengine-us version and take-up and sources domain digest, in `MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD`), which the step process passes on to its QRF workers; a child with its parent's record compares those three values instead of building two tax-benefit systems, and refuses to run when any differs. Processes without a record from their parent still run the full check. The QRF worker identity digest changes once, because its import trace now opens three fewer files. diff --git a/docs/spec-engine.md b/docs/spec-engine.md index 33da8b2e36..f50f32af0f 100644 --- a/docs/spec-engine.md +++ b/docs/spec-engine.md @@ -411,7 +411,15 @@ final_owner_stage: … compilation; engine bumps fail closed until the lock is regenerated and every bundle-owned treatment re-reviewed. The engine owns its facts; the bundle owns treatments and pipelines; neither derives from - the other at build time. + the other at build time. A process that passed the full comparison can + pass the processes it starts a record of it in + `MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD` (the lock file's SHA-256, the + installed policyengine-us version and a digest of the take-up and + sources domains, bound to the issuing process ID). A direct child + compares those three values instead of deriving the lock again and + refuses to run when any differs; the US base stage's `--stage all` + process does this for its step processes, which pass it on to their QRF + workers. - Column/entity mapping comes from the ABI projection with a **total-and-injective assertion** (the suffix naming rule died on `takes_up_eitc`/`takes_up_dc_ptc`). diff --git a/packages/microcosm-build/src/microcosm/build/country_spec.py b/packages/microcosm-build/src/microcosm/build/country_spec.py index 26cf98a6b0..7a2caceb77 100644 --- a/packages/microcosm-build/src/microcosm/build/country_spec.py +++ b/packages/microcosm-build/src/microcosm/build/country_spec.py @@ -76,6 +76,7 @@ "ResolvedCountrySpec", "country_resource", "country_stage_plan", + "country_engine_abi_lock_check_environment", "load_country_take_up_contract_projection", "load_country_spec", "load_gates_manifest", @@ -2057,6 +2058,24 @@ def _select_take_up_compatibility_payload( return projection +def country_engine_abi_lock_check_environment(country: str) -> dict[str, str]: + """Hand this process's check of a country's lock file to a child process. + + The result holds the record of the check of the packaged + ``engine_abi.lock.json`` (the package directory that + :func:`load_country_take_up_contract_projection` reads) that this process + passed, or is empty when no attested check passed here; see + :func:`microcosm.build.spec_engine.engine_abi.engine_abi_lock_check_environment`. + """ + + from microcosm.build.spec_engine.engine_abi import ( + engine_abi_lock_check_environment, + ) + + root = Path(str(importlib_resources.files("microcosm.build").joinpath(country))) + return engine_abi_lock_check_environment(root) + + def load_country_take_up_contract_projection( country: str | Path, ) -> Mapping[str, Any] | None: diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py b/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py index 76bafd8b0b..38a25b7ffd 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py @@ -4,6 +4,12 @@ facts those treatments consume. This module joins those authorities only to emit and verify ``engine_abi.lock.json``. The generated lock is the one exact runtime/source pin: vintage rows index its version rather than copying it. + +Deriving the lock imports policyengine-us, builds two tax-benefit systems and +indexes policyengine-us's source code. A process that passed the full check can +hand the build processes it starts a record of what it compared +(:func:`engine_abi_lock_check_environment`); a child with its parent's record +compares those values instead of deriving the lock again. """ from __future__ import annotations @@ -11,9 +17,11 @@ import hashlib import importlib.metadata import json +import os from collections.abc import Mapping from contextlib import contextmanager from contextvars import ContextVar +from dataclasses import dataclass from pathlib import Path, PurePosixPath from typing import TYPE_CHECKING @@ -41,6 +49,47 @@ _ACTIVE_TAKE_UP_MANIFEST_PROGRAM_BINDINGS: ContextVar[ tuple[tuple[str, str, str], ...] | None ] = ContextVar("active_take_up_manifest_program_bindings", default=None) +#: The environment variable through which a process that passed the lock check +#: hands a record of that check to the build processes it starts. +ENGINE_ABI_LOCK_CHECK_RECORD_VARIABLE = "MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD" +_LOCK_CHECK_RECORD_SCHEMA_VERSION = 1 +_LOCK_CHECK_RECORD_KEYS = frozenset( + {"schema_version", "issuer_pid", "lock_sha256", "engine", "domains_sha256"} +) +_SHA256_HEX_DIGITS = frozenset("0123456789abcdef") + + +@dataclass(frozen=True) +class _LockCheckInputs: + """What one passed lock check compared, which a child process must match. + + Besides microcosm's own code, the fresh derivation reads only the installed + policyengine-us and the bundle's typed take-up and sources domains. + Microcosm's code is not recorded: a record reaches only the issuing + process's direct children, which run the same checkout within the same run. + A source edit during a base run is the base stage's run-config check to + catch (its builder code digest), not this record's. + """ + + lock_sha256: str + engine_version: str + domains_sha256: str + + def record(self, *, issuer_pid: int) -> dict[str, object]: + return { + "schema_version": _LOCK_CHECK_RECORD_SCHEMA_VERSION, + "issuer_pid": issuer_pid, + "lock_sha256": self.lock_sha256, + "engine": { + "package": POLICYENGINE_US_PACKAGE, + "version": self.engine_version, + }, + "domains_sha256": self.domains_sha256, + } + + +#: Lock files this process has checked, by path, with what each check compared. +_PASSED_LOCK_CHECKS: dict[str, _LockCheckInputs] = {} def active_take_up_manifest_program_bindings() -> ( @@ -417,6 +466,12 @@ def assert_engine_abi_lock_current( Bundles without typed take-up do not need an ABI lock. A lock with no take-up surface is refused because it has no bundle mapping to attest. + + A process whose parent passed this check for the same lock and handed it a + record (:func:`engine_abi_lock_check_environment`) compares the lock file's + SHA-256, the installed policyengine-us version and the take-up and sources + domains with that record instead of deriving the lock again, and refuses + to run when any of them differs. """ take_up = domains.get("take_up") @@ -428,45 +483,82 @@ def assert_engine_abi_lock_current( ) return None + parent_check = _parent_lock_check() + if parent_check is not None: + parsed = _lock_matching_parent_check( + lock_resource, + domains, + parent_check, + schema_registry=schema_registry, + ) + _PASSED_LOCK_CHECKS[str(lock_resource)] = parent_check + return parsed + try: expected_payload = engine_abi_lock_payload_from_domains(domains) except importlib.metadata.PackageNotFoundError: + expected_payload = None + if expected_payload is None: # The engine distribution is absent, so currency is unattestable in # this environment (e.g. the wheels gate's engine-less venv). The # committed lock is still validated structurally — present, schema- # valid, canonical UTF-8 JSON in canonical byte form — and returned # unattested. Every environment that regenerates the lock or builds # against engine facts installs the engine and takes the attested - # path above, which stays fail-closed on any drift. - if not lock_resource.is_file(): - raise SpecValidationError( - "engine_abi.lock.json is required for a bundle with a " - "policy-engine ABI" - ) from None - try: - raw = lock_resource.read_bytes() - except OSError as error: - raise SpecValidationError( - f"unable to read generated lock: {error}", - source=ENGINE_ABI_LOCK_FILENAME, - ) from error - try: - parsed = json.loads(raw) - except (UnicodeDecodeError, json.JSONDecodeError) as error: - raise SpecValidationError( - "generated lock is not canonical UTF-8 JSON", - source=ENGINE_ABI_LOCK_FILENAME, - ) from error - schema_registry.validate(parsed, ENGINE_ABI_LOCK_SCHEMA_ID) + # path below, which stays fail-closed on any drift. + raw, parsed = _read_schema_valid_lock(lock_resource, schema_registry) if raw != canonical_json_bytes(parsed) + b"\n": raise SpecValidationError( "generated lock is not in canonical byte form", source=ENGINE_ABI_LOCK_FILENAME, - ) from None - assert isinstance(parsed, Mapping) + ) return parsed schema_registry.validate(expected_payload, ENGINE_ABI_LOCK_SCHEMA_ID) expected_bytes = canonical_json_bytes(expected_payload) + b"\n" + raw, parsed = _read_schema_valid_lock(lock_resource, schema_registry) + if raw != expected_bytes: + raise SpecValidationError( + "generated lock is stale or non-canonical; regenerate it from the " + "fresh installed engine ABI", + source=ENGINE_ABI_LOCK_FILENAME, + ) + engine = _require_mapping(expected_payload["engine"], location="engine") + _PASSED_LOCK_CHECKS[str(lock_resource)] = _LockCheckInputs( + lock_sha256=hashlib.sha256(raw).hexdigest(), + engine_version=str(engine["version"]), + domains_sha256=_lock_check_domains_sha256(domains), + ) + return parsed + + +def engine_abi_lock_check_environment(root: Traversable | Path) -> dict[str, str]: + """Environment entries that hand this process's lock check to a child. + + Returns the record of the check this process passed for ``root``'s lock + file (fully, or by matching its own parent's record), bound to this + process's ID, or nothing when no such check passed here. A child honours + the record only when its parent process issued it, so a record inherited + from further up the process tree is ignored and that child runs the full + check. + """ + + lock_resource = root.joinpath(*PurePosixPath(ENGINE_ABI_LOCK_FILENAME).parts) + passed = _PASSED_LOCK_CHECKS.get(str(lock_resource)) + if passed is None: + return {} + return { + ENGINE_ABI_LOCK_CHECK_RECORD_VARIABLE: json.dumps( + passed.record(issuer_pid=os.getpid()), + sort_keys=True, + separators=(",", ":"), + ) + } + + +def _read_schema_valid_lock( + lock_resource: Traversable | Path, + schema_registry: SchemaRegistry, +) -> tuple[bytes, Mapping[str, object]]: if not lock_resource.is_file(): raise SpecValidationError( "engine_abi.lock.json is required for a bundle with a policy-engine ABI" @@ -486,21 +578,142 @@ def assert_engine_abi_lock_current( source=ENGINE_ABI_LOCK_FILENAME, ) from error schema_registry.validate(parsed, ENGINE_ABI_LOCK_SCHEMA_ID) - if raw != expected_bytes: + assert isinstance(parsed, Mapping) + return raw, parsed + + +def _lock_check_domains_sha256(domains: Mapping[str, object]) -> str: + """Digest the two bundle domains the fresh lock derivation reads.""" + + take_up = _require_mapping(domains.get("take_up"), location="take_up") + sources = _require_mapping(domains.get("sources"), location="sources") + return hashlib.sha256( + canonical_json_bytes({"take_up": take_up, "sources": sources}) + ).hexdigest() + + +def _is_sha256_hex(value: object) -> bool: + return ( + isinstance(value, str) and len(value) == 64 and set(value) <= _SHA256_HEX_DIGITS + ) + + +def _parent_lock_check() -> _LockCheckInputs | None: + """Read the lock check record this process's parent handed it, if any.""" + + raw = os.environ.get(ENGINE_ABI_LOCK_CHECK_RECORD_VARIABLE) + if raw is None: + return None + + def malformed(reason: str) -> SpecValidationError: + return SpecValidationError( + f"{ENGINE_ABI_LOCK_CHECK_RECORD_VARIABLE} holds a malformed lock " + f"check record: {reason}; refusing to run", + source=ENGINE_ABI_LOCK_FILENAME, + ) + + try: + record = json.loads(raw) + except json.JSONDecodeError as error: + raise malformed("it is not JSON") from error + if not isinstance(record, dict) or set(record) != _LOCK_CHECK_RECORD_KEYS: + raise malformed( + f"it must be an object with keys {sorted(_LOCK_CHECK_RECORD_KEYS)}" + ) + if record["schema_version"] != _LOCK_CHECK_RECORD_SCHEMA_VERSION: + raise malformed(f"schema_version {record['schema_version']!r} is not 1") + issuer_pid = record["issuer_pid"] + if ( + isinstance(issuer_pid, bool) + or not isinstance(issuer_pid, int) + or issuer_pid < 1 + ): + raise malformed("issuer_pid must be a positive process ID") + for field in ("lock_sha256", "domains_sha256"): + if not _is_sha256_hex(record[field]): + raise malformed(f"{field} must be a lowercase SHA-256 hex digest") + engine = record["engine"] + if ( + not isinstance(engine, dict) + or set(engine) != {"package", "version"} + or engine["package"] != POLICYENGINE_US_PACKAGE + or not isinstance(engine["version"], str) + or not engine["version"] + ): + raise malformed( + f"engine must name package {POLICYENGINE_US_PACKAGE!r} and a version" + ) + if issuer_pid != os.getppid(): + # Issued further up the process tree, not by this process's parent. + return None + return _LockCheckInputs( + lock_sha256=record["lock_sha256"], + engine_version=engine["version"], + domains_sha256=record["domains_sha256"], + ) + + +def _lock_matching_parent_check( + lock_resource: Traversable | Path, + domains: Mapping[str, object], + parent_check: _LockCheckInputs, + *, + schema_registry: SchemaRegistry, +) -> Mapping[str, object]: + """Return the lock if it and its inputs are those the parent checked.""" + + raw, parsed = _read_schema_valid_lock(lock_resource, schema_registry) + observed_lock_sha256 = hashlib.sha256(raw).hexdigest() + if observed_lock_sha256 != parent_check.lock_sha256: raise SpecValidationError( - "generated lock is stale or non-canonical; regenerate it from the " - "fresh installed engine ABI", + "engine_abi.lock.json: the lock file differs from the one the parent " + f"process checked (SHA-256 {observed_lock_sha256}, parent checked " + f"{parent_check.lock_sha256}); refusing to run", + source=ENGINE_ABI_LOCK_FILENAME, + ) + try: + installed_version: str | None = _installed_engine_version( + POLICYENGINE_US_PACKAGE + ) + except importlib.metadata.PackageNotFoundError: + installed_version = None + if installed_version != parent_check.engine_version: + observed = "not installed" if installed_version is None else installed_version + raise SpecValidationError( + "engine_abi.lock.json: the installed policyengine-us differs from " + "the one the parent process checked the lock file against " + f"({observed}, parent checked {parent_check.engine_version}); " + "refusing to run", + source=ENGINE_ABI_LOCK_FILENAME, + ) + observed_domains_sha256 = _lock_check_domains_sha256(domains) + if observed_domains_sha256 != parent_check.domains_sha256: + raise SpecValidationError( + "engine_abi.lock.json: the take-up and sources domains differ from " + "those the parent process checked the lock file against (SHA-256 " + f"{observed_domains_sha256}, parent checked " + f"{parent_check.domains_sha256}); refusing to run", + source=ENGINE_ABI_LOCK_FILENAME, + ) + if parsed.get("engine") != { + "package": POLICYENGINE_US_PACKAGE, + "version": parent_check.engine_version, + }: + raise SpecValidationError( + "engine_abi.lock.json: the lock file does not name the policyengine-us " + "version the parent process checked it against; refusing to run", source=ENGINE_ABI_LOCK_FILENAME, ) - assert isinstance(parsed, Mapping) return parsed __all__ = [ + "ENGINE_ABI_LOCK_CHECK_RECORD_VARIABLE", "ENGINE_ABI_LOCK_FILENAME", "ENGINE_ABI_LOCK_SCHEMA_ID", "assert_engine_abi_lock_current", "emit_engine_abi_lock", + "engine_abi_lock_check_environment", "engine_abi_lock_bytes", "engine_abi_lock_bytes_from_domains", "engine_abi_lock_payload", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/take_up_contract.py b/packages/microcosm-build/src/microcosm/build/us_runtime/take_up_contract.py index 190aadf510..72e308a099 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/take_up_contract.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/take_up_contract.py @@ -42,6 +42,7 @@ "load_take_up_contract", "seeded_take_up_programs", "take_up_contract_identity", + "us_engine_abi_lock_check_environment", ] #: Engine-derived fields on each program entry that a test asserts against the @@ -231,6 +232,24 @@ def load_take_up_contract() -> TakeUpContract: return _parse_take_up_contract(projection) +def us_engine_abi_lock_check_environment() -> dict[str, str]: + """Environment entries that let a child reuse this process's US lock check. + + Loading the take-up contract checks ``engine_abi.lock.json`` once per + process. A process passes these entries to the base step processes and QRF + workers it starts; each compares the lock file's SHA-256, the installed + policyengine-us version and the take-up and sources domains with this + process's check instead of deriving the lock again, and refuses to run when + any of them differs. Empty where no attested check ran (policyengine-us is + not installed); a child then checks the lock file itself. + """ + + from microcosm.build.country_spec import country_engine_abi_lock_check_environment + + load_take_up_contract() + return country_engine_abi_lock_check_environment("us") + + def take_up_contract_identity( contract: TakeUpContract | None = None, ) -> dict[str, object]: diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py b/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py index 19f7354dd4..cbb40ad90b 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/worker_identity.py @@ -494,12 +494,25 @@ def primary_qrf_worker_launch_environment() -> Iterator[dict[str, str]]: Disabling writes alone still allows Python to execute existing bytecode. A fresh, empty cache prefix prevents source-tree or inherited-prefix caches from being read, while the semantic identity binds only its placeholder. + + Both also receive this process's record of its policyengine-us lock-file + check, so both compare the lock with that record instead of deriving it + again. The clean import trace therefore opens the same files whether or + not this process itself received a record from its parent, and the + identity does not depend on how the process computing it was started. The + record's value is not part of the identity. """ + from microcosm.build.us_runtime.take_up_contract import ( + us_engine_abi_lock_check_environment, + ) + + lock_check = us_engine_abi_lock_check_environment() with TemporaryDirectory(prefix="microcosm-qrf-pycache-") as cache_prefix: yield { **_WORKER_ENVIRONMENT_OVERRIDES, "PYTHONPYCACHEPREFIX": str(Path(cache_prefix).absolute()), + **lock_check, } diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index 22f21c0672..973c0b97e5 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -1240,8 +1240,15 @@ def _append_path_argument(command: list[str], flag: str, value: Path | None) -> def _staged_subprocess_environment() -> dict[str, str]: + from microcosm.build.us_runtime.take_up_contract import ( + us_engine_abi_lock_check_environment, + ) + environment = os.environ.copy() environment.setdefault("PYTHONHASHSEED", "0") + # Each child compares the policyengine-us lock file and engine version with + # this process's check instead of deriving the lock again. + environment.update(us_engine_abi_lock_check_environment()) # The child starts no emitter: this process records its telemetry. return child_stage_environment(environment) From 56bf1eb5879176c56d7e760fc8f94e100c371c8b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:46:35 +0400 Subject: [PATCH 03/12] Add a failing test that QRF workers get the record from their own parent run_primary_puf_qrf_chain starts the QRF workers from the step process. When its caller passes no environment, as the base tool's primary_qrf_chain step does, each worker only inherits the step process's environment, whose record was issued by the --stage all process. The worker's parent is the step process, so it ignores that record and still derives the lock afresh. The test requires every worker the chain starts to receive the record of the step process's own check, with or without a caller environment. Co-Authored-By: Claude Opus 5.5 --- .../test_us_engine_abi_lock_check_record.py | 55 ++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py b/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py index 3e99f303bb..352be27481 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py @@ -20,7 +20,7 @@ import pytest -from microcosm.build.us_runtime import take_up_contract, worker_identity +from microcosm.build.us_runtime import puf_qrf_chain, take_up_contract, worker_identity from test_support.paths import paths_for _TEST_PATHS = paths_for("microcosm-build") @@ -78,6 +78,59 @@ def test_qrf_workers_and_the_import_trace_receive_the_lock_check_record( assert environment[RECORD_VARIABLE] == expected[RECORD_VARIABLE] +@pytest.mark.parametrize( + "caller_environment", + [None, {"POPULACE_FIT_N_JOBS": "1"}], + ids=["base tool passes no environment", "caller passes an environment"], +) +def test_qrf_workers_started_by_the_chain_receive_this_processes_record( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + caller_environment: dict[str, str] | None, +) -> None: + """The step process issues the record each of its QRF workers receives. + + A record that the worker merely inherits was issued by the step process's + own parent, so the worker would ignore it and run the full check. + """ + + monkeypatch.setenv(RECORD_VARIABLE, '{"stub": "record of the parent"}') + expected = _stub_record_environment(monkeypatch) + monkeypatch.setattr( + puf_qrf_chain, "_load_manifest", lambda root: {"initial_state": {}} + ) + monkeypatch.setattr( + puf_qrf_chain, "_manifest_strings", lambda manifest, key: ["first_target"] + ) + monkeypatch.setattr( + puf_qrf_chain.QRFChainState, "from_dict", staticmethod(lambda value: None) + ) + monkeypatch.setattr( + puf_qrf_chain, + "_target_path", + lambda root, manifest, index: tmp_path / "not-yet-written", + ) + launched: list[dict[str, str]] = [] + + def stopped_worker( + command: list[str], *, env: dict[str, str], check: bool + ) -> subprocess.CompletedProcess[str]: + launched.append(env) + return subprocess.CompletedProcess(command, 1) + + monkeypatch.setattr(puf_qrf_chain.subprocess, "run", stopped_worker) + + with pytest.raises(RuntimeError, match="failed with exit code 1"): + puf_qrf_chain.run_primary_puf_qrf_chain( + tmp_path, environment=caller_environment + ) + + assert len(launched) == 1 + assert launched[0][RECORD_VARIABLE] == expected[RECORD_VARIABLE] + for name, value in (caller_environment or {}).items(): + assert launched[0][name] == value + + def _installed_policyengine_us_version() -> str: try: return importlib.metadata.version("policyengine-us") From f9f4c68743019803c4d6f75c3dea2dc0871ae758 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:50:04 +0400 Subject: [PATCH 04/12] Hand each QRF worker the record of the step process's own lock check run_primary_puf_qrf_chain now adds us_engine_abi_lock_check_environment() to every worker's environment, whether or not its caller passes an environment. The base tool's primary_qrf_chain step passes none, so its workers previously inherited only the --stage all process's record, which they ignore because their parent is the step process, and each one derived the lock afresh. tools/build_us_multispine_pool.py calls the chain the same way and gains the same. Co-Authored-By: Claude Opus 5.5 --- .../microcosm/build/us_runtime/puf_qrf_chain.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/puf_qrf_chain.py b/packages/microcosm-build/src/microcosm/build/us_runtime/puf_qrf_chain.py index 174fc4991a..82abb1a074 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/puf_qrf_chain.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/puf_qrf_chain.py @@ -279,9 +279,19 @@ def run_primary_puf_qrf_chain( "Primary QRF checkpoints have a non-contiguous prefix: " f"target {first_gap} is missing but later target(s) {later} exist." ) - child_environment = None - if environment is not None: - child_environment = {**os.environ, **dict(environment)} + from microcosm.build.us_runtime.take_up_contract import ( + us_engine_abi_lock_check_environment, + ) + + # Each worker compares the policyengine-us lock file and engine version + # with this process's check instead of deriving the lock again. An + # inherited record was issued by this process's parent, which a worker + # would ignore. + child_environment = { + **os.environ, + **({} if environment is None else dict(environment)), + **us_engine_abi_lock_check_environment(), + } for target_index, _target in enumerate(target_order): target_path = _target_path(root, manifest, target_index) if target_path.exists(): From da07ae5ea65206d866906355b00334ce2578ad03 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:53:13 +0400 Subject: [PATCH 05/12] Add failing tests that base processes import torch only where it is used Importing microcosm.calibrate imports microcosm.calibrate.solve, whose module-level `import torch` (and its import of HardConcrete from gates) loads torch in every US base step process and QRF worker, about 1.4 s and 100-200 MB each, although none of them calibrates. The tests require that importing the calibration package, or starting a base step process or QRF worker, does not import torch, and that a solver function that uses torch imports it on first use. Co-Authored-By: Claude Opus 5.5 --- .../test_us_engine_abi_lock_check_record.py | 35 +++++++++++ .../shared/test_solve_torch_import.py | 60 +++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 packages/microcosm-calibrate/tests/engine_free/shared/test_solve_torch_import.py diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py b/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py index 352be27481..4b379fea21 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py @@ -201,3 +201,38 @@ def test_a_base_process_refuses_to_start_when_its_parents_check_no_longer_holds( assert completed.returncode != 0, completed.stdout assert refusal in completed.stderr, completed.stderr[-4000:] + + +@pytest.mark.parametrize("process", sorted(_PROCESS_COMMANDS)) +def test_a_base_process_start_does_not_import_torch( + process: str, + tmp_path: Path, +) -> None: + """Torch is imported only by the calibration functions that use it.""" + + environment = { + **{ + name: value for name, value in os.environ.items() if name != RECORD_VARIABLE + }, + **take_up_contract.us_engine_abi_lock_check_environment(), + } + command = _PROCESS_COMMANDS[process] + + completed = subprocess.run( + [command[0], "-X", "importtime", *command[1:]], + env=environment, + cwd=tmp_path, + capture_output=True, + text=True, + timeout=600, + check=False, + ) + + assert completed.returncode == 0, completed.stderr[-4000:] + imported = { + line.rsplit("|", 1)[1].strip() + for line in completed.stderr.splitlines() + if line.startswith("import time:") and "|" in line + } + assert "microcosm.calibrate" in imported + assert "torch" not in imported diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_solve_torch_import.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_solve_torch_import.py new file mode 100644 index 0000000000..5cf97b69ef --- /dev/null +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_solve_torch_import.py @@ -0,0 +1,60 @@ +"""Importing the calibration package does not import torch. + +Torch is imported by the solver functions that use it, so a process that only +imports ``microcosm.calibrate`` (every US base step process and QRF worker +does, through ``microcosm.build``) does not pay for importing it. +""" + +from __future__ import annotations + +import subprocess +import sys + +_IMPORT_PROBE = """ +import sys + +import microcosm.calibrate +import microcosm.calibrate.solve + +print(sorted(name for name in ("torch", "microcosm.calibrate.gates") if name in sys.modules)) +""" + + +def test_importing_the_calibration_package_does_not_import_torch() -> None: + completed = subprocess.run( + [sys.executable, "-c", _IMPORT_PROBE], + capture_output=True, + text=True, + timeout=300, + check=False, + ) + + assert completed.returncode == 0, completed.stderr[-4000:] + assert completed.stdout.strip() == "[]" + + +_FIRST_USE_PROBE = """ +import sys + +import numpy as np +from scipy import sparse + +from microcosm.calibrate import solve + +assert "torch" not in sys.modules +matrix = solve._torch_constraint_matrix(sparse.csr_matrix(np.eye(2))) +print(type(matrix).__module__, type(matrix).__name__, "torch" in sys.modules) +""" + + +def test_a_solver_function_imports_torch_on_first_use() -> None: + completed = subprocess.run( + [sys.executable, "-c", _FIRST_USE_PROBE], + capture_output=True, + text=True, + timeout=300, + check=False, + ) + + assert completed.returncode == 0, completed.stderr[-4000:] + assert completed.stdout.strip() == "torch Tensor True" From 38fc6a2a37ac140556f635531601d0d223def255 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:17:21 +0400 Subject: [PATCH 06/12] Import torch only in the solver functions that use it microcosm.calibrate.solve imported torch, and HardConcrete from microcosm.calibrate.gates, at module level. Every importer of microcosm.calibrate therefore loaded torch, including each US base step process and QRF worker, none of which calibrates. The twelve solve functions that use torch at run time now import it themselves, and _optimize imports HardConcrete; annotations keep their TYPE_CHECKING imports. No computation changes: the pre-change optimizer comparisons in test_l2_basis.py and test_solve.py still return identical bytes. solve.py and puf_qrf_chain.py are among the sources whose digest the spec engine's legacy-v1 seed protocol records (it is recorded, not used to draw), so these move, re-pinned with tools/repin_us_spec_engine_contracts.py: - EXPECTED_HASHES seed_map and seed_protocol in inventory_coverage.py; - docs/evidence/spec-engine/us-f0-coverage.json; - the spec_sha256 pins in test_spec_engine_loader.py and test_us_multispine_pool_tool.py. The helper-source pins for _apply_constraint and _relative_error_loss in pre_best_iterate/controls.json and test_l2_basis.py move because both helpers now begin with `import torch`. With the lock-check record, a step process start now takes 6.3 s and 0.30 GB peak RSS and a QRF worker start 8.4 s and 0.29 GB (median of 3 on a 10-core Mac at load average 5), against 37.8 s / 1.54 GB and 36.6 s / 1.75 GB before this branch. Co-Authored-By: Claude Opus 5.5 --- .../us-base-engine-lock-check-once.changed.md | 2 +- .../src/microcosm/calibrate/solve.py | 48 ++++++++++++++++++- .../tests/engine_free/shared/test_l2_basis.py | 9 ++-- .../fixtures/pre_best_iterate/controls.json | 4 +- 4 files changed, 55 insertions(+), 8 deletions(-) diff --git a/changelog.d/us-base-engine-lock-check-once.changed.md b/changelog.d/us-base-engine-lock-check-once.changed.md index 927b43abfd..47a3170c75 100644 --- a/changelog.d/us-base-engine-lock-check-once.changed.md +++ b/changelog.d/us-base-engine-lock-check-once.changed.md @@ -1 +1 @@ -The US base stage checks the policyengine-us lock file (`engine_abi.lock.json`) once in the `--stage all` process instead of in every step process and QRF worker. The parent hands each step process a record of its check (lock file SHA-256, installed policyengine-us version and take-up and sources domain digest, in `MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD`), which the step process passes on to its QRF workers; a child with its parent's record compares those three values instead of building two tax-benefit systems, and refuses to run when any differs. Processes without a record from their parent still run the full check. The QRF worker identity digest changes once, because its import trace now opens three fewer files. +The US base stage checks the policyengine-us lock file (`engine_abi.lock.json`) once in the `--stage all` process instead of in every step process and QRF worker. The parent hands each step process a record of its check (lock file SHA-256, installed policyengine-us version and take-up and sources domain digest, in `MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD`), and each step process hands the QRF workers it starts the record of its own check. A child with its parent's record compares those three values instead of building two tax-benefit systems, and refuses to run when any differs. Processes without a record from their parent still run the full check. `microcosm.calibrate.solve` now imports torch inside the functions that use it, so importing `microcosm.calibrate` no longer imports torch. Together these cut a step process start from about 38 s and 1.5 GB peak resident memory to about 6 s and 0.3 GB, and a QRF worker start from about 37 s and 1.75 GB to about 8 s and 0.3 GB, on a 10-core Mac. The QRF worker identity digest changes once: its import trace no longer opens `gate_shadow.py`, `multispine_pool.py` or `us_late_overlap_ownership.py`, and imports fewer standard-library and third-party modules. The seed-protocol and seed-map digests and the US `spec_sha256` pins move because `solve.py` and `puf_qrf_chain.py` are attested kernel sources; no draw or data output changes. diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py index 483d2f920a..0a9c29dfe5 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py @@ -90,9 +90,9 @@ import warnings from collections.abc import Callable, Mapping from dataclasses import dataclass, field +from typing import TYPE_CHECKING import numpy as np -import torch from scipy import sparse from microcosm.calibrate.exact_k import ( @@ -103,7 +103,6 @@ assert_exact_k_support, exact_k_design_feasibility, ) -from microcosm.calibrate.gates import HardConcrete from microcosm.calibrate.initialization import GateInitialization from microcosm.calibrate.matrix import ( CalibrationProblem, @@ -113,6 +112,13 @@ from microcosm.calibrate.target import TargetSet from microcosm.frame import Frame, MassChange, WeightKind, Weights +if TYPE_CHECKING: + # Torch is imported by the functions that use it, so importing this + # module (as every importer of microcosm.calibrate does) does not import it. + import torch + + from microcosm.calibrate.gates import HardConcrete + __all__ = [ "calibrate", "calibrate_l0_refit", @@ -604,6 +610,9 @@ def _torch_constraint_matrix(matrix) -> torch.Tensor: to a torch sparse-CSR tensor and every epoch runs SpMM instead; autograd flows to the dense weight operand. """ + + import torch + cells = int(matrix.shape[0]) * int(matrix.shape[1]) density = (matrix.nnz / cells) if cells else 1.0 if cells >= _SPARSE_MIN_CELLS and density <= _SPARSE_DENSITY_CUTOFF: @@ -619,6 +628,9 @@ def _torch_constraint_matrix(matrix) -> torch.Tensor: def _apply_constraint(matrix: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: """``A @ w`` for a dense or sparse-CSR ``A`` (targets x records).""" + + import torch + if matrix.layout == torch.sparse_csr: # SpMM needs a 2-D dense operand; SpMV is not exposed with autograd. return (matrix @ weights.unsqueeze(1)).squeeze(1) @@ -756,6 +768,9 @@ def _relative_error_loss( target_loss_cap: float, ) -> torch.Tensor: """The capped weighted-MAPE target loss, optionally averaged with row weights.""" + + import torch + scaled_error = (estimate - targets) / target_loss_scales loss = torch.clamp( torch.abs(scaled_error), @@ -1053,6 +1068,9 @@ def _sorted_capped_log_shift( rounds once per record, at the resolution of a log-sum that size (*Precision* in :func:`_capped_log_shift` gives the figures). """ + + import torch + rest = ~capped & torch.isfinite(log_weights) order = torch.argsort(cap_shift[rest]) rest_shift = cap_shift[rest][order] @@ -1155,6 +1173,9 @@ def _capped_log_shift( Returns the shift and the rounds taken (``active_set_rounds + 1`` when the sort finished it). """ + + import torch + cap_shift = torch.where( torch.isneginf(log_upper), torch.full_like(log_upper, -math.inf), @@ -1207,6 +1228,9 @@ def _project_softmax_log_weights_( projection is the shift alone. Returns the active-set rounds taken (0 without a cap). """ + + import torch + log_weights = log_w.detach().to(torch.float64) log_weights = log_weights + ( math.log(total) - float(torch.logsumexp(log_weights, dim=0)) @@ -1225,6 +1249,9 @@ def _max_cap_ratio(weights: torch.Tensor, cap: torch.Tensor) -> float: A record with a zero cap reads ``0`` while its weight is zero (``0 / 0``) and ``inf`` once it is not. """ + + import torch + ratio = weights.detach().to(torch.float64) / cap return float(torch.nan_to_num(ratio, nan=0.0, posinf=math.inf).max()) @@ -1278,6 +1305,11 @@ def _optimize( callers. The third value is aligned per-record ``pi_i`` for an L0 run and ``None`` when no gates were active. """ + + import torch + + from microcosm.calibrate.gates import HardConcrete + w0 = np.asarray(initial_weights, dtype=np.float64) start = _prepare_warm_start_weights( w0, @@ -1582,6 +1614,9 @@ def _optimize_proximal( is used for the prox, so ``l1_lambda`` is the recorded mean-ratio objective coefficient. """ + + import torch + w0 = np.asarray(initial_weights, dtype=np.float64) start = _prepare_warm_start_weights( w0, @@ -1821,6 +1856,9 @@ def _search_l0_lambda_for_budget( vector is appended. The default four-item tuple is retained for existing workspace callers. """ + + import torch + bracket_lo, bracket_hi = _check_l0_search_bracket(search_bracket) lo_u, hi_u = math.log10(bracket_lo), math.log10(bracket_hi) warm = initial_lambda is not None and initial_lambda > 0 @@ -2658,6 +2696,9 @@ def calibrate( (``l0_lambda``) lies outside the search bracket, or if no targets compile (from the matrix build). """ + + import torch + if method == "apg": warnings.warn( "method='apg' is deprecated and now aliases method='adam'; result " @@ -3097,6 +3138,9 @@ def solve_constraint_system( ``(weights, trajectory)``, as :func:`calibrate` reports ``weights`` and ``loss_trajectory``. """ + + import torch + _check_mass(mass) _check_epochs_and_weight_ratio(epochs, max_weight_ratio, mass=mass) l2_anchor_weights = _checked_l2_options( diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_l2_basis.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_l2_basis.py index a56f368a92..839bb873ab 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_l2_basis.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_l2_basis.py @@ -781,10 +781,13 @@ def test_result_reports_the_realized_chi_square_distance() -> None: ) #: The live helpers the oracle imports. These digests equal the helpers' #: sources at bda72cb02 (checked with ``git show bda72cb02:.../solve.py`` when -#: the pin was written), so the oracle runs the pre-change closure exactly. +#: the pin was written), except that ``_apply_constraint`` and +#: ``_relative_error_loss`` now begin with ``import torch``, so that importing +#: ``solve`` does not import torch. Their computations are unchanged, so the +#: oracle runs the pre-change closure exactly. _HELPER_SOURCE_SHA256 = { "_apply_constraint": ( - "86281bdf18bdc17acafbbe79e15fb6b4c4102840a1315c3b6bbf52b170d8749c" + "83c043a3e29353196cc38dbbac34b6f0a3158559e3a3fc4b298ea204917b1bf9" ), "_prepare_warm_start_weights": ( "2e50a07a704ad2ab9d6529a965b7554f7aaba3972ec046a14e5a519e4f0904ed" @@ -793,7 +796,7 @@ def test_result_reports_the_realized_chi_square_distance() -> None: "f220ae141fc9144a4a1eec2c894f49065e88bbc1fd18be837ddec2d96cdd52f0" ), "_relative_error_loss": ( - "e7bba6d694211827780e2d5a0c60436decbaa1dc9310a7caa62945ac4d50843d" + "c1467e48d95dcda283f50e171ec31dda5658facc9a0ec23ad7f430e035615529" ), } diff --git a/packages/microcosm-calibrate/tests/fixtures/pre_best_iterate/controls.json b/packages/microcosm-calibrate/tests/fixtures/pre_best_iterate/controls.json index 7a4c3bbb67..6a36dde56d 100644 --- a/packages/microcosm-calibrate/tests/fixtures/pre_best_iterate/controls.json +++ b/packages/microcosm-calibrate/tests/fixtures/pre_best_iterate/controls.json @@ -124,10 +124,10 @@ "source_path": "packages/microcosm-calibrate/src/microcosm/calibrate/solve.py", "source_sha256": "f4b32c40a8675c37b0a4f3c1e48ca7b2078e803dac4413221aeb98c23b9e2066", "helper_source_sha256": { - "_apply_constraint": "86281bdf18bdc17acafbbe79e15fb6b4c4102840a1315c3b6bbf52b170d8749c", + "_apply_constraint": "83c043a3e29353196cc38dbbac34b6f0a3158559e3a3fc4b298ea204917b1bf9", "_prepare_warm_start_weights": "2e50a07a704ad2ab9d6529a965b7554f7aaba3972ec046a14e5a519e4f0904ed", "_project_to_total": "f220ae141fc9144a4a1eec2c894f49065e88bbc1fd18be837ddec2d96cdd52f0", - "_relative_error_loss": "e7bba6d694211827780e2d5a0c60436decbaa1dc9310a7caa62945ac4d50843d", + "_relative_error_loss": "c1467e48d95dcda283f50e171ec31dda5658facc9a0ec23ad7f430e035615529", "_validate_target_loss_cap": "7d7a663cc1de3f3667ea713329387a7913063335a47bc693299fd5c2479f8553" }, "gates_source_path": "packages/microcosm-calibrate/src/microcosm/calibrate/gates.py", From 628ec8f658ef10fdcd54f9703faa07bc02b7d035 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:17:32 +0400 Subject: [PATCH 07/12] Say in the lock-check record's docstring what a child does not compare Round 1 of review noted that a child compares only the policyengine-us version string. State that a same-version reinstall or a changed policyengine-core during a run is not noticed by a child with a record. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/spec_engine/engine_abi.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py b/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py index 38a25b7ffd..01cbcbc5fa 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py @@ -69,6 +69,11 @@ class _LockCheckInputs: process's direct children, which run the same checkout within the same run. A source edit during a base run is the base stage's run-config check to catch (its builder code digest), not this record's. + + The engine is matched by its installed distribution version only, as the + base stage's run config records it. A policyengine-us reinstalled with + different files under the same version during a run, or a changed + policyengine-core, is not noticed by a child holding a record. """ lock_sha256: str From df1a6bb020b8d05f6f0b17caf8357d2b8be4b97d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:51:00 +0400 Subject: [PATCH 08/12] Rewrite the QRF worker torch-autoload test for the new import order test_stacked_worker_first_torch_import_forces_autoload_off exited at the worker's first torch import, which used to happen while the worker's parent packages loaded. Now that microcosm.calibrate.solve imports torch inside the functions that use it, loading the worker imports no torch, so the child reached main() and failed on the test's placeholder manifest. The child now loads the worker module, checks that torch is still absent, then makes the process's first torch import itself and records the same controls, plus the device-backend setting the launcher passed before the worker module could set its own. Also correct three comments that said solve imports torch at load time, or that step processes pass the parent's record on to their QRF workers. Co-Authored-By: Claude Opus 5.5 --- docs/spec-engine.md | 6 ++--- .../build/us_runtime/puf_qrf_worker.py | 7 +++--- .../microcosm/build/us_runtime/support_mix.py | 3 ++- .../engine_free/us/test_us_stacked_spine.py | 25 ++++++++++++++----- 4 files changed, 28 insertions(+), 13 deletions(-) diff --git a/docs/spec-engine.md b/docs/spec-engine.md index f50f32af0f..5676c9bc2b 100644 --- a/docs/spec-engine.md +++ b/docs/spec-engine.md @@ -417,9 +417,9 @@ final_owner_stage: … installed policyengine-us version and a digest of the take-up and sources domains, bound to the issuing process ID). A direct child compares those three values instead of deriving the lock again and - refuses to run when any differs; the US base stage's `--stage all` - process does this for its step processes, which pass it on to their QRF - workers. + refuses to run when any differs. In the US base stage, the `--stage all` + process passes its record to each step process, and each step process + passes a record of its own check to the QRF workers it starts. - Column/entity mapping comes from the ABI projection with a **total-and-injective assertion** (the suffix naming rule died on `takes_up_eitc`/`takes_up_dc_ptc`). diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/puf_qrf_worker.py b/packages/microcosm-build/src/microcosm/build/us_runtime/puf_qrf_worker.py index 24d3b6a761..502f4013e7 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/puf_qrf_worker.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/puf_qrf_worker.py @@ -7,9 +7,10 @@ from pathlib import Path _TORCH_BACKEND_AUTOLOAD_ENVIRONMENT = "TORCH_DEVICE_BACKEND_AUTOLOAD" -# The authenticated launcher sets this before interpreter startup because -# parent-package imports can load Torch before this module. Keep the bootstrap -# override as defense in depth for subsequent imports. +# The authenticated launcher sets this before interpreter startup. Loading this +# module's parent packages no longer imports torch, but anything that imports it +# later in this process must see device-backend autoloading off, so keep the +# bootstrap override as defense in depth. os.environ[_TORCH_BACKEND_AUTOLOAD_ENVIRONMENT] = "0" from microcosm.build.us_runtime.puf_qrf_chain import ( # noqa: E402 diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/support_mix.py b/packages/microcosm-build/src/microcosm/build/us_runtime/support_mix.py index ea299ae3de..ae12c86efe 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/support_mix.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/support_mix.py @@ -331,7 +331,8 @@ def arm_initial_weights( def kish_ess(weights: np.ndarray) -> float: """Kish effective sample size ``(sum w)^2 / sum w^2`` over rows.""" - # Imported here: microcosm.calibrate.solve imports torch. + # Imported here, so importing this module does not load the calibration + # solver. from microcosm.calibrate.solve import effective_sample_size return effective_sample_size(weights) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_stacked_spine.py b/packages/microcosm-build/tests/engine_free/us/test_us_stacked_spine.py index 8b9b4be75f..4b0d0baa91 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_stacked_spine.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_stacked_spine.py @@ -4481,7 +4481,14 @@ def test_stacked_worker_first_torch_import_forces_autoload_off( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: - """Exercise the stacked launch in a child with no preloaded parent packages.""" + """Exercise the stacked launch in a child with no preloaded parent packages. + + Loading the worker no longer imports torch (``microcosm.calibrate.solve`` + imports it inside the functions that use it), so the child loads the worker + module, checks that torch is still absent, and then makes the process's + first torch import itself. The launcher's forced controls must be in effect + before the worker module sets its own device-backend override. + """ import subprocess @@ -4525,7 +4532,7 @@ def initialize(_frame: Frame, _donor: pd.DataFrame, root: Path, **_kwargs) -> No ), ) # Keep the real chain's subprocess argv/environment assembly; replace only - # the model/checkpoint work, which the first-import probe never reaches. + # the model/checkpoint work, which the probe never runs. monkeypatch.setattr( chain_module, "_load_manifest", @@ -4541,18 +4548,20 @@ def initialize(_frame: Frame, _donor: pd.DataFrame, root: Path, **_kwargs) -> No launch_prefixes: list[Path] = [] script = r""" import builtins +import importlib import json import os -import runpy import sys assert "torch" not in sys.modules assert "microcosm.build" not in sys.modules +launcher_autoload = os.environ.get("TORCH_DEVICE_BACKEND_AUTOLOAD") original_import = builtins.__import__ def record_first_torch_import(name, *args, **kwargs): if name == "torch" or name.startswith("torch."): print("FIRST_TORCH_IMPORT=" + json.dumps({ + "launcher_autoload": launcher_autoload, "autoload": os.environ.get("TORCH_DEVICE_BACKEND_AUTOLOAD"), "worker_loaded": "microcosm.build.us_runtime.puf_qrf_worker" in sys.modules, "pycache_prefix": sys.pycache_prefix, @@ -4563,8 +4572,11 @@ def record_first_torch_import(name, *args, **kwargs): builtins.__import__ = record_first_torch_import sys.argv = [sys.argv[1], *sys.argv[2:]] -runpy.run_module("microcosm.build.us_runtime.puf_qrf_worker", run_name="__main__") -raise AssertionError("worker never imported torch") +importlib.import_module("microcosm.build.us_runtime.puf_qrf_worker") +if "torch" in sys.modules: + raise AssertionError("loading the worker imported torch") +import torch # noqa: E402,F401 - the process's first torch import, recorded above +raise AssertionError("the first torch import was not recorded") """ def launch_probe(argv: list[str], **kwargs): @@ -4616,8 +4628,9 @@ def launch_probe(argv: list[str], **kwargs): assert len(launch_prefixes) == 1 assert observed == [ { + "launcher_autoload": "0", "autoload": "0", - "worker_loaded": False, + "worker_loaded": True, "pycache_prefix": str(launch_prefixes[0]), "dont_write_bytecode": 1, } From 31c747bb4dfde9975e72ad6c8e7d7021bb26d38e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:19:49 +0400 Subject: [PATCH 09/12] Check that the full bundle loader with a record skips policyengine-us test_the_full_us_bundle_loader_accepts_the_parents_record asserted only the child's exit code, which a child that ignored the record and ran the full check would also pass. It now also requires that the child imports no policyengine-us. The changelog now says that the QRF workers of the multispine pool tool and the release tool's stacked spine receive a record too, since run_primary_puf_qrf_chain adds it for every caller. Co-Authored-By: Claude Opus 5.5 --- changelog.d/us-base-engine-lock-check-once.changed.md | 2 +- .../us/test_us_engine_abi_lock_check_record.py | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/changelog.d/us-base-engine-lock-check-once.changed.md b/changelog.d/us-base-engine-lock-check-once.changed.md index 47a3170c75..a3641497f7 100644 --- a/changelog.d/us-base-engine-lock-check-once.changed.md +++ b/changelog.d/us-base-engine-lock-check-once.changed.md @@ -1 +1 @@ -The US base stage checks the policyengine-us lock file (`engine_abi.lock.json`) once in the `--stage all` process instead of in every step process and QRF worker. The parent hands each step process a record of its check (lock file SHA-256, installed policyengine-us version and take-up and sources domain digest, in `MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD`), and each step process hands the QRF workers it starts the record of its own check. A child with its parent's record compares those three values instead of building two tax-benefit systems, and refuses to run when any differs. Processes without a record from their parent still run the full check. `microcosm.calibrate.solve` now imports torch inside the functions that use it, so importing `microcosm.calibrate` no longer imports torch. Together these cut a step process start from about 38 s and 1.5 GB peak resident memory to about 6 s and 0.3 GB, and a QRF worker start from about 37 s and 1.75 GB to about 8 s and 0.3 GB, on a 10-core Mac. The QRF worker identity digest changes once: its import trace no longer opens `gate_shadow.py`, `multispine_pool.py` or `us_late_overlap_ownership.py`, and imports fewer standard-library and third-party modules. The seed-protocol and seed-map digests and the US `spec_sha256` pins move because `solve.py` and `puf_qrf_chain.py` are attested kernel sources; no draw or data output changes. +The US base stage checks the policyengine-us lock file (`engine_abi.lock.json`) once in the `--stage all` process instead of in every step process and QRF worker. The parent hands each step process a record of its check (lock file SHA-256, installed policyengine-us version and take-up and sources domain digest, in `MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD`), and `run_primary_puf_qrf_chain` hands every QRF worker it starts the record of its caller's own check, so the QRF workers of `tools/build_us_multispine_pool.py` and of the release tool's stacked spine skip the derivation too. A child with its parent's record compares those three values instead of building two tax-benefit systems, and refuses to run when any differs. Processes without a record from their parent still run the full check. `microcosm.calibrate.solve` now imports torch inside the functions that use it, so importing `microcosm.calibrate` no longer imports torch. Together these cut a step process start from about 38 s and 1.5 GB peak resident memory to about 6 s and 0.3 GB, and a QRF worker start from about 37 s and 1.75 GB to about 8 s and 0.3 GB, on a 10-core Mac. The QRF worker identity digest changes once: its import trace no longer opens `gate_shadow.py`, `multispine_pool.py` or `us_late_overlap_ownership.py`, and imports fewer standard-library and third-party modules. The seed-protocol and seed-map digests and the US `spec_sha256` pins move because `solve.py` and `puf_qrf_chain.py` are attested kernel sources; no draw or data output changes. diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_engine_abi_lock_check_record.py b/packages/microcosm-build/tests/engine_contract/us/test_us_engine_abi_lock_check_record.py index 3ae0ffcba0..e1eaced0ff 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_us_engine_abi_lock_check_record.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_engine_abi_lock_check_record.py @@ -86,7 +86,11 @@ def test_a_base_process_with_its_parents_record_does_not_import_policyengine_us( def test_the_full_us_bundle_loader_accepts_the_parents_record( tmp_path: Path, ) -> None: - """The full loader compares the same take-up and sources domains.""" + """The full loader compares the same take-up and sources domains. + + Had its digest of those domains differed, the child would refuse; had it + ignored the record, it would import policyengine-us to derive the lock. + """ environment = { **os.environ, @@ -96,6 +100,8 @@ def test_the_full_us_bundle_loader_accepts_the_parents_record( completed = subprocess.run( [ sys.executable, + "-X", + "importtime", "-c", "from microcosm.build.spec_engine import load_bundle\nload_bundle('us')\n", ], @@ -108,3 +114,6 @@ def test_the_full_us_bundle_loader_accepts_the_parents_record( ) assert completed.returncode == 0, completed.stderr[-4000:] + imported = _imported_modules(completed.stderr) + assert "microcosm.build.spec_engine.engine_abi" in imported + assert "policyengine_us" not in imported From aadceefc8aa63a0a89ca51a5ef421f38e09a0534 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:55:52 +0400 Subject: [PATCH 10/12] Re-pin the seed digests, spec hashes and calibrate parity pins on main After rebasing onto main (which moved the same pins for #1686's shared SIPP read), re-run tools/repin_us_spec_engine_contracts.py in its documented order, twice so the coverage test's covered-item count is taken after the seed digests are current, then tools/spec_engine_coverage.py and the re-pin tool's --check: - EXPECTED_HASHES seed_map and seed_protocol in inventory_coverage.py; - docs/evidence/spec-engine/us-f0-coverage.json; - the spec_sha256 pins in test_spec_engine_loader.py and test_us_multispine_pool_tool.py, each with a line saying why it moved. calibrate.adam@1's implementation hash covers solve.py's bytes, so re-pin the calibrate graph parity case with tools/graph_parity_repin.py on arm64/darwin/py3.14, the platform it was recorded on. The tool refuses if the kernel's output bytes move; they did not. Co-Authored-By: Claude Opus 5.5 --- docs/evidence/spec-engine/us-f0-coverage.json | 16 ++++++++-------- .../build/spec_engine/inventory_coverage.py | 7 +++++-- .../shared/test_spec_engine_loader.py | 4 +++- .../us/test_us_multispine_pool_tool.py | 5 ++++- .../fixtures/parity/kernels/calibrate/pins.json | 2 +- 5 files changed, 21 insertions(+), 13 deletions(-) diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index e8344d4b9b..d2b3171679 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "74aa4ed49e24b76e6126d440180a71553c767f0cc60156ddd183033fd8972505", - "protocol_sha256": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403" + "map_sha256": "18f3d56228481759dc55e88557150ec8d2017fbbe43e100392ce3502aab749ac", + "protocol_sha256": "60168760c5521b6b808c35496863317ff97427f2305a8c80d73dce7390c89b4f" }, "failures": [], "observed": { - "map_sha256": "74aa4ed49e24b76e6126d440180a71553c767f0cc60156ddd183033fd8972505", - "protocol_sha256": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403" + "map_sha256": "18f3d56228481759dc55e88557150ec8d2017fbbe43e100392ce3502aab749ac", + "protocol_sha256": "60168760c5521b6b808c35496863317ff97427f2305a8c80d73dce7390c89b4f" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403", + "implementation_sha256": "60168760c5521b6b808c35496863317ff97427f2305a8c80d73dce7390c89b4f", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403", + "implementation_sha256": "60168760c5521b6b808c35496863317ff97427f2305a8c80d73dce7390c89b4f", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "499389d4b1f0c967c54a6f2fa81b8a07a7e59c045bf2a8fe6bb909f08561d049" + "spec_sha256": "098de45a444dba7a1151503f78b4c4574bb4acd60a0be0351cdc69528d2469de" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "499389d4b1f0c967c54a6f2fa81b8a07a7e59c045bf2a8fe6bb909f08561d049" + "spec_sha256": "098de45a444dba7a1151503f78b4c4574bb4acd60a0be0351cdc69528d2469de" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index 52bdfc8b8e..ffae4ebc9f 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -413,8 +413,11 @@ # is unchanged, and no draw changes. # microcosm#1686's shared SIPP person-file read moves both again: the five # SIPP donor tables are byte-identical, and no draw changes. - "seed_map": "74aa4ed49e24b76e6126d440180a71553c767f0cc60156ddd183033fd8972505", - "seed_protocol": "24bb621745b2b753c1f89843c90f29949c0ad764df4cdcd315afdbf9aa7f6403", + # Importing torch inside the solve functions that use it, and the QRF chain + # handing each worker a record of its caller's lock-file check, move both + # again: solve's and puf_qrf_chain's attested bytes change; no draw does. + "seed_map": "18f3d56228481759dc55e88557150ec8d2017fbbe43e100392ce3502aab749ac", + "seed_protocol": "60168760c5521b6b808c35496863317ff97427f2305a8c80d73dce7390c89b4f", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index 403ae2d6a4..d4f5b187f4 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -39,8 +39,10 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # microcosm.fit.qrf, moves the fit kernels' bytes again. # calibrate's return_frame option in solve moves it again. # microcosm#1686's shared SIPP person-file read moves it again. + # Importing torch inside the solve functions that use it, and the QRF chain + # passing its workers a lock-file check record, move it again. assert first.spec_sha256 == ( - "c0431e2baa14c8fcc5fb3475f8cca5391d3c87c814f84f4256a7710b942b8c0b" + "30724d025798cf3a979bb80b3d584b1bda4070edcf8f6dfa3567e12e994df9c1" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 68f1f6a56a..02552c188e 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -371,7 +371,10 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm.fit.qrf, moves it again. # calibrate's return_frame option in solve moves it again. # microcosm#1686's shared SIPP person-file read moves it again. - "spec_sha256": "499389d4b1f0c967c54a6f2fa81b8a07a7e59c045bf2a8fe6bb909f08561d049", + # Importing torch inside the solve functions that use it, and the + # QRF chain passing its workers a lock-file check record, move it + # again. + "spec_sha256": "098de45a444dba7a1151503f78b4c4574bb4acd60a0be0351cdc69528d2469de", }, } diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json index da8d41937d..825ed11df9 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"e8ab1d370f02917ac073f7ac0e2413e259d66acf66adeab93d4bfa9057554673","kernel":"calibrate.adam@1","node":"calibrate","node_key":"18a16aefaba5c3fbbce77d193074a202ef1d58e0a3d90bd085bf8ae5853628b2","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"18a16aefaba5c3fbbce77d193074a202ef1d58e0a3d90bd085bf8ae5853628b2"}},"seed":0} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"0405a5f273a4ee02a966a74165291241aebe7a193b92559707a965c5f685eb88","kernel":"calibrate.adam@1","node":"calibrate","node_key":"a7302055f9caeadb3dad6a60b810d68fc26a7cd412ccb1fe01b080af0572d47f","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"a7302055f9caeadb3dad6a60b810d68fc26a7cd412ccb1fe01b080af0572d47f"}},"seed":0} From 584ca3710aac705ee477185d57e5ac71f825dcc8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:40:11 +0400 Subject: [PATCH 11/12] Fix the wording points from the third review round - The refusal messages no longer repeat engine_abi.lock.json, which SpecValidationError already prints from its source. - The _LockCheckInputs docstring says only direct children act on a record, since every descendant can inherit the variable. - docs/spec-engine.md says a process issues a record after the full comparison or after matching its own parent's record. Co-Authored-By: Claude Opus 5.5 --- docs/spec-engine.md | 5 +++-- .../src/microcosm/build/spec_engine/engine_abi.py | 13 +++++++------ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/spec-engine.md b/docs/spec-engine.md index 5676c9bc2b..633256fe1a 100644 --- a/docs/spec-engine.md +++ b/docs/spec-engine.md @@ -411,8 +411,9 @@ final_owner_stage: … compilation; engine bumps fail closed until the lock is regenerated and every bundle-owned treatment re-reviewed. The engine owns its facts; the bundle owns treatments and pipelines; neither derives from - the other at build time. A process that passed the full comparison can - pass the processes it starts a record of it in + the other at build time. A process that passed the comparison (fully, or + by matching its own parent's record) can pass the processes it starts a + record of it in `MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD` (the lock file's SHA-256, the installed policyengine-us version and a digest of the take-up and sources domains, bound to the issuing process ID). A direct child diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py b/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py index 01cbcbc5fa..c100bb57af 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/engine_abi.py @@ -65,8 +65,9 @@ class _LockCheckInputs: Besides microcosm's own code, the fresh derivation reads only the installed policyengine-us and the bundle's typed take-up and sources domains. - Microcosm's code is not recorded: a record reaches only the issuing - process's direct children, which run the same checkout within the same run. + Microcosm's code is not recorded: only the issuing process's direct + children act on a record (others ignore it), and they run the same + checkout within the same run. A source edit during a base run is the base stage's run-config check to catch (its builder code digest), not this record's. @@ -671,7 +672,7 @@ def _lock_matching_parent_check( observed_lock_sha256 = hashlib.sha256(raw).hexdigest() if observed_lock_sha256 != parent_check.lock_sha256: raise SpecValidationError( - "engine_abi.lock.json: the lock file differs from the one the parent " + "the lock file differs from the one the parent " f"process checked (SHA-256 {observed_lock_sha256}, parent checked " f"{parent_check.lock_sha256}); refusing to run", source=ENGINE_ABI_LOCK_FILENAME, @@ -685,7 +686,7 @@ def _lock_matching_parent_check( if installed_version != parent_check.engine_version: observed = "not installed" if installed_version is None else installed_version raise SpecValidationError( - "engine_abi.lock.json: the installed policyengine-us differs from " + "the installed policyengine-us differs from " "the one the parent process checked the lock file against " f"({observed}, parent checked {parent_check.engine_version}); " "refusing to run", @@ -694,7 +695,7 @@ def _lock_matching_parent_check( observed_domains_sha256 = _lock_check_domains_sha256(domains) if observed_domains_sha256 != parent_check.domains_sha256: raise SpecValidationError( - "engine_abi.lock.json: the take-up and sources domains differ from " + "the take-up and sources domains differ from " "those the parent process checked the lock file against (SHA-256 " f"{observed_domains_sha256}, parent checked " f"{parent_check.domains_sha256}); refusing to run", @@ -705,7 +706,7 @@ def _lock_matching_parent_check( "version": parent_check.engine_version, }: raise SpecValidationError( - "engine_abi.lock.json: the lock file does not name the policyengine-us " + "the lock file does not name the policyengine-us " "version the parent process checked it against; refusing to run", source=ENGINE_ABI_LOCK_FILENAME, ) From 9e42298f625e7a94e89f338020fa0fa49b810f31 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:56:21 +0400 Subject: [PATCH 12/12] Say in the changelog that UK full builds re-solve once after this merges Review of #1750 noted that calibrate.adam@1, whose hash every UK solve kernel embeds, and uk.full.problem@1 both hash calibrate.solve, so the torch import move re-keys the UK solve: a build run with --require-solve-reuse against a graph store written before the merge stops with SolveReuseError. Co-Authored-By: Claude Opus 5.5 --- changelog.d/us-base-engine-lock-check-once.changed.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/us-base-engine-lock-check-once.changed.md b/changelog.d/us-base-engine-lock-check-once.changed.md index a3641497f7..123d68354a 100644 --- a/changelog.d/us-base-engine-lock-check-once.changed.md +++ b/changelog.d/us-base-engine-lock-check-once.changed.md @@ -1 +1 @@ -The US base stage checks the policyengine-us lock file (`engine_abi.lock.json`) once in the `--stage all` process instead of in every step process and QRF worker. The parent hands each step process a record of its check (lock file SHA-256, installed policyengine-us version and take-up and sources domain digest, in `MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD`), and `run_primary_puf_qrf_chain` hands every QRF worker it starts the record of its caller's own check, so the QRF workers of `tools/build_us_multispine_pool.py` and of the release tool's stacked spine skip the derivation too. A child with its parent's record compares those three values instead of building two tax-benefit systems, and refuses to run when any differs. Processes without a record from their parent still run the full check. `microcosm.calibrate.solve` now imports torch inside the functions that use it, so importing `microcosm.calibrate` no longer imports torch. Together these cut a step process start from about 38 s and 1.5 GB peak resident memory to about 6 s and 0.3 GB, and a QRF worker start from about 37 s and 1.75 GB to about 8 s and 0.3 GB, on a 10-core Mac. The QRF worker identity digest changes once: its import trace no longer opens `gate_shadow.py`, `multispine_pool.py` or `us_late_overlap_ownership.py`, and imports fewer standard-library and third-party modules. The seed-protocol and seed-map digests and the US `spec_sha256` pins move because `solve.py` and `puf_qrf_chain.py` are attested kernel sources; no draw or data output changes. +The US base stage checks the policyengine-us lock file (`engine_abi.lock.json`) once in the `--stage all` process instead of in every step process and QRF worker. The parent hands each step process a record of its check (lock file SHA-256, installed policyengine-us version and take-up and sources domain digest, in `MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD`), and `run_primary_puf_qrf_chain` hands every QRF worker it starts the record of its caller's own check, so the QRF workers of `tools/build_us_multispine_pool.py` and of the release tool's stacked spine skip the derivation too. A child with its parent's record compares those three values instead of building two tax-benefit systems, and refuses to run when any differs. Processes without a record from their parent still run the full check. `microcosm.calibrate.solve` now imports torch inside the functions that use it, so importing `microcosm.calibrate` no longer imports torch. Together these cut a step process start from about 38 s and 1.5 GB peak resident memory to about 6 s and 0.3 GB, and a QRF worker start from about 37 s and 1.75 GB to about 8 s and 0.3 GB, on a 10-core Mac. The QRF worker identity digest changes once: its import trace no longer opens `gate_shadow.py`, `multispine_pool.py` or `us_late_overlap_ownership.py`, and imports fewer standard-library and third-party modules. The seed-protocol and seed-map digests and the US `spec_sha256` pins move because `solve.py` and `puf_qrf_chain.py` are attested kernel sources; no draw or data output changes. UK full builds re-solve once after this merges: `calibrate.adam@1`, whose hash every UK solve kernel embeds, and `uk.full.problem@1` both hash `calibrate.solve`, so a build run with `--require-solve-reuse` against a graph store written before the merge stops with `SolveReuseError`. So merge before a UK build that writes the store or after the build that reuses it, not between the two.