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..123d68354a --- /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`), 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. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index b613307197..71be9d4600 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": "20648ca766969baf424f491150ab3d12b3edeb89a0544433e64e88c8efb42bb2", - "protocol_sha256": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15" + "map_sha256": "9c809470367a211c88ba047211ad9461850ca56100af41d56d807312ee8ccd5f", + "protocol_sha256": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5" }, "failures": [], "observed": { - "map_sha256": "20648ca766969baf424f491150ab3d12b3edeb89a0544433e64e88c8efb42bb2", - "protocol_sha256": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15" + "map_sha256": "9c809470367a211c88ba047211ad9461850ca56100af41d56d807312ee8ccd5f", + "protocol_sha256": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15", + "implementation_sha256": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15", + "implementation_sha256": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "b94bfc6a5742de010443938a676d4d34e70df80dd405f89e2ff7a70f747c8107" + "spec_sha256": "4c3c3beab01e381aadfea510f61ca28117670d35c6bed1e4bb0df2fa1be07b2e" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "b94bfc6a5742de010443938a676d4d34e70df80dd405f89e2ff7a70f747c8107" + "spec_sha256": "4c3c3beab01e381aadfea510f61ca28117670d35c6bed1e4bb0df2fa1be07b2e" }, "status": "pass" } diff --git a/docs/spec-engine.md b/docs/spec-engine.md index 33da8b2e36..633256fe1a 100644 --- a/docs/spec-engine.md +++ b/docs/spec-engine.md @@ -411,7 +411,16 @@ 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 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 + compares those three values instead of deriving the lock again and + 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/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..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 @@ -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,53 @@ _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: 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. + + 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 + 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 +472,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 +489,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 +584,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", + "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( + "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( + "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( + "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/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index acb3e86c87..b08a37c45b 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 @@ -415,8 +415,11 @@ # SIPP donor tables are byte-identical, and no draw changes. # The SIPP 2023 donor download tag and the financial-asset cache lookup # move both again: the donor bytes are unchanged, and no draw changes. - "seed_map": "20648ca766969baf424f491150ab3d12b3edeb89a0544433e64e88c8efb42bb2", - "seed_protocol": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15", + # 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": "9c809470367a211c88ba047211ad9461850ca56100af41d56d807312ee8ccd5f", + "seed_protocol": "eea4cf01a4924295e760edbe74e368dc6a48d66334ffe9a04d2fa13beebee2c5", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", 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(): 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/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/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..e1eaced0ff --- /dev/null +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_engine_abi_lock_check_record.py @@ -0,0 +1,119 @@ +"""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. + + 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, + **take_up_contract.us_engine_abi_lock_check_environment(), + } + + completed = subprocess.run( + [ + sys.executable, + "-X", + "importtime", + "-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:] + imported = _imported_modules(completed.stderr) + assert "microcosm.build.spec_engine.engine_abi" in imported + assert "policyengine_us" not in imported 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/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index 039139d1cc..6f2df4ecf2 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 @@ -41,8 +41,10 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # microcosm#1686's shared SIPP person-file read moves it again. # The SIPP 2023 donor download tag and the financial-asset cache lookup # move 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 == ( - "9ef2736b6b2c8e9e02c6d12c76acb6b4349479cd7bfceb0124a7bb8264bc9219" + "55fe6aee2557efed00c0a4da13f1bac5d28b6c12a28608bc1016e346c9fbb952" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") 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..4b379fea21 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_engine_abi_lock_check_record.py @@ -0,0 +1,238 @@ +"""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 puf_qrf_chain, 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] + + +@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") + 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:] + + +@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-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, } 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 6be927d3a6..69dd4629d4 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 @@ -373,7 +373,10 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1686's shared SIPP person-file read moves it again. # The SIPP 2023 donor download tag and the financial-asset cache lookup # move it again. - "spec_sha256": "b94bfc6a5742de010443938a676d4d34e70df80dd405f89e2ff7a70f747c8107", + # 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": "4c3c3beab01e381aadfea510f61ca28117670d35c6bed1e4bb0df2fa1be07b2e", }, } diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py index b413091678..6cc1a8099c 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py @@ -97,9 +97,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 ( @@ -110,7 +110,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, @@ -120,6 +119,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", @@ -611,6 +617,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: @@ -626,6 +635,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) @@ -763,6 +775,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), @@ -1087,6 +1102,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] @@ -1189,6 +1207,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), @@ -1241,6 +1262,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)) @@ -1259,6 +1283,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()) @@ -1317,6 +1344,11 @@ def _optimize( for each record. ``None`` (default) is the record's own starting weight, and every expression below is then the historical one. """ + + import torch + + from microcosm.calibrate.gates import HardConcrete + w0 = np.asarray(initial_weights, dtype=np.float64) if weight_bound_reference is None: bound_base = w0 @@ -1637,6 +1669,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, @@ -1876,6 +1911,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 @@ -2824,6 +2862,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 " @@ -3293,6 +3334,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, 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/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" 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", 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 e20dffbd05..0136c6e039 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":"0f2dc8f6eb3c1c9d07626bea14593453905e8191b7c4c4d68428ac14b9d11e06","kernel":"calibrate.adam@1","node":"calibrate","node_key":"51931394a100e39dc4b3bb195cca7e84c96599228b2a8b8bb8a196511ae44bf7","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"51931394a100e39dc4b3bb195cca7e84c96599228b2a8b8bb8a196511ae44bf7"}},"seed":0} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"b5cc6d747c03a75e3f8380bfbf3b6248273d6ad96d490c79f62b67a5b3f3de08","kernel":"calibrate.adam@1","node":"calibrate","node_key":"dfb189a13516a57d3f5e9365e7c6564cbc2a5b10aa46524edf04f90bb48882d8","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"dfb189a13516a57d3f5e9365e7c6564cbc2a5b10aa46524edf04f90bb48882d8"}},"seed":0} 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)