From bc94e9206c27bf3f1fe6878b0724e6225ed1da23 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:52:13 +0400 Subject: [PATCH 1/8] Size QRF prediction workers from joblib.cpu_count() With POPULACE_FIT_PREDICT_WORKERS unset, the QRF draw's thread pool, the primary-QRF worker identity and the older stacked-spine binding now take their width from microcosm.fit.qrf.default_predict_workers(), which returns joblib.cpu_count(): the smallest of the machine's CPU count, the affinity mask, a cgroup CPU quota and LOKY_MAX_CPU_COUNT. os.cpu_count() counted only the machine's CPUs. The variable still overrides it. The worker identity's cache keys an unset variable by the resolved width, because joblib.cpu_count() can change within a process. Tests compare 1 and 4 prediction workers and 1 and 4 fit jobs on fixed seeds for a single-forest target, a three-sign gated target and a fit_draw_next chain, and require byte-identical draws. Re-pinned the attested fit.qrf hashes: repin, coverage (41/41), repin, --check clean, then graph_parity_repin fit.qrf under Python 3.14. Co-Authored-By: Claude Opus 5.5 --- ...redict-workers-joblib-cpu-count.changed.md | 1 + docs/evidence/spec-engine/us-f0-coverage.json | 16 +- .../build/spec_engine/inventory_coverage.py | 6 +- .../build/us_runtime/stacked_spine.py | 3 +- .../build/us_runtime/worker_identity.py | 47 ++- .../shared/test_spec_engine_loader.py | 4 +- .../us/test_us_qrf_predict_worker_default.py | 116 ++++++ .../engine_free/us/test_us_stacked_spine.py | 6 +- .../us/test_us_multispine_pool_tool.py | 4 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 41 ++- .../shared/test_qrf_worker_counts.py | 331 ++++++++++++++++++ .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- 12 files changed, 541 insertions(+), 36 deletions(-) create mode 100644 changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py create mode 100644 packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py diff --git a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md new file mode 100644 index 0000000000..9c2909b17a --- /dev/null +++ b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md @@ -0,0 +1 @@ +Size the QRF draw's thread pool from the CPUs the process may use. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. The primary-QRF worker identity (`worker_identity.py`) and the older binding in `stacked_spine.py` record the same value, and the identity's cache now keys an unset variable by that value. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. A base run interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 348354e26c..d67a1e00ec 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": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "protocol_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e" + "map_sha256": "dceefacd3341afbade42936752f33829e084a5fdf526ace4d1b9866e199e7ecb", + "protocol_sha256": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265" }, "failures": [], "observed": { - "map_sha256": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "protocol_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e" + "map_sha256": "dceefacd3341afbade42936752f33829e084a5fdf526ace4d1b9866e199e7ecb", + "protocol_sha256": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + "implementation_sha256": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + "implementation_sha256": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84" + "spec_sha256": "f5ac251cebcbaf97d8f29fe9cea477126e381602b66f7b2c956995f931b5de75" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84" + "spec_sha256": "f5ac251cebcbaf97d8f29fe9cea477126e381602b66f7b2c956995f931b5de75" }, "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 fff542b87b..7a21968a75 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 @@ -402,8 +402,10 @@ # microcosm#1641 moves both again: it rewords docstrings and a comment in # solve and the delivery gate's docstring in ssi_take_up, which now names # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. - "seed_map": "d756dc67535c04788e605bedb4cd6721cf715e5f5ce4be73d9b27420a61b3d50", - "seed_protocol": "2c57cbfb9dd0f132f9b5751eb8bc303f4b7e37430cd5e0b155aac0b0b8eaa42e", + # The QRF draw's default thread count, joblib.cpu_count() in place of + # os.cpu_count() in microcosm.fit.qrf, moves both again; no draw changes. + "seed_map": "dceefacd3341afbade42936752f33829e084a5fdf526ace4d1b9866e199e7ecb", + "seed_protocol": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py index 1943db7cb2..2d0aca9155 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py @@ -221,6 +221,7 @@ us_late_producer_schedule_receipt, ) from microcosm.fit import Regime +from microcosm.fit.qrf import default_predict_workers from microcosm.frame import US_SCHEMA, Frame, WeightKind __all__ = [ @@ -6028,7 +6029,7 @@ def _legacy_primary_qrf_worker_execution_binding() -> dict[str, object]: ) predict_workers_raw = os.environ.get("POPULACE_FIT_PREDICT_WORKERS") if predict_workers_raw is None or not predict_workers_raw.strip(): - predict_workers = os.cpu_count() or 1 + predict_workers = default_predict_workers() predict_workers_source = "os_cpu_count_fallback" else: try: 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 c8a8996ea0..e54c880146 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 @@ -154,7 +154,7 @@ def record_worker_event(event, arguments): } _SHA256_ALPHABET = frozenset("0123456789abcdef") _PRIMARY_QRF_WORKER_IDENTITY_CACHE: dict[ - tuple[str | None, str | None, str | None], dict[str, object] + tuple[str | None, str | None, str | None, int | None], dict[str, object] ] = {} @@ -1221,6 +1221,24 @@ def _canonical_pyvenv_config() -> dict[str, object]: } +def _default_predict_workers() -> int: + """The QRF draw's own width for an unset ``POPULACE_FIT_PREDICT_WORKERS``. + + The worker resolves the same value through ``microcosm.fit.qrf``, so the + identity records the pool width the worker uses. Imported here rather + than at module level, which loads only the standard library and + ``packaging``. + """ + + from microcosm.fit.qrf import default_predict_workers + + return default_predict_workers() + + +def _predict_workers_unset(configured: str | None) -> bool: + return configured is None or not configured.strip() + + def _semantic_environment() -> dict[str, object]: fit_jobs_raw = os.environ.get("POPULACE_FIT_N_JOBS") if fit_jobs_raw is None: @@ -1239,8 +1257,8 @@ def _semantic_environment() -> dict[str, object]: "the primary-QRF worker binding." ) predict_workers_raw = os.environ.get("POPULACE_FIT_PREDICT_WORKERS") - if predict_workers_raw is None or not predict_workers_raw.strip(): - predict_workers = os.cpu_count() or 1 + if _predict_workers_unset(predict_workers_raw): + predict_workers = _default_predict_workers() predict_workers_source = "os_cpu_count_fallback" else: try: @@ -1276,6 +1294,20 @@ def _semantic_environment() -> dict[str, object]: } +def _primary_qrf_worker_identity_cache_key( + uv_lock_sha256: str | None, +) -> tuple[str | None, str | None, str | None, int | None]: + predict_workers_raw = os.environ.get("POPULACE_FIT_PREDICT_WORKERS") + return ( + uv_lock_sha256, + os.environ.get("POPULACE_FIT_N_JOBS"), + predict_workers_raw, + _default_predict_workers() + if _predict_workers_unset(predict_workers_raw) + else None, + ) + + def clear_primary_qrf_worker_identity_cache() -> None: """Clear process attestations after deliberate runtime or source mutations.""" @@ -1298,15 +1330,14 @@ def primary_qrf_worker_semantic_identity( lock on its first cache miss and after clearing, while explicit approved and legacy digests have separate entries. Bound environment values are likewise keyed by their raw configured strings so validation is preserved. + An unset prediction-worker count is also keyed by the width it resolves + to, which ``joblib.cpu_count()`` can change within a process (through + ``LOKY_MAX_CPU_COUNT`` or the CPU affinity mask). """ if uv_lock_sha256 is not None: _require_sha256(uv_lock_sha256, boundary="primary-QRF worker lock") - key = ( - uv_lock_sha256, - os.environ.get("POPULACE_FIT_N_JOBS"), - os.environ.get("POPULACE_FIT_PREDICT_WORKERS"), - ) + key = _primary_qrf_worker_identity_cache_key(uv_lock_sha256) if key not in _PRIMARY_QRF_WORKER_IDENTITY_CACHE: _PRIMARY_QRF_WORKER_IDENTITY_CACHE[key] = ( _uncached_primary_qrf_worker_semantic_identity( 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 56e430cbe6..25a17754e9 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 @@ -32,8 +32,10 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # kernels' bytes too. # microcosm#1641's docstring and comment wording in solve and ssi_take_up # moves it again. + # The QRF draw's default thread count, joblib.cpu_count() in + # microcosm.fit.qrf, moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "cb9742d5089eddb8783ee1cb890206b33a35efe5ff572656dbd58a1b95ea1e28" + "6a7728eddeb6be4d2e6a087e7d0eb403469730ef4d576c406650b77ca6e11699" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py new file mode 100644 index 0000000000..8824e9d6ea --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py @@ -0,0 +1,116 @@ +"""The primary-QRF worker records the QRF draw's default pool width. + +With ``POPULACE_FIT_PREDICT_WORKERS`` unset, the QRF draw sizes its thread pool +by ``joblib.cpu_count()`` (``microcosm.fit.qrf.default_predict_workers``). The +worker identity in ``worker_identity.py`` and the older binding in +``stacked_spine.py`` record that same width, and the environment variable +still overrides it. Each test patches ``joblib.cpu_count`` to a value that +``os.cpu_count()``, the earlier default, does not return. +""" + +# ruff: noqa: F403, F405 +from __future__ import annotations + +import os + +import joblib + +from test_support.microcosm_build.us_stacked_spine import * + +PREDICT_WORKERS_ENV = "POPULACE_FIT_PREDICT_WORKERS" + + +def _patch_joblib_cpu_count(monkeypatch: pytest.MonkeyPatch, value: int) -> None: + def patched_cpu_count(only_physical_cores: bool = False) -> int: + return value + + monkeypatch.setattr(joblib, "cpu_count", patched_cpu_count) + + +def _cpu_count_unlike_os(offset: int = 3) -> int: + return (os.cpu_count() or 1) + offset + + +def _set_predict_workers( + monkeypatch: pytest.MonkeyPatch, configured: str | None +) -> None: + if configured is None: + monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) + else: + monkeypatch.setenv(PREDICT_WORKERS_ENV, configured) + + +def _worker_identity_predict_controls() -> dict[str, object]: + return worker_identity_module._semantic_environment()["semantic_controls"][ + PREDICT_WORKERS_ENV + ] + + +def _stacked_spine_predict_controls() -> dict[str, object]: + binding = stacked_spine_module._legacy_primary_qrf_worker_execution_binding() + return binding["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] + + +PREDICT_CONTROL_READERS = ( + pytest.param(_worker_identity_predict_controls, id="worker_identity"), + pytest.param(_stacked_spine_predict_controls, id="stacked_spine"), +) + + +@pytest.mark.parametrize("read_controls", PREDICT_CONTROL_READERS) +@pytest.mark.parametrize("configured", [None, "", " "]) +def test_unset_predict_workers_record_joblib_cpu_count( + read_controls, configured: str | None, monkeypatch: pytest.MonkeyPatch +) -> None: + joblib_cpu_count = _cpu_count_unlike_os() + _patch_joblib_cpu_count(monkeypatch, joblib_cpu_count) + _set_predict_workers(monkeypatch, configured) + + controls = read_controls() + + assert controls["configured"] == configured + assert controls["resolved"] == joblib_cpu_count + + +@pytest.mark.parametrize("read_controls", PREDICT_CONTROL_READERS) +@pytest.mark.parametrize(("configured", "expected"), [("1", 1), ("2", 2), ("7", 7)]) +def test_predict_workers_override_wins_over_joblib_cpu_count( + read_controls, + configured: str, + expected: int, + monkeypatch: pytest.MonkeyPatch, +) -> None: + _patch_joblib_cpu_count(monkeypatch, _cpu_count_unlike_os()) + _set_predict_workers(monkeypatch, configured) + + assert read_controls() == { + "configured": configured, + "resolved": expected, + "resolution": "environment_override", + } + + +def test_worker_identity_memo_binds_unset_predict_worker_default( + _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch +) -> None: + """A changed ``joblib.cpu_count()`` recomputes the cached identity.""" + _source, calls = _worker_identity_memo_inputs + monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) + smaller, larger = _cpu_count_unlike_os(3), _cpu_count_unlike_os(5) + + _patch_joblib_cpu_count(monkeypatch, smaller) + first = worker_identity_module.primary_qrf_worker_semantic_identity() + _patch_joblib_cpu_count(monkeypatch, larger) + second = worker_identity_module.primary_qrf_worker_semantic_identity() + + predict = PREDICT_WORKERS_ENV + assert first["environment"]["semantic_controls"][predict]["resolved"] == smaller + assert second["environment"]["semantic_controls"][predict]["resolved"] == larger + assert worker_identity_module._canonical_sha256( + first + ) != worker_identity_module._canonical_sha256(second) + assert len(calls) == 2 + + _patch_joblib_cpu_count(monkeypatch, smaller) + assert worker_identity_module.primary_qrf_worker_semantic_identity() is first + assert len(calls) == 2 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 b4171135ce..b683fbbfbf 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 @@ -3332,11 +3332,7 @@ def test_primary_qrf_worker_execution_binding_isolates_semantic_memo( def test_worker_identity_session_prime_matches_pipeline_binding( _session_primary_qrf_worker_identities, ) -> None: - key = ( - None, - worker_identity_module.os.environ.get("POPULACE_FIT_N_JOBS"), - worker_identity_module.os.environ.get("POPULACE_FIT_PREDICT_WORKERS"), - ) + key = worker_identity_module._primary_qrf_worker_identity_cache_key(None) memo = worker_identity_module._PRIMARY_QRF_WORKER_IDENTITY_CACHE assert key in memo first = memo[key] 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 a22f1927d5..1a5c353f4d 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 @@ -363,7 +363,9 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1543's fit input checks in microcosm.fit.qrf move it again. # microcosm#1641 moves it again: docstring and comment wording in # solve and ssi_take_up, and the calibration contract's renamed modes. - "spec_sha256": "372858d059a129d7b3bcbd7ac2dbdc314742345bd35aaff8d53943e737c98f84", + # The QRF draw's default thread count, joblib.cpu_count() in + # microcosm.fit.qrf, moves it again. + "spec_sha256": "f5ac251cebcbaf97d8f29fe9cea477126e381602b66f7b2c956995f931b5de75", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 89d322dc10..4caba55c2c 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -64,6 +64,7 @@ from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, replace +import joblib import numpy as np import pandas as pd from quantile_forest import RandomForestQuantileRegressor @@ -1354,11 +1355,12 @@ def _predict_chunk(bound: tuple[int, int]) -> None: #: Environment override for the parallel draw's worker count. A build tool sets #: it to leave cores for concurrent work or to pin timing; unset defaults to -#: :func:`os.cpu_count`. +#: :func:`default_predict_workers`. _PREDICT_WORKERS_ENV = "POPULACE_FIT_PREDICT_WORKERS" #: Environment override for quantile-forest fit parallelism. Unset retains the -#: historical ``n_jobs=-1`` behavior; checkpointed production builds can pin it +#: historical ``n_jobs=-1`` behavior, which joblib resolves to +#: :func:`joblib.cpu_count` threads; checkpointed production builds can pin it #: to one (or another positive width) without changing the model API. _N_JOBS_ENV = "POPULACE_FIT_N_JOBS" @@ -1381,10 +1383,14 @@ def _predict_chunk(bound: tuple[int, int]) -> None: def _fit_n_jobs() -> int: """Resolve quantile-forest fit parallelism. - Unset preserves the historical ``n_jobs=-1`` default. If the environment - variable is present it must be a strict positive base-10 integer; in - particular, an empty string is an invalid configured value rather than a - second spelling of "unset". + Unset preserves the historical ``n_jobs=-1`` default. joblib resolves a + negative ``n_jobs`` when it starts the fit's and ``apply``'s threads, as + ``joblib.cpu_count() + 1 + n_jobs``, so ``-1`` already counts only the + CPUs the process may use (see :func:`default_predict_workers`). Chain + states and the primary-QRF worker identity record the literal ``-1``, + not that count. If the environment variable is present it must be a + strict positive base-10 integer; in particular, an empty string is an + invalid configured value rather than a second spelling of "unset". Raises: ValueError: If ``POPULACE_FIT_N_JOBS`` is set to anything other than a @@ -1404,6 +1410,23 @@ def _fit_n_jobs() -> int: return jobs +def default_predict_workers() -> int: + """The draw's thread-pool width when ``POPULACE_FIT_PREDICT_WORKERS`` is unset. + + :func:`joblib.cpu_count` is the smallest of the machine's logical CPU + count, the process's CPU affinity mask, a Linux cgroup CPU quota + (``cpu.max``) and ``LOKY_MAX_CPU_COUNT``. :func:`os.cpu_count`, the + default before it, counts only the machine's CPUs: in a container held to + a CPU quota it started one thread per host CPU, and the quota then paused + them. The value can change within a process (when ``LOKY_MAX_CPU_COUNT`` + or the affinity mask changes), so callers read it when they need it. + + The primary-QRF worker identity records this value for an unset override + (``microcosm.build.us_runtime.worker_identity``), so both read it here. + """ + return joblib.cpu_count() + + def _predict_workers() -> int: """Resolve the draw's thread-pool width. @@ -1415,15 +1438,15 @@ def _predict_workers() -> int: MB to gigabytes each, re-paid on every fit in the fit-then-predict-per- pattern transfer path — for no speed gain over the GIL-free threads. - Defaults to :func:`os.cpu_count`; ``POPULACE_FIT_PREDICT_WORKERS`` overrides - it with a positive integer. + Defaults to :func:`default_predict_workers`; ``POPULACE_FIT_PREDICT_WORKERS`` + overrides it with a positive integer. Raises: ValueError: If the override is set but not a positive integer. """ override = os.environ.get(_PREDICT_WORKERS_ENV) if override is None or not override.strip(): - return os.cpu_count() or 1 + return default_predict_workers() try: workers = int(override) except ValueError: diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py new file mode 100644 index 0000000000..f0a1934355 --- /dev/null +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py @@ -0,0 +1,331 @@ +"""QRF thread sizing: the default worker count, and draws that ignore it. + +The draw's thread pool is sized by ``POPULACE_FIT_PREDICT_WORKERS``, else by +:func:`joblib.cpu_count`, which counts the CPUs the process may use (affinity +mask, cgroup CPU quota, ``LOKY_MAX_CPU_COUNT``) where :func:`os.cpu_count` +counts the machine's. Tree building is sized by ``POPULACE_FIT_N_JOBS``, else +by ``n_jobs=-1``, which joblib resolves to the same :func:`joblib.cpu_count`. + +Neither count may change an imputed value. The equality tests fit and draw on +fixed seeds once with one fit job and one prediction worker, then again with +several of either, and require the float64 bytes of every draw to be equal. +Each run records the thread pool the draw used and the ``n_jobs`` each forest +was fit with, so a run that silently fell back to one thread fails. +""" + +from __future__ import annotations + +import os +from collections.abc import Callable, Iterator +from concurrent.futures import ThreadPoolExecutor + +import joblib +import numpy as np +import pandas as pd +import pytest + +from microcosm.fit import QRF, Regime, RegimeGatedQRF +from microcosm.fit import qrf as qrf_module +from microcosm.fit.qrf import _fit_n_jobs, _predict_workers + +PREDICT_WORKERS_ENV = "POPULACE_FIT_PREDICT_WORKERS" +FIT_JOBS_ENV = "POPULACE_FIT_N_JOBS" + +#: The "N" of the 1-versus-N comparisons, for both prediction workers and fit +#: jobs. Threads, so it need not be at most the CI runner's CPU count. +SEVERAL = 4 + +#: Donor and recipient row counts. With ``SEVERAL`` workers the draw splits a +#: recipient pass into ``4 * SEVERAL`` chunks of ceil(rows / 16) rows, the last +#: one shorter; with one worker it runs four larger chunks serially. +DONOR_ROWS = 1_200 +RECIPIENT_ROWS = 1_001 + +N_ESTIMATORS = 8 + +#: (fit jobs, prediction workers) per run. The first is the serial baseline. +SERIAL = ("1", "1") +COMPARED_SETTINGS = ( + pytest.param((str(SEVERAL), "1"), id="several_fit_jobs"), + pytest.param(("1", str(SEVERAL)), id="several_prediction_workers"), + pytest.param((str(SEVERAL), str(SEVERAL)), id="several_of_both"), +) + + +# ---------------------------------------------------------------------------- +# The default prediction worker count +# ---------------------------------------------------------------------------- + + +def _cpu_count_unlike_os(monkeypatch: pytest.MonkeyPatch) -> int: + """Patch :func:`joblib.cpu_count` to a value :func:`os.cpu_count` is not.""" + joblib_cpu_count = (os.cpu_count() or 1) + 3 + + def patched_cpu_count(only_physical_cores: bool = False) -> int: + return joblib_cpu_count + + monkeypatch.setattr(joblib, "cpu_count", patched_cpu_count) + return joblib_cpu_count + + +@pytest.mark.parametrize("configured", [None, "", " "]) +def test_unset_prediction_workers_default_to_joblib_cpu_count( + configured: str | None, monkeypatch: pytest.MonkeyPatch +) -> None: + """An unset or blank override resolves to ``joblib.cpu_count()``.""" + joblib_cpu_count = _cpu_count_unlike_os(monkeypatch) + if configured is None: + monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) + else: + monkeypatch.setenv(PREDICT_WORKERS_ENV, configured) + + assert _predict_workers() == joblib_cpu_count + assert qrf_module.default_predict_workers() == joblib_cpu_count + + +@pytest.mark.parametrize(("configured", "expected"), [("1", 1), ("2", 2), ("7", 7)]) +def test_prediction_worker_override_wins_over_joblib_cpu_count( + configured: str, expected: int, monkeypatch: pytest.MonkeyPatch +) -> None: + """``POPULACE_FIT_PREDICT_WORKERS`` still takes precedence.""" + _cpu_count_unlike_os(monkeypatch) + monkeypatch.setenv(PREDICT_WORKERS_ENV, configured) + + assert _predict_workers() == expected + + +def test_fit_jobs_default_stays_minus_one_under_joblib_cpu_count( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Fit jobs keep the literal ``-1`` that chain states record. + + joblib resolves ``-1`` to its own CPU count when it builds trees, so the + fit already follows :func:`joblib.cpu_count` without recording it. + """ + _cpu_count_unlike_os(monkeypatch) + monkeypatch.delenv(FIT_JOBS_ENV, raising=False) + assert _fit_n_jobs() == -1 + monkeypatch.setenv(FIT_JOBS_ENV, "3") + assert _fit_n_jobs() == 3 + + +# ---------------------------------------------------------------------------- +# Recording which thread pools a run used +# ---------------------------------------------------------------------------- + + +class _PoolRecorder: + """Records every draw thread pool's width and how many chunks it ran.""" + + def __init__(self) -> None: + self.pool_widths: list[int] = [] + self.chunks_per_pool: list[int] = [] + + def executor_class(self) -> type[ThreadPoolExecutor]: + recorder = self + + class RecordingThreadPoolExecutor(ThreadPoolExecutor): + def __init__(self, max_workers: int, *args, **kwargs) -> None: + super().__init__(max_workers, *args, **kwargs) + recorder.pool_widths.append(max_workers) + + def map(self, function, chunk_bounds, *args, **kwargs) -> Iterator: + chunk_bounds = list(chunk_bounds) + recorder.chunks_per_pool.append(len(chunk_bounds)) + return super().map(function, chunk_bounds, *args, **kwargs) + + return RecordingThreadPoolExecutor + + +def _forest_fit_jobs(target_models: dict) -> list[int]: + """The ``n_jobs`` of every forest in a fitted model's targets.""" + return [ + forest.model.n_jobs + for target_model in target_models.values() + for forest in (target_model.positive, target_model.negative) + if forest is not None + ] + + +def _run_under( + monkeypatch: pytest.MonkeyPatch, + setting: tuple[str, str], + run: Callable[[], tuple[dict[str, np.ndarray], list[int]]], +) -> dict[str, np.ndarray]: + """Run a fit and draw under one (fit jobs, prediction workers) setting. + + ``run`` returns the draws by name and the ``n_jobs`` its forests were fit + with. The helper checks those against the setting, and checks that the + draw used a thread pool of the configured width over several chunks, or + no pool at all for one worker. + """ + fit_jobs, predict_workers = setting + monkeypatch.setenv(FIT_JOBS_ENV, fit_jobs) + monkeypatch.setenv(PREDICT_WORKERS_ENV, predict_workers) + recorder = _PoolRecorder() + monkeypatch.setattr(qrf_module, "ThreadPoolExecutor", recorder.executor_class()) + + draws, forest_fit_jobs = run() + + assert forest_fit_jobs, "the run fit no forest" + assert set(forest_fit_jobs) == {int(fit_jobs)} + if int(predict_workers) == 1: + assert recorder.pool_widths == [] + else: + assert recorder.pool_widths, "the draw never used its thread pool" + assert set(recorder.pool_widths) == {int(predict_workers)} + assert min(recorder.chunks_per_pool) > int(predict_workers) + for name, values in draws.items(): + assert values.dtype == np.float64, name + return draws + + +def _assert_byte_identical( + expected: dict[str, np.ndarray], actual: dict[str, np.ndarray] +) -> None: + assert list(actual) == list(expected) + for name, values in expected.items(): + assert actual[name].shape == values.shape, name + assert actual[name].tobytes() == values.tobytes(), name + + +# ---------------------------------------------------------------------------- +# Fixtures: fixed-seed donors and recipients +# ---------------------------------------------------------------------------- + + +def _donor_columns(seed: int) -> dict[str, np.ndarray]: + rng = np.random.default_rng(seed) + x = rng.normal(0.0, 1.0, DONOR_ROWS) + z = rng.uniform(0.0, 10.0, DONOR_ROWS) + positive = np.exp(1.0 + 0.4 * x + 0.1 * z + rng.normal(0.0, 0.5, DONOR_ROWS)) + sign = rng.choice([-1.0, 0.0, 1.0], size=DONOR_ROWS, p=[0.25, 0.35, 0.4]) + signed = sign * np.abs(50.0 * x + 5.0 * z + rng.normal(0.0, 20.0, DONOR_ROWS)) + follower = 2.0 * np.abs(signed) + 10.0 * z + rng.gamma(2.0, 5.0, DONOR_ROWS) + return { + "x": x, + "z": z, + "positive": positive, + "signed": signed, + "follower": follower, + } + + +def _donor_weights(seed: int) -> np.ndarray: + return np.random.default_rng(seed + 1).uniform(0.5, 4.0, DONOR_ROWS) + + +def _recipients(seed: int) -> pd.DataFrame: + rng = np.random.default_rng(seed + 2) + return pd.DataFrame( + { + "x": rng.normal(0.0, 1.1, RECIPIENT_ROWS), + "z": rng.uniform(-0.5, 10.5, RECIPIENT_ROWS), + }, + index=pd.RangeIndex(10_000, 10_000 + RECIPIENT_ROWS), + ) + + +# ---------------------------------------------------------------------------- +# Byte-identical draws for 1 and N prediction workers and fit jobs +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("setting", COMPARED_SETTINGS) +def test_plain_qrf_draws_are_byte_identical_across_thread_counts( + setting: tuple[str, str], make_person_frame, monkeypatch: pytest.MonkeyPatch +) -> None: + """A one-forest, ungated target draws the same bytes at any thread count.""" + frame = make_person_frame(_donor_columns(seed=11), _donor_weights(seed=11)) + recipients = _recipients(seed=11) + + def run() -> tuple[dict[str, np.ndarray], list[int]]: + fitted = QRF(n_estimators=N_ESTIMATORS, seed=31).fit( + frame, ["x", "z"], ["positive"] + ) + assert fitted.regimes() == {"positive": Regime.POSITIVE_ONLY} + draws = fitted.predict(recipients) + return ( + {"positive": draws["positive"].to_numpy()}, + _forest_fit_jobs(fitted._target_models), + ) + + serial = _run_under(monkeypatch, SERIAL, run) + _assert_byte_identical(serial, _run_under(monkeypatch, setting, run)) + + +@pytest.mark.parametrize("setting", COMPARED_SETTINGS) +def test_three_sign_gated_draws_are_byte_identical_across_thread_counts( + setting: tuple[str, str], make_person_frame, monkeypatch: pytest.MonkeyPatch +) -> None: + """A zero, positive and negative target draws the same bytes at any count. + + The target has a sign gate and a forest per sign, and both forests draw + through the thread pool. + """ + frame = make_person_frame(_donor_columns(seed=12), _donor_weights(seed=12)) + recipients = _recipients(seed=12) + + def run() -> tuple[dict[str, np.ndarray], list[int]]: + fitted = RegimeGatedQRF(n_estimators=N_ESTIMATORS, seed=37).fit( + frame, ["x", "z"], ["signed"] + ) + assert fitted.regimes() == {"signed": Regime.THREE_SIGN} + drawn = fitted.predict(recipients)["signed"].to_numpy() + assert (drawn == 0.0).any() and (drawn > 0).any() and (drawn < 0).any() + return {"signed": drawn}, _forest_fit_jobs(fitted._target_models) + + serial = _run_under(monkeypatch, SERIAL, run) + _assert_byte_identical(serial, _run_under(monkeypatch, setting, run)) + + +@pytest.mark.parametrize("setting", COMPARED_SETTINGS) +def test_chained_fit_draw_next_is_byte_identical_across_thread_counts( + setting: tuple[str, str], make_person_frame, monkeypatch: pytest.MonkeyPatch +) -> None: + """Target-at-a-time chain steps draw the same bytes at any thread count. + + Each run starts its own chain, because a chain state refuses a resume + under a different fit job count. The second target conditions on the + first target's raw draws, so a difference in the first would carry on. + """ + frame = make_person_frame(_donor_columns(seed=13), _donor_weights(seed=13)) + recipients = _recipients(seed=13) + targets = ["signed", "follower"] + + def run() -> tuple[dict[str, np.ndarray], list[int]]: + model = RegimeGatedQRF(n_estimators=N_ESTIMATORS, seed=41) + state = model.start_chain(frame, ["x", "z"], targets) + raw_priors = pd.DataFrame(index=recipients.index) + draws: dict[str, np.ndarray] = {} + forest_fit_jobs: list[int] = [] + while not state.is_complete: + step = model.fit_draw_next(frame, recipients, raw_priors, state=state) + draws[step.target] = np.array(step.raw_draw) + raw_priors[step.target] = step.raw_draw + forest_fit_jobs.extend(_forest_fit_jobs(step.fitted._target_models)) + state = step.state + assert list(draws) == targets + return draws, forest_fit_jobs + + serial = _run_under(monkeypatch, SERIAL, run) + _assert_byte_identical(serial, _run_under(monkeypatch, setting, run)) + + +def test_unset_prediction_workers_size_the_draw_pool_from_joblib( + make_person_frame, monkeypatch: pytest.MonkeyPatch +) -> None: + """With the override unset, the draw's pool is ``joblib.cpu_count()`` wide.""" + joblib_cpu_count = _cpu_count_unlike_os(monkeypatch) + frame = make_person_frame(_donor_columns(seed=14), _donor_weights(seed=14)) + monkeypatch.setenv(FIT_JOBS_ENV, "1") + monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) + recorder = _PoolRecorder() + monkeypatch.setattr(qrf_module, "ThreadPoolExecutor", recorder.executor_class()) + + fitted = QRF(n_estimators=N_ESTIMATORS, seed=43).fit( + frame, ["x", "z"], ["positive"] + ) + fitted.predict(_recipients(seed=14)) + + assert recorder.pool_widths == [joblib_cpu_count] diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index 776082a2e7..dfc1edc8d7 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"c145a8a43a9d039ff3062675626513a5f127020be13301196680f3e7894ba1ce","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"322704897a8e9e576efced73663c0970b3db05d177eba8d81630d29e46753ee2","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"322704897a8e9e576efced73663c0970b3db05d177eba8d81630d29e46753ee2"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"528712dc4ca84e4ebfb42f923cbca2e7f849ea4d8a9a0688411dfb97cbedb41f"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"99d453803f091d08dd1f158eac9f804768539e2e82a8cd6ec1e9b03c76e8d767"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"e9023393cb479c22c487569f919997aea7a32c1a6029cb97f808bbaf3c119de6","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"3c1003e93b8b98b2de140aa49a0eb2dc337b7273632d8315043dd485f3130ffc","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"3c1003e93b8b98b2de140aa49a0eb2dc337b7273632d8315043dd485f3130ffc"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"c28e4cbafd0c0ba49e739aa5505c11e3afb770d4153a7fc37e8a58fee4988665"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"7f0a68ba4d88838a3d8970ad6edcfd557bed4af055ceb49f36d8770a920cd73a"}},"seed":947} From b70a864fd6400f69206ccde06e26423b36962318 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:22:59 +0400 Subject: [PATCH 2/8] Label the joblib fallback in the worker identity An unset POPULACE_FIT_PREDICT_WORKERS now records resolution "joblib_cpu_count_fallback". Validation still accepts the older "os_cpu_count_fallback", so identities recorded before stay readable. legacy_primary_qrf_worker_execution_binding maps the new label back to the old one in the frozen schema-4 shape, as it already freezes policy, overrides and bound_names, so the scoring-only relocation of schema-9 pools still finds only its two permitted differences. The older stacked-spine binding builds that schema-4 shape and keeps the old label. Co-Authored-By: Claude Opus 5.5 --- ...redict-workers-joblib-cpu-count.changed.md | 2 +- .../build/us_runtime/stacked_spine.py | 2 + .../build/us_runtime/worker_identity.py | 24 ++- .../us/test_us_qrf_predict_worker_default.py | 139 +++++++++++++++++- 4 files changed, 157 insertions(+), 10 deletions(-) diff --git a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md index 9c2909b17a..dda0616099 100644 --- a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md +++ b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md @@ -1 +1 @@ -Size the QRF draw's thread pool from the CPUs the process may use. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. The primary-QRF worker identity (`worker_identity.py`) and the older binding in `stacked_spine.py` record the same value, and the identity's cache now keys an unset variable by that value. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. A base run interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. +Size the QRF draw's thread pool from the CPUs the process may use. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. The primary-QRF worker identity (`worker_identity.py`) and the older binding in `stacked_spine.py` record the same value, and the identity's cache now keys an unset variable by that value. The identity labels that fallback `resolution: "joblib_cpu_count_fallback"`; identities recorded before carry `"os_cpu_count_fallback"` and still validate, and the frozen schema-4 worker shape keeps the old label, so the scoring-only relocation of schema-9 pools still finds only its two permitted differences. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. A base run interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py index 2d0aca9155..b643dba21e 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py @@ -6030,6 +6030,8 @@ def _legacy_primary_qrf_worker_execution_binding() -> dict[str, object]: predict_workers_raw = os.environ.get("POPULACE_FIT_PREDICT_WORKERS") if predict_workers_raw is None or not predict_workers_raw.strip(): predict_workers = default_predict_workers() + # This builds the frozen schema-4 shape, whose label for the fallback + # predates the joblib.cpu_count() default. predict_workers_source = "os_cpu_count_fallback" else: try: 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 e54c880146..3c6f6f2eaf 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 @@ -62,6 +62,20 @@ "POPULACE_FIT_N_JOBS", "POPULACE_FIT_PREDICT_WORKERS", ) +#: ``resolution`` of an unset POPULACE_FIT_PREDICT_WORKERS: the QRF draw's +#: default width, ``joblib.cpu_count()``. +_PREDICT_WORKERS_FALLBACK = "joblib_cpu_count_fallback" +#: The same field as identities recorded it while the default was +#: ``os.cpu_count()``. Those records still validate, and the frozen schema-4 +#: worker shape (``legacy_primary_qrf_worker_execution_binding``) keeps it. +_SCHEMA_4_PREDICT_WORKERS_FALLBACK = "os_cpu_count_fallback" +_PREDICT_WORKERS_RESOLUTIONS = frozenset( + { + "environment_override", + _PREDICT_WORKERS_FALLBACK, + _SCHEMA_4_PREDICT_WORKERS_FALLBACK, + } +) _TORCH_BACKEND_ENTRY_POINT_GROUP = "torch.backends" _WORKER_ENVIRONMENT_OVERRIDES = { "TORCH_DEVICE_BACKEND_AUTOLOAD": "0", @@ -1259,7 +1273,7 @@ def _semantic_environment() -> dict[str, object]: predict_workers_raw = os.environ.get("POPULACE_FIT_PREDICT_WORKERS") if _predict_workers_unset(predict_workers_raw): predict_workers = _default_predict_workers() - predict_workers_source = "os_cpu_count_fallback" + predict_workers_source = _PREDICT_WORKERS_FALLBACK else: try: predict_workers = int(predict_workers_raw) @@ -1639,8 +1653,7 @@ def _validate_semantic_identity( or isinstance(predict.get("resolved"), bool) or not isinstance(predict.get("resolved"), int) or int(predict["resolved"]) < 1 - or predict.get("resolution") - not in {"environment_override", "os_cpu_count_fallback"} + or predict.get("resolution") not in _PREDICT_WORKERS_RESOLUTIONS ): raise ValueError(f"{boundary} resolved worker controls are malformed.") return value @@ -1763,6 +1776,11 @@ def legacy_primary_qrf_worker_execution_binding( environment["policy"] = "inherit_parent_environment_with_bound_fit_controls" environment["overrides"] = {} environment["bound_names"] = list(_SEMANTIC_ENVIRONMENT_NAMES) + # Schema-4 code labelled an unset prediction-worker count with the + # os.cpu_count() fallback's name; keep that label in this frozen shape. + predict_workers = environment["semantic_controls"]["POPULACE_FIT_PREDICT_WORKERS"] + if predict_workers["resolution"] == _PREDICT_WORKERS_FALLBACK: + predict_workers["resolution"] = _SCHEMA_4_PREDICT_WORKERS_FALLBACK return { "module": worker_module["name"], "argv_template": [str(executable), *argv[1:]], diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py index 8824e9d6ea..df30b76cbf 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py @@ -6,18 +6,26 @@ ``stacked_spine.py`` record that same width, and the environment variable still overrides it. Each test patches ``joblib.cpu_count`` to a value that ``os.cpu_count()``, the earlier default, does not return. + +The identity labels that fallback ``"joblib_cpu_count_fallback"``. Identities +written before carry ``"os_cpu_count_fallback"`` and still validate, and the +schema-4 worker shape that legacy pools recorded keeps the old label, so the +scoring-only relocation of those pools still compares equal. """ # ruff: noqa: F403, F405 from __future__ import annotations import os +from copy import deepcopy import joblib from test_support.microcosm_build.us_stacked_spine import * PREDICT_WORKERS_ENV = "POPULACE_FIT_PREDICT_WORKERS" +JOBLIB_FALLBACK = "joblib_cpu_count_fallback" +SCHEMA_4_FALLBACK = "os_cpu_count_fallback" def _patch_joblib_cpu_count(monkeypatch: pytest.MonkeyPatch, value: int) -> None: @@ -57,19 +65,35 @@ def _stacked_spine_predict_controls() -> dict[str, object]: ) -@pytest.mark.parametrize("read_controls", PREDICT_CONTROL_READERS) +@pytest.mark.parametrize( + ("read_controls", "expected_resolution"), + ( + pytest.param( + _worker_identity_predict_controls, JOBLIB_FALLBACK, id="worker_identity" + ), + # The older binding builds the frozen schema-4 shape, so it keeps the + # label that shape has always carried. + pytest.param( + _stacked_spine_predict_controls, SCHEMA_4_FALLBACK, id="stacked_spine" + ), + ), +) @pytest.mark.parametrize("configured", [None, "", " "]) def test_unset_predict_workers_record_joblib_cpu_count( - read_controls, configured: str | None, monkeypatch: pytest.MonkeyPatch + read_controls, + expected_resolution: str, + configured: str | None, + monkeypatch: pytest.MonkeyPatch, ) -> None: joblib_cpu_count = _cpu_count_unlike_os() _patch_joblib_cpu_count(monkeypatch, joblib_cpu_count) _set_predict_workers(monkeypatch, configured) - controls = read_controls() - - assert controls["configured"] == configured - assert controls["resolved"] == joblib_cpu_count + assert read_controls() == { + "configured": configured, + "resolved": joblib_cpu_count, + "resolution": expected_resolution, + } @pytest.mark.parametrize("read_controls", PREDICT_CONTROL_READERS) @@ -114,3 +138,106 @@ def test_worker_identity_memo_binds_unset_predict_worker_default( _patch_joblib_cpu_count(monkeypatch, smaller) assert worker_identity_module.primary_qrf_worker_semantic_identity() is first assert len(calls) == 2 + + +def _live_binding_with_unset_predict_workers( + monkeypatch: pytest.MonkeyPatch, joblib_cpu_count: int +) -> dict[str, object]: + monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) + _patch_joblib_cpu_count(monkeypatch, joblib_cpu_count) + return worker_identity_module.primary_qrf_worker_execution_binding() + + +def _with_resolution(binding: dict[str, object], label: str) -> dict[str, object]: + """A copy of ``binding`` whose fallback label is ``label``, re-digested.""" + relabelled = deepcopy(binding) + semantic = relabelled["semantic_identity"] + semantic["environment"]["semantic_controls"][PREDICT_WORKERS_ENV]["resolution"] = ( + label + ) + relabelled["semantic_identity_sha256"] = worker_identity_module._canonical_sha256( + semantic + ) + return relabelled + + +@pytest.mark.parametrize("label", [JOBLIB_FALLBACK, SCHEMA_4_FALLBACK]) +def test_worker_identity_validation_accepts_both_fallback_labels( + _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch, label: str +) -> None: + """Identities recorded before the joblib default still validate.""" + binding = _live_binding_with_unset_predict_workers( + monkeypatch, _cpu_count_unlike_os() + ) + + worker_identity_module.validate_primary_qrf_worker_execution_binding( + _with_resolution(binding, label), boundary="fallback label" + ) + + +def test_worker_identity_validation_refuses_an_unknown_fallback_label( + _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch +) -> None: + binding = _live_binding_with_unset_predict_workers( + monkeypatch, _cpu_count_unlike_os() + ) + + with pytest.raises(ValueError, match="resolved worker controls are malformed"): + worker_identity_module.validate_primary_qrf_worker_execution_binding( + _with_resolution(binding, "process_cpu_count_fallback"), + boundary="fallback label", + ) + + +def test_schema_4_projection_keeps_the_os_cpu_count_fallback_label( + _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch +) -> None: + """The legacy projection matches what the schema-4 code records. + + The scoring-only relocation of a schema-9 pool allows only two differences + between the pool's recorded schema-4 worker and this projection of the live + worker. ``stacked_spine``'s older binding is that schema-4 recorder. + """ + joblib_cpu_count = _cpu_count_unlike_os() + binding = _live_binding_with_unset_predict_workers(monkeypatch, joblib_cpu_count) + semantic = binding["semantic_identity"] + live_controls = semantic["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] + assert live_controls["resolution"] == JOBLIB_FALLBACK + + projected = worker_identity_module.legacy_primary_qrf_worker_execution_binding( + semantic_identity=semantic + ) + + assert projected["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] == { + "configured": None, + "resolved": joblib_cpu_count, + "resolution": SCHEMA_4_FALLBACK, + } + assert live_controls["resolution"] == JOBLIB_FALLBACK + schema_4_recorded = ( + stacked_spine_module._legacy_primary_qrf_worker_execution_binding() + ) + assert ( + worker_identity_module._legacy_worker_execution_mismatch_paths( + schema_4_recorded, projected + ) + == () + ) + + +def test_schema_4_projection_keeps_an_override_label( + _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch +) -> None: + _patch_joblib_cpu_count(monkeypatch, _cpu_count_unlike_os()) + monkeypatch.setenv(PREDICT_WORKERS_ENV, "2") + semantic = worker_identity_module.primary_qrf_worker_semantic_identity() + + projected = worker_identity_module.legacy_primary_qrf_worker_execution_binding( + semantic_identity=semantic + ) + + assert projected["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] == { + "configured": "2", + "resolved": 2, + "resolution": "environment_override", + } From 3ef18db118be1384794f042902fa5a039628221c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:40:21 +0400 Subject: [PATCH 3/8] Address review round 1 of the joblib worker default - The frozen schema-4 projection reports an unset prediction-worker count as schema-4 code recorded it, os.cpu_count() under "os_cpu_count_fallback", so the scoring-only relocation of schema-9 pools compares what it compared before. The live identity still records joblib.cpu_count(). - The older stacked-spine binding records "joblib_cpu_count_fallback". - The worker identity reads joblib.cpu_count() once per cache entry, so the identity records the count its key holds. - A non-integer LOKY_MAX_CPU_COUNT fails with an error naming it. - Three test caches key by the count the identity uses instead of os.cpu_count(), so a mid-session LOKY_MAX_CPU_COUNT change recomputes. - Docstrings: the joblib count's floor of 1, cgroup v1 and v2 quotas, and joblib's serial mode. Re-pinned the attested fit.qrf hashes: repin, coverage (41/41), repin, --check clean, then graph_parity_repin fit.qrf under Python 3.14. Co-Authored-By: Claude Opus 5.5 --- ...redict-workers-joblib-cpu-count.changed.md | 2 +- docs/evidence/spec-engine/us-f0-coverage.json | 16 ++-- .../build/spec_engine/inventory_coverage.py | 4 +- .../build/us_runtime/stacked_spine.py | 4 +- .../build/us_runtime/worker_identity.py | 32 ++++++-- .../us/test_spec_engine_coverage_tool.py | 2 +- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_multispine_pool_h5_io.py | 2 +- .../us/test_us_qrf_predict_worker_default.py | 78 ++++++++++++++----- .../us/test_us_multispine_pool_tool.py | 2 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 30 +++++-- .../shared/test_qrf_worker_counts.py | 18 ++++- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- .../spec_engine_inventory_coverage.py | 2 +- 14 files changed, 140 insertions(+), 56 deletions(-) diff --git a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md index dda0616099..0d0f1b56fa 100644 --- a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md +++ b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md @@ -1 +1 @@ -Size the QRF draw's thread pool from the CPUs the process may use. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. The primary-QRF worker identity (`worker_identity.py`) and the older binding in `stacked_spine.py` record the same value, and the identity's cache now keys an unset variable by that value. The identity labels that fallback `resolution: "joblib_cpu_count_fallback"`; identities recorded before carry `"os_cpu_count_fallback"` and still validate, and the frozen schema-4 worker shape keeps the old label, so the scoring-only relocation of schema-9 pools still finds only its two permitted differences. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. A base run interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. +Size the QRF draw's thread pool from the CPUs the process may use. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, and 1 when joblib has turned multiprocessing off, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. The primary-QRF worker identity (`worker_identity.py`) and the older binding in `stacked_spine.py` record the same value, and the identity's cache now keys an unset variable by that value. Both label that fallback `resolution: "joblib_cpu_count_fallback"`; identities recorded before carry `"os_cpu_count_fallback"` and still validate. The frozen schema-4 worker shape that the scoring-only relocation of schema-9 pools compares with their sealed records reports an unset count as that code recorded it, the host's `os.cpu_count()` under the old label, so that comparison is unchanged. A `LOKY_MAX_CPU_COUNT` that is not an integer, which joblib refuses, now fails with an error naming it. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. A base run interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index d67a1e00ec..a930040990 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": "dceefacd3341afbade42936752f33829e084a5fdf526ace4d1b9866e199e7ecb", - "protocol_sha256": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265" + "map_sha256": "1452f5d308ed2119faf6cdf00d727c62d6888b677f3807f798c11b45e324c1be", + "protocol_sha256": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814" }, "failures": [], "observed": { - "map_sha256": "dceefacd3341afbade42936752f33829e084a5fdf526ace4d1b9866e199e7ecb", - "protocol_sha256": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265" + "map_sha256": "1452f5d308ed2119faf6cdf00d727c62d6888b677f3807f798c11b45e324c1be", + "protocol_sha256": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265", + "implementation_sha256": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265", + "implementation_sha256": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "f5ac251cebcbaf97d8f29fe9cea477126e381602b66f7b2c956995f931b5de75" + "spec_sha256": "bbee1e2239ed6fc47ab825c769a9f7364bc58030ed762c5eb24dcbf2e0e9af35" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "f5ac251cebcbaf97d8f29fe9cea477126e381602b66f7b2c956995f931b5de75" + "spec_sha256": "bbee1e2239ed6fc47ab825c769a9f7364bc58030ed762c5eb24dcbf2e0e9af35" }, "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 7a21968a75..05e4757959 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 @@ -404,8 +404,8 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The QRF draw's default thread count, joblib.cpu_count() in place of # os.cpu_count() in microcosm.fit.qrf, moves both again; no draw changes. - "seed_map": "dceefacd3341afbade42936752f33829e084a5fdf526ace4d1b9866e199e7ecb", - "seed_protocol": "0d2036d9b0d4cf890b15e7454326544ba426ebca20be45288c429d8e35e65265", + "seed_map": "1452f5d308ed2119faf6cdf00d727c62d6888b677f3807f798c11b45e324c1be", + "seed_protocol": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py index b643dba21e..fb1ff09496 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py @@ -6030,9 +6030,7 @@ def _legacy_primary_qrf_worker_execution_binding() -> dict[str, object]: predict_workers_raw = os.environ.get("POPULACE_FIT_PREDICT_WORKERS") if predict_workers_raw is None or not predict_workers_raw.strip(): predict_workers = default_predict_workers() - # This builds the frozen schema-4 shape, whose label for the fallback - # predates the joblib.cpu_count() default. - predict_workers_source = "os_cpu_count_fallback" + predict_workers_source = "joblib_cpu_count_fallback" else: try: predict_workers = int(predict_workers_raw) 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 3c6f6f2eaf..5d9b8481e2 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 @@ -67,7 +67,8 @@ _PREDICT_WORKERS_FALLBACK = "joblib_cpu_count_fallback" #: The same field as identities recorded it while the default was #: ``os.cpu_count()``. Those records still validate, and the frozen schema-4 -#: worker shape (``legacy_primary_qrf_worker_execution_binding``) keeps it. +#: worker shape (``legacy_primary_qrf_worker_execution_binding``) records an +#: unset count as that code did: ``os.cpu_count()`` under this label. _SCHEMA_4_PREDICT_WORKERS_FALLBACK = "os_cpu_count_fallback" _PREDICT_WORKERS_RESOLUTIONS = frozenset( { @@ -1253,7 +1254,12 @@ def _predict_workers_unset(configured: str | None) -> bool: return configured is None or not configured.strip() -def _semantic_environment() -> dict[str, object]: +def _semantic_environment( + predict_workers_fallback: int | None = None, +) -> dict[str, object]: + """Bind the fit controls; an unset prediction-worker count records + ``predict_workers_fallback`` when given, else reads the QRF default.""" + fit_jobs_raw = os.environ.get("POPULACE_FIT_N_JOBS") if fit_jobs_raw is None: fit_jobs = -1 @@ -1272,7 +1278,11 @@ def _semantic_environment() -> dict[str, object]: ) predict_workers_raw = os.environ.get("POPULACE_FIT_PREDICT_WORKERS") if _predict_workers_unset(predict_workers_raw): - predict_workers = _default_predict_workers() + predict_workers = ( + _default_predict_workers() + if predict_workers_fallback is None + else predict_workers_fallback + ) predict_workers_source = _PREDICT_WORKERS_FALLBACK else: try: @@ -1353,9 +1363,13 @@ def primary_qrf_worker_semantic_identity( _require_sha256(uv_lock_sha256, boundary="primary-QRF worker lock") key = _primary_qrf_worker_identity_cache_key(uv_lock_sha256) if key not in _PRIMARY_QRF_WORKER_IDENTITY_CACHE: + # The identity records the count the key holds, read once, so a + # change during the attestation cannot file it under another count. + predict_workers_fallback = key[3] _PRIMARY_QRF_WORKER_IDENTITY_CACHE[key] = ( _uncached_primary_qrf_worker_semantic_identity( - uv_lock_sha256=uv_lock_sha256 + uv_lock_sha256=uv_lock_sha256, + predict_workers_fallback=predict_workers_fallback, ) ) return _PRIMARY_QRF_WORKER_IDENTITY_CACHE[key] @@ -1364,6 +1378,7 @@ def primary_qrf_worker_semantic_identity( def _uncached_primary_qrf_worker_semantic_identity( *, uv_lock_sha256: str | None = None, + predict_workers_fallback: int | None = None, ) -> dict[str, object]: """Build the canonical worker identity, excluding all launcher aliases.""" @@ -1395,7 +1410,7 @@ def _uncached_primary_qrf_worker_semantic_identity( "Primary-QRF worker cannot read its loaded Python runtime." ) from error pyvenv_config = _canonical_pyvenv_config() - environment = _semantic_environment() + environment = _semantic_environment(predict_workers_fallback) import_trace = _clean_worker_import_trace() namespace_rows = _worker_package_resource_rows(import_trace) imports_sha256 = _canonical_sha256( @@ -1776,10 +1791,13 @@ def legacy_primary_qrf_worker_execution_binding( environment["policy"] = "inherit_parent_environment_with_bound_fit_controls" environment["overrides"] = {} environment["bound_names"] = list(_SEMANTIC_ENVIRONMENT_NAMES) - # Schema-4 code labelled an unset prediction-worker count with the - # os.cpu_count() fallback's name; keep that label in this frozen shape. + # Schema-4 code resolved an unset prediction-worker count to this host's + # os.cpu_count() under the label below, and the sealed records compared + # with this projection hold that. The live draw uses joblib.cpu_count(), + # which the attested semantic identity binds; the count changes no draw. predict_workers = environment["semantic_controls"]["POPULACE_FIT_PREDICT_WORKERS"] if predict_workers["resolution"] == _PREDICT_WORKERS_FALLBACK: + predict_workers["resolved"] = os.cpu_count() or 1 predict_workers["resolution"] = _SCHEMA_4_PREDICT_WORKERS_FALLBACK return { "module": worker_module["name"], diff --git a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py index 394d432ee2..61ed20ecaf 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py @@ -44,7 +44,7 @@ def binding() -> dict[str, object]: cached( os.environ.get("POPULACE_FIT_N_JOBS"), os.environ.get("POPULACE_FIT_PREDICT_WORKERS"), - os.cpu_count(), + worker_identity_module._default_predict_workers(), ) ) 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 25a17754e9..996f5c30cf 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 @@ -35,7 +35,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # The QRF draw's default thread count, joblib.cpu_count() in # microcosm.fit.qrf, moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "6a7728eddeb6be4d2e6a087e7d0eb403469730ef4d576c406650b77ca6e11699" + "1b9b05539a15598c392feeea440e460888afa19c974270945f4a1bd08a26af8e" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py index ccfda92e6b..ed2abbc8fd 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py @@ -1314,7 +1314,7 @@ def _canonical_stacked_late_dag_receipt() -> dict[str, object]: _cached_canonical_stacked_late_dag_receipt( worker_identity_module.os.environ.get("POPULACE_FIT_N_JOBS"), worker_identity_module.os.environ.get("POPULACE_FIT_PREDICT_WORKERS"), - worker_identity_module.os.cpu_count(), + worker_identity_module._default_predict_workers(), ) ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py index df30b76cbf..e2e7e5714f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py @@ -7,10 +7,11 @@ still overrides it. Each test patches ``joblib.cpu_count`` to a value that ``os.cpu_count()``, the earlier default, does not return. -The identity labels that fallback ``"joblib_cpu_count_fallback"``. Identities -written before carry ``"os_cpu_count_fallback"`` and still validate, and the -schema-4 worker shape that legacy pools recorded keeps the old label, so the -scoring-only relocation of those pools still compares equal. +Both label that fallback ``"joblib_cpu_count_fallback"``. Identities written +before carry ``"os_cpu_count_fallback"`` and still validate. The schema-4 +worker shape that legacy pools recorded is projected as that code recorded it, +the host's ``os.cpu_count()`` under the old label, so the scoring-only +relocation of those pools compares what it compared before. """ # ruff: noqa: F403, F405 @@ -71,10 +72,8 @@ def _stacked_spine_predict_controls() -> dict[str, object]: pytest.param( _worker_identity_predict_controls, JOBLIB_FALLBACK, id="worker_identity" ), - # The older binding builds the frozen schema-4 shape, so it keeps the - # label that shape has always carried. pytest.param( - _stacked_spine_predict_controls, SCHEMA_4_FALLBACK, id="stacked_spine" + _stacked_spine_predict_controls, JOBLIB_FALLBACK, id="stacked_spine" ), ), ) @@ -189,42 +188,81 @@ def test_worker_identity_validation_refuses_an_unknown_fallback_label( ) -def test_schema_4_projection_keeps_the_os_cpu_count_fallback_label( +def test_schema_4_projection_records_an_unset_count_as_schema_4_code_did( _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch ) -> None: - """The legacy projection matches what the schema-4 code records. + """The legacy projection reports ``os.cpu_count()`` under the old label. - The scoring-only relocation of a schema-9 pool allows only two differences - between the pool's recorded schema-4 worker and this projection of the live - worker. ``stacked_spine``'s older binding is that schema-4 recorder. + Schema-4 code resolved an unset count to ``os.cpu_count()`` and labelled it + ``"os_cpu_count_fallback"``. The scoring-only relocation of a schema-9 pool + compares that record with this projection of the live worker and allows + only the two relocated interpreter paths to differ. The live identity + itself still records the ``joblib.cpu_count()`` the draw uses. """ joblib_cpu_count = _cpu_count_unlike_os() binding = _live_binding_with_unset_predict_workers(monkeypatch, joblib_cpu_count) semantic = binding["semantic_identity"] live_controls = semantic["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] - assert live_controls["resolution"] == JOBLIB_FALLBACK + live_before = deepcopy(live_controls) projected = worker_identity_module.legacy_primary_qrf_worker_execution_binding( semantic_identity=semantic ) - assert projected["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] == { + schema_4_controls = { "configured": None, - "resolved": joblib_cpu_count, + "resolved": os.cpu_count() or 1, "resolution": SCHEMA_4_FALLBACK, } - assert live_controls["resolution"] == JOBLIB_FALLBACK - schema_4_recorded = ( - stacked_spine_module._legacy_primary_qrf_worker_execution_binding() + assert ( + projected["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] + == schema_4_controls + ) + assert ( + live_controls + == live_before + == { + "configured": None, + "resolved": joblib_cpu_count, + "resolution": JOBLIB_FALLBACK, + } + ) + relocated_python = "/relocated/campaign/.venv/bin/python" + recorded = deepcopy(projected) + recorded["argv_template"][0] = relocated_python + recorded["interpreter"]["executable"] = relocated_python + recorded["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] = dict( + schema_4_controls ) assert ( worker_identity_module._legacy_worker_execution_mismatch_paths( - schema_4_recorded, projected + recorded, projected ) - == () + == worker_identity_module.LEGACY_WORKER_PERMITTED_MISMATCHES ) +def test_worker_identity_records_the_count_it_is_cached_under( + _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch +) -> None: + """The cache key and the identity read ``joblib.cpu_count()`` once.""" + monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) + first_count, later_count = _cpu_count_unlike_os(3), _cpu_count_unlike_os(5) + calls = [] + + def changing_cpu_count(only_physical_cores: bool = False) -> int: + calls.append(None) + return first_count if len(calls) == 1 else later_count + + monkeypatch.setattr(joblib, "cpu_count", changing_cpu_count) + + identity = worker_identity_module.primary_qrf_worker_semantic_identity() + + controls = identity["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] + assert controls["resolved"] == first_count + assert len(calls) == 1 + + def test_schema_4_projection_keeps_an_override_label( _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch ) -> None: 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 1a5c353f4d..e73deea4e8 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 @@ -365,7 +365,7 @@ def capture_equality(expected: object, actual: object) -> None: # solve and ssi_take_up, and the calibration contract's renamed modes. # The QRF draw's default thread count, joblib.cpu_count() in # microcosm.fit.qrf, moves it again. - "spec_sha256": "f5ac251cebcbaf97d8f29fe9cea477126e381602b66f7b2c956995f931b5de75", + "spec_sha256": "bbee1e2239ed6fc47ab825c769a9f7364bc58030ed762c5eb24dcbf2e0e9af35", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 4caba55c2c..f6fd219c26 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -1414,17 +1414,33 @@ def default_predict_workers() -> int: """The draw's thread-pool width when ``POPULACE_FIT_PREDICT_WORKERS`` is unset. :func:`joblib.cpu_count` is the smallest of the machine's logical CPU - count, the process's CPU affinity mask, a Linux cgroup CPU quota - (``cpu.max``) and ``LOKY_MAX_CPU_COUNT``. :func:`os.cpu_count`, the - default before it, counts only the machine's CPUs: in a container held to - a CPU quota it started one thread per host CPU, and the quota then paused - them. The value can change within a process (when ``LOKY_MAX_CPU_COUNT`` - or the affinity mask changes), so callers read it when they need it. + count, the process's CPU affinity mask, a Linux cgroup CPU quota (cgroup + v2 ``cpu.max`` or v1 ``cpu.cfs_quota_us``, rounded up) and + ``LOKY_MAX_CPU_COUNT``, and at least 1. It is 1 when joblib has turned + multiprocessing off (``JOBLIB_MULTIPROCESSING=0``, or no working + semaphores), as tree building with ``n_jobs=-1`` then also runs on one + thread. :func:`os.cpu_count`, the default before it, counts only the + machine's CPUs: in a container held to a CPU quota it started one thread + per host CPU, and the quota then paused them. The value can change within + a process (when ``LOKY_MAX_CPU_COUNT`` or the affinity mask changes), so + callers read it when they need it. The primary-QRF worker identity records this value for an unset override (``microcosm.build.us_runtime.worker_identity``), so both read it here. + + Raises: + ValueError: If ``LOKY_MAX_CPU_COUNT`` is not an integer, which joblib + refuses, or joblib cannot read the cgroup CPU quota. """ - return joblib.cpu_count() + try: + return joblib.cpu_count() + except ValueError as error: + raise ValueError( + "Cannot size the QRF draw's thread pool: joblib.cpu_count() failed " + f"with LOKY_MAX_CPU_COUNT={os.environ.get('LOKY_MAX_CPU_COUNT')!r} " + f"({error}). Set LOKY_MAX_CPU_COUNT to an integer, or set " + f"{_PREDICT_WORKERS_ENV}." + ) from error def _predict_workers() -> int: diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py index f0a1934355..259bdb09ac 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py @@ -9,8 +9,8 @@ Neither count may change an imputed value. The equality tests fit and draw on fixed seeds once with one fit job and one prediction worker, then again with several of either, and require the float64 bytes of every draw to be equal. -Each run records the thread pool the draw used and the ``n_jobs`` each forest -was fit with, so a run that silently fell back to one thread fails. +Each run records the thread pool the draw used, so a draw that silently ran +on one thread fails, and the ``n_jobs`` each forest was configured with. """ from __future__ import annotations @@ -94,6 +94,20 @@ def test_prediction_worker_override_wins_over_joblib_cpu_count( assert _predict_workers() == expected +@pytest.mark.parametrize("malformed", ["", "4.0", "four"]) +def test_malformed_loky_max_cpu_count_is_named_in_the_error( + malformed: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """joblib refuses a non-integer ``LOKY_MAX_CPU_COUNT``; the error says so.""" + monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) + monkeypatch.setenv("LOKY_MAX_CPU_COUNT", malformed) + + with pytest.raises(ValueError, match="LOKY_MAX_CPU_COUNT"): + _predict_workers() + monkeypatch.setenv(PREDICT_WORKERS_ENV, "2") + assert _predict_workers() == 2 + + def test_fit_jobs_default_stays_minus_one_under_joblib_cpu_count( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index dfc1edc8d7..27bfa4dd5c 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"e9023393cb479c22c487569f919997aea7a32c1a6029cb97f808bbaf3c119de6","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"3c1003e93b8b98b2de140aa49a0eb2dc337b7273632d8315043dd485f3130ffc","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"3c1003e93b8b98b2de140aa49a0eb2dc337b7273632d8315043dd485f3130ffc"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"c28e4cbafd0c0ba49e739aa5505c11e3afb770d4153a7fc37e8a58fee4988665"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"7f0a68ba4d88838a3d8970ad6edcfd557bed4af055ceb49f36d8770a920cd73a"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"0f04fbf25e743af4f09830c56dff10f497c9743dfc4def03193829da3115e00f","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"b7966fdb66ace4deb3074e651901b91d490f15ab09594e2bad9f1bdd1298c864","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"b7966fdb66ace4deb3074e651901b91d490f15ab09594e2bad9f1bdd1298c864"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"08c01581e921c997d591d86175287aa49420b40c3c09c43c7a2752b2c55eb94a"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"e1919c2c9c075115252f1ebd5756b49837e18a6716822e862d3a5c2c6bd9e84c"}},"seed":947} diff --git a/test_support/microcosm_build/spec_engine_inventory_coverage.py b/test_support/microcosm_build/spec_engine_inventory_coverage.py index 5f4dea19f1..b44cfd0a03 100644 --- a/test_support/microcosm_build/spec_engine_inventory_coverage.py +++ b/test_support/microcosm_build/spec_engine_inventory_coverage.py @@ -90,7 +90,7 @@ def binding() -> dict[str, object]: cached( os.environ.get("POPULACE_FIT_N_JOBS"), os.environ.get("POPULACE_FIT_PREDICT_WORKERS"), - os.cpu_count(), + worker_identity_module._default_predict_workers(), ) ) From eac8a2880a7cb5178cadeab7d68fe20e783c67b6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:19:28 +0400 Subject: [PATCH 4/8] Stop comparing thread counts in the primary-QRF worker identity With POPULACE_FIT_PREDICT_WORKERS unset, the prediction-worker count now comes from the machine (joblib.cpu_count()). The worker identity compared the resolved count, so a pool built on a host with more CPUs than the release tool's LOKY_MAX_CPU_COUNT cap of 16, or a checkpoint resumed on another host, was refused although the count changes no imputed value. The worker binding is now schema 2. POPULACE_FIT_N_JOBS and POPULACE_FIT_PREDICT_WORKERS are recorded in a new audit_thread_controls field next to audit_aliases, outside the semantic identity that pool loading, checkpoint resume, the pool's checkpoint identity and the spec engine's worker resolution compare. Building a binding still refuses a malformed count. Schema-1 bindings still validate and are refused as a changed identity. The semantic identity is cached per lock only. The spec template names schema 2 and the new field; pins re-pinned. The scoring-only relocation of the sealed schema-9 pool keeps comparing its frozen schema-4 shape, thread counts included. Co-Authored-By: Claude Opus 5.5 --- ...redict-workers-joblib-cpu-count.changed.md | 4 +- docs/evidence/spec-engine/us-f0-coverage.json | 4 +- .../build/spec_engine/imputation_semantics.py | 5 +- .../build/spec_engine/inventory_coverage.py | 11 +- .../spec_engine/schema/imputation.schema.json | 17 +- .../microcosm/build/us/spec/imputation.yaml | 4 +- .../build/us_runtime/stacked_spine.py | 10 +- .../build/us_runtime/worker_identity.py | 323 ++++++----- .../engine_contract/us/test_us_spec_bundle.py | 5 +- .../us/test_us_qrf_predict_worker_default.py | 79 +-- .../us/test_us_qrf_worker_thread_controls.py | 515 ++++++++++++++++++ .../engine_free/us/test_us_stacked_spine.py | 41 +- tools/us_bundle_generation/imputation.py | 5 +- 13 files changed, 799 insertions(+), 224 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py diff --git a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md index 0d0f1b56fa..36173314de 100644 --- a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md +++ b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md @@ -1 +1,3 @@ -Size the QRF draw's thread pool from the CPUs the process may use. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, and 1 when joblib has turned multiprocessing off, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. The primary-QRF worker identity (`worker_identity.py`) and the older binding in `stacked_spine.py` record the same value, and the identity's cache now keys an unset variable by that value. Both label that fallback `resolution: "joblib_cpu_count_fallback"`; identities recorded before carry `"os_cpu_count_fallback"` and still validate. The frozen schema-4 worker shape that the scoring-only relocation of schema-9 pools compares with their sealed records reports an unset count as that code recorded it, the host's `os.cpu_count()` under the old label, so that comparison is unchanged. A `LOKY_MAX_CPU_COUNT` that is not an integer, which joblib refuses, now fails with an error naming it. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. A base run interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. +Size the QRF draw's thread pool from the CPUs the process may use, and stop comparing thread counts when a recorded primary-QRF worker is checked against the live one. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, and 1 when joblib has turned multiprocessing off, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. A `LOKY_MAX_CPU_COUNT` that is not an integer, which joblib refuses, now fails with an error naming it. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. + +Because the default count now follows the machine, the primary-QRF worker binding (`worker_identity.py`, now schema 2) records `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` in a new `audit_thread_controls` field next to the interpreter paths in `audit_aliases`, and no longer in its semantic identity. Loading a pool for release or scoring, resuming the primary-QRF checkpoint, the pool's checkpoint identity and the spec engine's worker resolution compare only the semantic identity, so a pool built on a host with 18 usable CPUs now loads under the release tool's `LOKY_MAX_CPU_COUNT` cap of 16, and a pool build and a release may set different thread counts. Building the binding still refuses a malformed count. An unset prediction-worker count is recorded as `resolution: "joblib_cpu_count_fallback"`; `"os_cpu_count_fallback"` still validates. Schema-1 bindings still validate, and a pool that holds one is refused because its worker identity changed. The semantic identity is now cached per lock only. The spec template for the worker binding (`imputation.yaml` and `imputation.schema.json`) names schema 2 and the new field. The frozen schema-4 shape that the scoring-only relocation of schema-9 pools compares with their sealed records keeps the counts where that code recorded them, an unset count as the host's `os.cpu_count()`, so that comparison is unchanged and still includes the counts. The unused older binding in `stacked_spine.py` records the joblib default under the new label. A base run or pool build interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index a930040990..0d024b43ae 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1324,12 +1324,12 @@ ], "expected": { "nodes": 38, - "sha256": "1b208fff4f6d878c522147fee617177544bda8963c940f98a4bfc37507cb955f" + "sha256": "ea67473e331b8849b3b48ecac89509661d904f2356ff2161a04715e569c79e91" }, "failures": [], "observed": { "nodes": 38, - "sha256": "1b208fff4f6d878c522147fee617177544bda8963c940f98a4bfc37507cb955f" + "sha256": "ea67473e331b8849b3b48ecac89509661d904f2356ff2161a04715e569c79e91" }, "status": "covered" }, diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/imputation_semantics.py b/packages/microcosm-build/src/microcosm/build/spec_engine/imputation_semantics.py index 2cbbdacbfa..d66d7bedb0 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/imputation_semantics.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/imputation_semantics.py @@ -262,7 +262,7 @@ def _worker_execution_template() -> dict[str, object]: "surface": "execution_profile", "resolve_as": "worker_execution", "template": { - "schema_version": 1, + "schema_version": 2, "semantic_identity": { "resolver_op": "primary_qrf_worker_semantic_identity" }, @@ -270,6 +270,9 @@ def _worker_execution_template() -> dict[str, object]: "resolver_op": "primary_qrf_worker_semantic_identity_sha256" }, "audit_aliases": {"resolver_op": "primary_qrf_worker_audit_aliases"}, + "audit_thread_controls": { + "resolver_op": "primary_qrf_worker_audit_thread_controls" + }, }, } 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 05e4757959..07b0d965ba 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 @@ -352,7 +352,7 @@ "early_families": "4aa9f736fd76e83955477ad1667e58f48f264783f05bdc7f0102cd32d61323bd", "full_checkpoint": "ecf64f2bfbb59ffaaa717d8a09d38e56a38d6d43c1aa0a209d57492b038fb19a", "gap_fill_schedule": "1c31f9868f7884347cc19cf1ff65da43f950b9114941a715bab168246db414a7", - "graph_nodes": "1b208fff4f6d878c522147fee617177544bda8963c940f98a4bfc37507cb955f", + "graph_nodes": "ea67473e331b8849b3b48ecac89509661d904f2356ff2161a04715e569c79e91", "geography_assignment": "44e7f5f6cd7ceeef85d532c3d46306d03de4f4ee811376e6d29920742746b65c", "late_families": "7857518a5327a816acae80d55a04f43e7445a5e47be822d3ccb747bcb375e199", "late_resource_semantics": "4464b646c45dff39a500e07bf60a8505d45725712fc27dcfc6de1e839fd6b0c3", @@ -526,10 +526,11 @@ def _without_operational_bindings(value: object) -> object: """Strip execution-profile subtrees before semantic inventory digesting. ``worker_execution`` is the primary-QRF worker's execution binding: its - semantic identity hashes the interpreter binary, ABI, ``pyvenv.cfg``, - the installed distributions' RECORD files, and the resolved fit - controls (CPU count included), and its audit aliases spell the - interpreter path. All of that authenticates an environment for replay + semantic identity hashes the interpreter binary, ABI, ``pyvenv.cfg`` and + the installed distributions' RECORD files, its audit aliases spell the + interpreter path, and its audit thread controls record the fit-job and + prediction-worker counts (the CPU count included). All of that + authenticates or describes an environment for replay and legitimately differs between macOS and the Linux CI runners; none of it is spec evidence. Inventory digests are therefore computed over the receipt with the whole subtree removed, as they were before the diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/schema/imputation.schema.json b/packages/microcosm-build/src/microcosm/build/spec_engine/schema/imputation.schema.json index cd9031b680..010f9c67f9 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/schema/imputation.schema.json +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/schema/imputation.schema.json @@ -3385,7 +3385,7 @@ "additionalProperties": false, "properties": { "schema_version": { - "const": 1 + "const": 2 }, "semantic_identity": { "type": "object", @@ -3422,13 +3422,26 @@ "required": [ "resolver_op" ] + }, + "audit_thread_controls": { + "type": "object", + "additionalProperties": false, + "properties": { + "resolver_op": { + "const": "primary_qrf_worker_audit_thread_controls" + } + }, + "required": [ + "resolver_op" + ] } }, "required": [ "schema_version", "semantic_identity", "semantic_identity_sha256", - "audit_aliases" + "audit_aliases", + "audit_thread_controls" ] } }, diff --git a/packages/microcosm-build/src/microcosm/build/us/spec/imputation.yaml b/packages/microcosm-build/src/microcosm/build/us/spec/imputation.yaml index 9cac97a3cc..c59ab2f141 100644 --- a/packages/microcosm-build/src/microcosm/build/us/spec/imputation.yaml +++ b/packages/microcosm-build/src/microcosm/build/us/spec/imputation.yaml @@ -4475,13 +4475,15 @@ producer_graph: surface: execution_profile resolve_as: worker_execution template: - schema_version: 1 + schema_version: 2 semantic_identity: resolver_op: primary_qrf_worker_semantic_identity semantic_identity_sha256: resolver_op: primary_qrf_worker_semantic_identity_sha256 audit_aliases: resolver_op: primary_qrf_worker_audit_aliases + audit_thread_controls: + resolver_op: primary_qrf_worker_audit_thread_controls doctrines: require_complete_recipient_predictors: true absent_cells: preserve_nulls diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py index fb1ff09496..a5b7b93ed9 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py @@ -6084,7 +6084,7 @@ def _legacy_primary_qrf_worker_execution_binding() -> dict[str, object]: def _late_primary_qrf_worker_execution_binding() -> dict[str, object]: - """Bind portable semantics and retain absolute launch paths for audit.""" + """Bind portable semantics; keep launch paths and thread counts for audit.""" return worker_identity_runtime.primary_qrf_worker_execution_binding() @@ -6395,7 +6395,11 @@ def _late_primary_resource_receipts_semantic_projection( *, boundary: str, ) -> dict[str, object]: - """Normalize only primary-worker audit aliases out of authentication.""" + """Normalize only the primary-worker audit fields out of authentication. + + Those are the interpreter paths and the thread counts; see + ``worker_identity.primary_qrf_worker_semantic_projection``. + """ normalized = _json_ready(resources) if not isinstance(normalized, dict): # pragma: no cover - Mapping normalized @@ -6426,7 +6430,7 @@ def _late_primary_resource_receipts_semantically_equal( *, boundary: str, ) -> bool: - """Compare checkpoint resources without authenticating launcher aliases.""" + """Compare checkpoint resources without authenticating worker audit fields.""" return _late_primary_resource_receipts_semantic_projection( left, boundary=f"{boundary} recorded" 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 5d9b8481e2..cdf70c6cdb 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 @@ -14,7 +14,7 @@ import subprocess import sys import sysconfig -from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence from contextlib import contextmanager from dataclasses import dataclass from importlib import metadata @@ -24,7 +24,16 @@ from packaging.requirements import InvalidRequirement, Requirement from packaging.utils import canonicalize_name -PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION = 1 +#: Schema 2 records the fit-job and prediction-worker counts in +#: ``audit_thread_controls``, outside the semantic identity that every +#: recorded-versus-live comparison reads. The counts change no imputed value +#: (``microcosm-fit``'s ``test_qrf_worker_counts.py``), and an unset +#: prediction-worker count follows the machine, so a pool built on one host +#: stays comparable on another. +PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION = 2 +#: Schema 1 kept the counts in ``semantic_identity.environment.semantic_controls``. +#: Those records still validate; they never equal a schema-2 identity. +_SCHEMA_1_WORKER_IDENTITY_SCHEMA_VERSION = 1 PRIMARY_QRF_WORKER_MODULE = "microcosm.build.us_runtime.puf_qrf_worker" PRIMARY_QRF_INTERPRETER_PLACEHOLDER = "{python_interpreter}" APPROVED_UV_LOCK_SHA256 = ( @@ -58,14 +67,15 @@ "85345eae623d0081354d746a118c9dc5ddaa89a641238e546d8c8e9f7aabbb44" ), } -_SEMANTIC_ENVIRONMENT_NAMES = ( +#: The thread-count variables the worker inherits from its parent. +_THREAD_CONTROL_NAMES = ( "POPULACE_FIT_N_JOBS", "POPULACE_FIT_PREDICT_WORKERS", ) #: ``resolution`` of an unset POPULACE_FIT_PREDICT_WORKERS: the QRF draw's #: default width, ``joblib.cpu_count()``. _PREDICT_WORKERS_FALLBACK = "joblib_cpu_count_fallback" -#: The same field as identities recorded it while the default was +#: The same field as bindings recorded it while the default was #: ``os.cpu_count()``. Those records still validate, and the frozen schema-4 #: worker shape (``legacy_primary_qrf_worker_execution_binding``) records an #: unset count as that code did: ``os.cpu_count()`` under this label. @@ -84,7 +94,7 @@ "PYTHONPYCACHEPREFIX": "{empty_pycache_dir}", } _BOUND_ENVIRONMENT_NAMES = ( - *_SEMANTIC_ENVIRONMENT_NAMES, + *_THREAD_CONTROL_NAMES, *_WORKER_ENVIRONMENT_OVERRIDES, ) _CLEAN_WORKER_IMPORT_TRACE_MARKER = "MICROCOSM_WORKER_IMPORT_TRACE=" @@ -168,9 +178,26 @@ def record_worker_event(event, arguments): "permitted_mismatches", } _SHA256_ALPHABET = frozenset("0123456789abcdef") -_PRIMARY_QRF_WORKER_IDENTITY_CACHE: dict[ - tuple[str | None, str | None, str | None, int | None], dict[str, object] -] = {} +_WORKER_BINDING_KEYS_BY_SCHEMA = { + _SCHEMA_1_WORKER_IDENTITY_SCHEMA_VERSION: frozenset( + { + "schema_version", + "semantic_identity", + "semantic_identity_sha256", + "audit_aliases", + } + ), + PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION: frozenset( + { + "schema_version", + "semantic_identity", + "semantic_identity_sha256", + "audit_aliases", + "audit_thread_controls", + } + ), +} +_PRIMARY_QRF_WORKER_IDENTITY_CACHE: dict[str | None, dict[str, object]] = {} @dataclass(frozen=True) @@ -1240,7 +1267,7 @@ def _default_predict_workers() -> int: """The QRF draw's own width for an unset ``POPULACE_FIT_PREDICT_WORKERS``. The worker resolves the same value through ``microcosm.fit.qrf``, so the - identity records the pool width the worker uses. Imported here rather + binding records the pool width the worker uses. Imported here rather than at module level, which loads only the standard library and ``packaging``. """ @@ -1250,15 +1277,16 @@ def _default_predict_workers() -> int: return default_predict_workers() -def _predict_workers_unset(configured: str | None) -> bool: - return configured is None or not configured.strip() - - -def _semantic_environment( - predict_workers_fallback: int | None = None, +def _thread_controls( + *, + unset_predict_workers: Callable[[], int], + unset_predict_workers_resolution: str, ) -> dict[str, object]: - """Bind the fit controls; an unset prediction-worker count records - ``predict_workers_fallback`` when given, else reads the QRF default.""" + """Read and check the thread-count variables the worker inherits. + + An unset or blank ``POPULACE_FIT_PREDICT_WORKERS`` records + ``unset_predict_workers()`` under ``unset_predict_workers_resolution``. + """ fit_jobs_raw = os.environ.get("POPULACE_FIT_N_JOBS") if fit_jobs_raw is None: @@ -1277,13 +1305,9 @@ def _semantic_environment( "the primary-QRF worker binding." ) predict_workers_raw = os.environ.get("POPULACE_FIT_PREDICT_WORKERS") - if _predict_workers_unset(predict_workers_raw): - predict_workers = ( - _default_predict_workers() - if predict_workers_fallback is None - else predict_workers_fallback - ) - predict_workers_source = _PREDICT_WORKERS_FALLBACK + if predict_workers_raw is None or not predict_workers_raw.strip(): + predict_workers = unset_predict_workers() + predict_workers_source = unset_predict_workers_resolution else: try: predict_workers = int(predict_workers_raw) @@ -1298,40 +1322,51 @@ def _semantic_environment( "integer for the primary-QRF worker binding." ) predict_workers_source = "environment_override" + return { + "POPULACE_FIT_N_JOBS": { + "configured": fit_jobs_raw, + "resolved": fit_jobs, + }, + "POPULACE_FIT_PREDICT_WORKERS": { + "configured": predict_workers_raw, + "resolved": predict_workers, + "resolution": predict_workers_source, + }, + } + + +def _audit_thread_controls() -> dict[str, object]: + """The thread counts this process would launch the worker with.""" + + return _thread_controls( + unset_predict_workers=_default_predict_workers, + unset_predict_workers_resolution=_PREDICT_WORKERS_FALLBACK, + ) + + +def _schema_4_thread_controls() -> dict[str, object]: + """The same counts as schema-4 code recorded them. + + That code resolved an unset prediction-worker count to ``os.cpu_count()`` + under ``"os_cpu_count_fallback"``. + """ + + return _thread_controls( + unset_predict_workers=lambda: os.cpu_count() or 1, + unset_predict_workers_resolution=_SCHEMA_4_PREDICT_WORKERS_FALLBACK, + ) + + +def _semantic_environment() -> dict[str, object]: return { "policy": ( "inherit_parent_environment_with_bound_fit_controls_and_forced_overrides" ), "overrides": dict(_WORKER_ENVIRONMENT_OVERRIDES), - "semantic_controls": { - "POPULACE_FIT_N_JOBS": { - "configured": fit_jobs_raw, - "resolved": fit_jobs, - }, - "POPULACE_FIT_PREDICT_WORKERS": { - "configured": predict_workers_raw, - "resolved": predict_workers, - "resolution": predict_workers_source, - }, - }, "bound_names": list(_BOUND_ENVIRONMENT_NAMES), } -def _primary_qrf_worker_identity_cache_key( - uv_lock_sha256: str | None, -) -> tuple[str | None, str | None, str | None, int | None]: - predict_workers_raw = os.environ.get("POPULACE_FIT_PREDICT_WORKERS") - return ( - uv_lock_sha256, - os.environ.get("POPULACE_FIT_N_JOBS"), - predict_workers_raw, - _default_predict_workers() - if _predict_workers_unset(predict_workers_raw) - else None, - ) - - def clear_primary_qrf_worker_identity_cache() -> None: """Clear process attestations after deliberate runtime or source mutations.""" @@ -1350,37 +1385,29 @@ def primary_qrf_worker_semantic_identity( ``clear_primary_qrf_worker_identity_cache()`` before reattesting. The returned object graph is shared across calls and must be treated as read-only. - The raw lock argument is part of the key: ``None`` validates the checkout's - lock on its first cache miss and after clearing, while explicit approved - and legacy digests have separate entries. Bound environment values are - likewise keyed by their raw configured strings so validation is preserved. - An unset prediction-worker count is also keyed by the width it resolves - to, which ``joblib.cpu_count()`` can change within a process (through - ``LOKY_MAX_CPU_COUNT`` or the CPU affinity mask). + The raw lock argument is the key: ``None`` validates the checkout's lock + on its first cache miss and after clearing, while explicit approved and + legacy digests have separate entries. The thread-count variables are not + part of this identity; ``primary_qrf_worker_execution_binding()`` reads + and checks them on every call. """ if uv_lock_sha256 is not None: _require_sha256(uv_lock_sha256, boundary="primary-QRF worker lock") - key = _primary_qrf_worker_identity_cache_key(uv_lock_sha256) - if key not in _PRIMARY_QRF_WORKER_IDENTITY_CACHE: - # The identity records the count the key holds, read once, so a - # change during the attestation cannot file it under another count. - predict_workers_fallback = key[3] - _PRIMARY_QRF_WORKER_IDENTITY_CACHE[key] = ( + if uv_lock_sha256 not in _PRIMARY_QRF_WORKER_IDENTITY_CACHE: + _PRIMARY_QRF_WORKER_IDENTITY_CACHE[uv_lock_sha256] = ( _uncached_primary_qrf_worker_semantic_identity( - uv_lock_sha256=uv_lock_sha256, - predict_workers_fallback=predict_workers_fallback, + uv_lock_sha256=uv_lock_sha256 ) ) - return _PRIMARY_QRF_WORKER_IDENTITY_CACHE[key] + return _PRIMARY_QRF_WORKER_IDENTITY_CACHE[uv_lock_sha256] def _uncached_primary_qrf_worker_semantic_identity( *, uv_lock_sha256: str | None = None, - predict_workers_fallback: int | None = None, ) -> dict[str, object]: - """Build the canonical worker identity, excluding all launcher aliases.""" + """Build the canonical worker identity, excluding all audit fields.""" if uv_lock_sha256 is None: lock_sha256 = _approved_uv_lock_sha256() @@ -1410,7 +1437,7 @@ def _uncached_primary_qrf_worker_semantic_identity( "Primary-QRF worker cannot read its loaded Python runtime." ) from error pyvenv_config = _canonical_pyvenv_config() - environment = _semantic_environment(predict_workers_fallback) + environment = _semantic_environment() import_trace = _clean_worker_import_trace() namespace_rows = _worker_package_resource_rows(import_trace) imports_sha256 = _canonical_sha256( @@ -1466,8 +1493,16 @@ def _uncached_primary_qrf_worker_semantic_identity( def primary_qrf_worker_execution_binding() -> dict[str, object]: - """Return semantic worker identity plus integrity-bound audit aliases.""" + """Return the semantic worker identity plus fields kept only for audit. + + ``audit_aliases`` spell the interpreter paths and ``audit_thread_controls`` + the fit-job and prediction-worker counts. Comparisons with a recorded + binding read only the semantic identity, so neither the install location + nor the machine's CPU count makes a pool or checkpoint incomparable. + """ + # Checked before the attestation, so a malformed count fails fast. + thread_controls = _audit_thread_controls() raw_executable = sys.executable executable = Path(raw_executable).absolute() # Execution bindings become mutable artifact payloads; their edits must @@ -1483,6 +1518,7 @@ def primary_qrf_worker_execution_binding() -> dict[str, object]: "sys_prefix": str(Path(sys.prefix).absolute()), "argv_template_0": raw_executable, }, + "audit_thread_controls": thread_controls, } validate_primary_qrf_worker_execution_binding( result, @@ -1491,8 +1527,48 @@ def primary_qrf_worker_execution_binding() -> dict[str, object]: return result +def _validate_thread_controls(controls: object, *, boundary: str) -> None: + controls = _require_exact_keys( + controls, + set(_THREAD_CONTROL_NAMES), + boundary=boundary, + ) + fit = _require_exact_keys( + controls.get("POPULACE_FIT_N_JOBS"), + {"configured", "resolved"}, + boundary=f"{boundary} fit jobs", + ) + predict = _require_exact_keys( + controls.get("POPULACE_FIT_PREDICT_WORKERS"), + {"configured", "resolved", "resolution"}, + boundary=f"{boundary} predict workers", + ) + if fit.get("configured") is not None and not isinstance(fit.get("configured"), str): + raise ValueError(f"{boundary} configured fit jobs must be a string or null.") + if predict.get("configured") is not None and not isinstance( + predict.get("configured"), str + ): + raise ValueError( + f"{boundary} configured predict workers must be a string or null." + ) + if ( + isinstance(fit.get("resolved"), bool) + or not isinstance(fit.get("resolved"), int) + or int(fit["resolved"]) < -1 + or fit.get("resolved") == 0 + or isinstance(predict.get("resolved"), bool) + or not isinstance(predict.get("resolved"), int) + or int(predict["resolved"]) < 1 + or predict.get("resolution") not in _PREDICT_WORKERS_RESOLUTIONS + ): + raise ValueError(f"{boundary} thread controls are malformed.") + + def _validate_semantic_identity( - semantic: object, *, boundary: str + semantic: object, + *, + boundary: str, + schema_version: int = PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION, ) -> Mapping[str, object]: value = _require_exact_keys( semantic, @@ -1625,9 +1701,12 @@ def _validate_semantic_identity( ] if value.get("argv_template") != expected_argv: raise ValueError(f"{boundary} semantic argv template changed.") + environment_keys = {"policy", "overrides", "bound_names"} + if schema_version == _SCHEMA_1_WORKER_IDENTITY_SCHEMA_VERSION: + environment_keys.add("semantic_controls") environment = _require_exact_keys( value.get("environment"), - {"policy", "overrides", "semantic_controls", "bound_names"}, + environment_keys, boundary=f"{boundary} environment", ) if ( @@ -1637,40 +1716,11 @@ def _validate_semantic_identity( or environment.get("bound_names") != list(_BOUND_ENVIRONMENT_NAMES) ): raise ValueError(f"{boundary} semantic environment policy changed.") - controls = _require_exact_keys( - environment.get("semantic_controls"), - set(_SEMANTIC_ENVIRONMENT_NAMES), - boundary=f"{boundary} semantic controls", - ) - fit = _require_exact_keys( - controls.get("POPULACE_FIT_N_JOBS"), - {"configured", "resolved"}, - boundary=f"{boundary} fit jobs", - ) - predict = _require_exact_keys( - controls.get("POPULACE_FIT_PREDICT_WORKERS"), - {"configured", "resolved", "resolution"}, - boundary=f"{boundary} predict workers", - ) - if fit.get("configured") is not None and not isinstance(fit.get("configured"), str): - raise ValueError(f"{boundary} configured fit jobs must be a string or null.") - if predict.get("configured") is not None and not isinstance( - predict.get("configured"), str - ): - raise ValueError( - f"{boundary} configured predict workers must be a string or null." + if schema_version == _SCHEMA_1_WORKER_IDENTITY_SCHEMA_VERSION: + _validate_thread_controls( + environment.get("semantic_controls"), + boundary=f"{boundary} semantic controls", ) - if ( - isinstance(fit.get("resolved"), bool) - or not isinstance(fit.get("resolved"), int) - or int(fit["resolved"]) < -1 - or fit.get("resolved") == 0 - or isinstance(predict.get("resolved"), bool) - or not isinstance(predict.get("resolved"), int) - or int(predict["resolved"]) < 1 - or predict.get("resolution") not in _PREDICT_WORKERS_RESOLUTIONS - ): - raise ValueError(f"{boundary} resolved worker controls are malformed.") return value @@ -1679,25 +1729,42 @@ def validate_primary_qrf_worker_execution_binding( *, boundary: str, ) -> None: - """Validate the closed v1 worker identity and its semantic self-digest.""" + """Validate a closed worker binding and its semantic self-digest. + + Schema 2 is current. Schema-1 records, written before the thread counts + left the semantic identity, still validate so a loader can report them + as a changed identity rather than an unreadable one. + """ + schema_version = ( + binding.get("schema_version") if isinstance(binding, Mapping) else None + ) + known_schema = ( + isinstance(schema_version, int) + and not isinstance(schema_version, bool) + and schema_version in _WORKER_BINDING_KEYS_BY_SCHEMA + ) worker = _require_exact_keys( binding, - { - "schema_version", - "semantic_identity", - "semantic_identity_sha256", - "audit_aliases", - }, + set( + _WORKER_BINDING_KEYS_BY_SCHEMA[ + schema_version + if known_schema + else PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION + ] + ), boundary=boundary, ) - if worker.get("schema_version") != PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION: + if not known_schema: raise ValueError( f"{boundary} requires schema version " - f"{PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION}." + f"{PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION} (or " + f"{_SCHEMA_1_WORKER_IDENTITY_SCHEMA_VERSION}, recorded before)." ) semantic = _validate_semantic_identity( - worker.get("semantic_identity"), boundary=f"{boundary} semantic_identity" + worker.get("semantic_identity"), + boundary=f"{boundary} semantic_identity", + schema_version=schema_version, ) semantic_sha256 = _require_sha256( worker.get("semantic_identity_sha256"), @@ -1714,6 +1781,11 @@ def validate_primary_qrf_worker_execution_binding( _require_string(value, boundary=f"{boundary} audit alias {name}") if name in {"sys_executable", "sys_prefix"} and not Path(value).is_absolute(): raise ValueError(f"{boundary} audit alias {name} must be absolute.") + if schema_version == PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION: + _validate_thread_controls( + worker.get("audit_thread_controls"), + boundary=f"{boundary} audit thread controls", + ) def _validated_primary_qrf_worker_semantic_identity( @@ -1733,7 +1805,11 @@ def primary_qrf_worker_semantic_projection( *, boundary: str, ) -> dict[str, object]: - """Project a binding for identities that must never hash audit aliases.""" + """Project a binding for identities that must never hash its audit fields. + + The projection drops ``audit_aliases`` (interpreter paths) and + ``audit_thread_controls`` (fit-job and prediction-worker counts). + """ semantic = _validated_primary_qrf_worker_semantic_identity( binding, boundary=boundary @@ -1752,7 +1828,7 @@ def primary_qrf_worker_bindings_semantically_equal( *, boundary: str, ) -> bool: - """Compare validated semantic identities while ignoring launcher aliases.""" + """Compare validated semantic identities, ignoring the audit fields.""" return _validated_primary_qrf_worker_semantic_identity( left, boundary=f"{boundary} recorded worker" @@ -1790,15 +1866,12 @@ def legacy_primary_qrf_worker_execution_binding( # semantic identity above still binds and enforces the current safe policy. environment["policy"] = "inherit_parent_environment_with_bound_fit_controls" environment["overrides"] = {} - environment["bound_names"] = list(_SEMANTIC_ENVIRONMENT_NAMES) - # Schema-4 code resolved an unset prediction-worker count to this host's - # os.cpu_count() under the label below, and the sealed records compared - # with this projection hold that. The live draw uses joblib.cpu_count(), - # which the attested semantic identity binds; the count changes no draw. - predict_workers = environment["semantic_controls"]["POPULACE_FIT_PREDICT_WORKERS"] - if predict_workers["resolution"] == _PREDICT_WORKERS_FALLBACK: - predict_workers["resolved"] = os.cpu_count() or 1 - predict_workers["resolution"] = _SCHEMA_4_PREDICT_WORKERS_FALLBACK + environment["bound_names"] = list(_THREAD_CONTROL_NAMES) + # The schema-4 shape keeps the thread counts beside the policy, as that + # code recorded them: an unset prediction-worker count as this host's + # os.cpu_count(). The sealed records compared with this projection hold + # those values, so this frozen comparison still includes the counts. + environment["semantic_controls"] = _schema_4_thread_controls() return { "module": worker_module["name"], "argv_template": [str(executable), *argv[1:]], diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_spec_bundle.py b/packages/microcosm-build/tests/engine_contract/us/test_us_spec_bundle.py index 4ea8a8e3cc..48a2c5a573 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_us_spec_bundle.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_spec_bundle.py @@ -301,7 +301,7 @@ def collect_sha256(value: object, path: tuple[str, ...] = ()) -> None: "surface": "execution_profile", "resolve_as": "worker_execution", "template": { - "schema_version": 1, + "schema_version": 2, "semantic_identity": { "resolver_op": "primary_qrf_worker_semantic_identity" }, @@ -309,6 +309,9 @@ def collect_sha256(value: object, path: tuple[str, ...] = ()) -> None: "resolver_op": "primary_qrf_worker_semantic_identity_sha256" }, "audit_aliases": {"resolver_op": "primary_qrf_worker_audit_aliases"}, + "audit_thread_controls": { + "resolver_op": "primary_qrf_worker_audit_thread_controls" + }, }, } runtime_bands = primary_binding["capital_gains_tail"]["soi_e19200_agi_bands"][ diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py index e2e7e5714f..f376c54c2b 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py @@ -2,16 +2,19 @@ With ``POPULACE_FIT_PREDICT_WORKERS`` unset, the QRF draw sizes its thread pool by ``joblib.cpu_count()`` (``microcosm.fit.qrf.default_predict_workers``). The -worker identity in ``worker_identity.py`` and the older binding in -``stacked_spine.py`` record that same width, and the environment variable -still overrides it. Each test patches ``joblib.cpu_count`` to a value that -``os.cpu_count()``, the earlier default, does not return. +worker binding in ``worker_identity.py`` (its ``audit_thread_controls``) and +the older binding in ``stacked_spine.py`` record that same width, and the +environment variable still overrides it. Each test patches +``joblib.cpu_count`` to a value that ``os.cpu_count()``, the earlier default, +does not return. -Both label that fallback ``"joblib_cpu_count_fallback"``. Identities written +Both label that fallback ``"joblib_cpu_count_fallback"``. Bindings written before carry ``"os_cpu_count_fallback"`` and still validate. The schema-4 worker shape that legacy pools recorded is projected as that code recorded it, the host's ``os.cpu_count()`` under the old label, so the scoring-only relocation of those pools compares what it compared before. +``test_us_qrf_worker_thread_controls.py`` covers why the counts sit outside +the compared semantic identity. """ # ruff: noqa: F403, F405 @@ -50,9 +53,8 @@ def _set_predict_workers( def _worker_identity_predict_controls() -> dict[str, object]: - return worker_identity_module._semantic_environment()["semantic_controls"][ - PREDICT_WORKERS_ENV - ] + binding = worker_identity_module.primary_qrf_worker_execution_binding() + return binding["audit_thread_controls"][PREDICT_WORKERS_ENV] def _stacked_spine_predict_controls() -> dict[str, object]: @@ -113,30 +115,24 @@ def test_predict_workers_override_wins_over_joblib_cpu_count( } -def test_worker_identity_memo_binds_unset_predict_worker_default( +def test_changed_joblib_cpu_count_reuses_the_cached_identity( _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch ) -> None: - """A changed ``joblib.cpu_count()`` recomputes the cached identity.""" + """The count is read per binding; the cached semantic identity omits it.""" _source, calls = _worker_identity_memo_inputs monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) smaller, larger = _cpu_count_unlike_os(3), _cpu_count_unlike_os(5) _patch_joblib_cpu_count(monkeypatch, smaller) - first = worker_identity_module.primary_qrf_worker_semantic_identity() + first = worker_identity_module.primary_qrf_worker_execution_binding() _patch_joblib_cpu_count(monkeypatch, larger) - second = worker_identity_module.primary_qrf_worker_semantic_identity() + second = worker_identity_module.primary_qrf_worker_execution_binding() predict = PREDICT_WORKERS_ENV - assert first["environment"]["semantic_controls"][predict]["resolved"] == smaller - assert second["environment"]["semantic_controls"][predict]["resolved"] == larger - assert worker_identity_module._canonical_sha256( - first - ) != worker_identity_module._canonical_sha256(second) - assert len(calls) == 2 - - _patch_joblib_cpu_count(monkeypatch, smaller) - assert worker_identity_module.primary_qrf_worker_semantic_identity() is first - assert len(calls) == 2 + assert first["audit_thread_controls"][predict]["resolved"] == smaller + assert second["audit_thread_controls"][predict]["resolved"] == larger + assert first["semantic_identity"] == second["semantic_identity"] + assert len(calls) == 1 def _live_binding_with_unset_predict_workers( @@ -148,15 +144,9 @@ def _live_binding_with_unset_predict_workers( def _with_resolution(binding: dict[str, object], label: str) -> dict[str, object]: - """A copy of ``binding`` whose fallback label is ``label``, re-digested.""" + """A copy of ``binding`` whose recorded fallback label is ``label``.""" relabelled = deepcopy(binding) - semantic = relabelled["semantic_identity"] - semantic["environment"]["semantic_controls"][PREDICT_WORKERS_ENV]["resolution"] = ( - label - ) - relabelled["semantic_identity_sha256"] = worker_identity_module._canonical_sha256( - semantic - ) + relabelled["audit_thread_controls"][PREDICT_WORKERS_ENV]["resolution"] = label return relabelled @@ -164,7 +154,7 @@ def _with_resolution(binding: dict[str, object], label: str) -> dict[str, object def test_worker_identity_validation_accepts_both_fallback_labels( _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch, label: str ) -> None: - """Identities recorded before the joblib default still validate.""" + """Bindings recorded before the joblib default still validate.""" binding = _live_binding_with_unset_predict_workers( monkeypatch, _cpu_count_unlike_os() ) @@ -181,7 +171,7 @@ def test_worker_identity_validation_refuses_an_unknown_fallback_label( monkeypatch, _cpu_count_unlike_os() ) - with pytest.raises(ValueError, match="resolved worker controls are malformed"): + with pytest.raises(ValueError, match="thread controls are malformed"): worker_identity_module.validate_primary_qrf_worker_execution_binding( _with_resolution(binding, "process_cpu_count_fallback"), boundary="fallback label", @@ -196,13 +186,13 @@ def test_schema_4_projection_records_an_unset_count_as_schema_4_code_did( Schema-4 code resolved an unset count to ``os.cpu_count()`` and labelled it ``"os_cpu_count_fallback"``. The scoring-only relocation of a schema-9 pool compares that record with this projection of the live worker and allows - only the two relocated interpreter paths to differ. The live identity + only the two relocated interpreter paths to differ. The live binding itself still records the ``joblib.cpu_count()`` the draw uses. """ joblib_cpu_count = _cpu_count_unlike_os() binding = _live_binding_with_unset_predict_workers(monkeypatch, joblib_cpu_count) semantic = binding["semantic_identity"] - live_controls = semantic["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] + live_controls = binding["audit_thread_controls"][PREDICT_WORKERS_ENV] live_before = deepcopy(live_controls) projected = worker_identity_module.legacy_primary_qrf_worker_execution_binding( @@ -242,27 +232,6 @@ def test_schema_4_projection_records_an_unset_count_as_schema_4_code_did( ) -def test_worker_identity_records_the_count_it_is_cached_under( - _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch -) -> None: - """The cache key and the identity read ``joblib.cpu_count()`` once.""" - monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) - first_count, later_count = _cpu_count_unlike_os(3), _cpu_count_unlike_os(5) - calls = [] - - def changing_cpu_count(only_physical_cores: bool = False) -> int: - calls.append(None) - return first_count if len(calls) == 1 else later_count - - monkeypatch.setattr(joblib, "cpu_count", changing_cpu_count) - - identity = worker_identity_module.primary_qrf_worker_semantic_identity() - - controls = identity["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] - assert controls["resolved"] == first_count - assert len(calls) == 1 - - def test_schema_4_projection_keeps_an_override_label( _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py new file mode 100644 index 0000000000..bea978d4e4 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py @@ -0,0 +1,515 @@ +"""The primary-QRF worker records its thread counts but never compares them. + +The QRF draw gives byte-identical imputations for any fit-job count and any +prediction-worker count (``microcosm-fit``'s ``test_qrf_worker_counts.py``), +and with ``POPULACE_FIT_PREDICT_WORKERS`` unset the count comes from the +machine (``joblib.cpu_count()``). Schema-2 worker bindings therefore keep +``POPULACE_FIT_N_JOBS`` and ``POPULACE_FIT_PREDICT_WORKERS`` in +``audit_thread_controls``, next to the interpreter paths in ``audit_aliases``, +and out of the semantic identity. Everything that compares a recorded worker +with the live one reads only the semantic identity: loading a pool for +release or scoring, resuming the primary-QRF checkpoint, the pool's +checkpoint identity, and the spec engine's worker resolution. A pool built on +an 18-CPU host therefore loads under the release tool's 16-CPU cap. + +Schema-1 bindings, which kept the counts in +``semantic_identity.environment.semantic_controls``, still validate, so a pool +recorded before is refused because its identity changed, not because its +record is unreadable. +""" + +# ruff: noqa: F403, F405 +from __future__ import annotations + +import json +from copy import deepcopy + +import joblib + +from microcosm.build.spec_engine import imputation_semantics +from test_support.microcosm_build.us_stacked_spine import * + +FIT_JOBS_ENV = "POPULACE_FIT_N_JOBS" +PREDICT_WORKERS_ENV = "POPULACE_FIT_PREDICT_WORKERS" +JOBLIB_FALLBACK = "joblib_cpu_count_fallback" +SCHEMA_4_FALLBACK = "os_cpu_count_fallback" +BINDING_KEYS = { + "schema_version", + "semantic_identity", + "semantic_identity_sha256", + "audit_aliases", + "audit_thread_controls", +} + +#: (POPULACE_FIT_N_JOBS, POPULACE_FIT_PREDICT_WORKERS, joblib.cpu_count()) +BASE_HOST = (None, None, 18) +RELEASE_UNDER_CPU_CAP = (None, None, 16) +OVERRIDDEN = ("2", "9", 4) +THREAD_SETTINGS = (BASE_HOST, RELEASE_UNDER_CPU_CAP, OVERRIDDEN) + + +def _apply_thread_setting( + monkeypatch: pytest.MonkeyPatch, + setting: tuple[str | None, str | None, int], +) -> None: + fit_jobs, predict_workers, joblib_cpu_count = setting + for name, value in ( + (FIT_JOBS_ENV, fit_jobs), + (PREDICT_WORKERS_ENV, predict_workers), + ): + if value is None: + monkeypatch.delenv(name, raising=False) + else: + monkeypatch.setenv(name, value) + + def patched_cpu_count(only_physical_cores: bool = False) -> int: + return joblib_cpu_count + + monkeypatch.setattr(joblib, "cpu_count", patched_cpu_count) + + +def _binding_under( + monkeypatch: pytest.MonkeyPatch, + setting: tuple[str | None, str | None, int], +) -> dict[str, object]: + _apply_thread_setting(monkeypatch, setting) + return worker_identity_module.primary_qrf_worker_execution_binding() + + +def _validate_binding(binding: object) -> None: + worker_identity_module.validate_primary_qrf_worker_execution_binding( + binding, boundary="thread-control fixture" + ) + + +def _as_schema_1_record(binding: dict[str, object]) -> dict[str, object]: + """``binding`` as schema-1 code recorded it: counts in the semantic identity.""" + record = deepcopy(binding) + controls = record.pop("audit_thread_controls") + record["schema_version"] = 1 + record["semantic_identity"]["environment"]["semantic_controls"] = controls + record["semantic_identity_sha256"] = worker_identity_module._canonical_sha256( + record["semantic_identity"] + ) + return record + + +def _validate_primary_config_against_live_worker( + config: Mapping[str, object], *, boundary: str +) -> None: + stacked_spine_module._validate_late_resource_binding( + config, + producer=stacked_spine_module.US_LATE_PRIMARY_PUF_STAGE, + entity="tax_unit", + column=stacked_spine_module.US_LATE_PRIMARY_EXECUTION_CONFIG_INPUT, + boundary=boundary, + ) + + +def test_worker_binding_records_thread_controls_outside_the_semantic_identity( + monkeypatch: pytest.MonkeyPatch, +) -> None: + binding = _binding_under(monkeypatch, BASE_HOST) + + assert binding["schema_version"] == 2 + assert binding["schema_version"] == ( + worker_identity_module.PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION + ) + assert set(binding) == BINDING_KEYS + assert set(binding["semantic_identity"]["environment"]) == { + "policy", + "overrides", + "bound_names", + } + assert binding["audit_thread_controls"] == { + FIT_JOBS_ENV: {"configured": None, "resolved": -1}, + PREDICT_WORKERS_ENV: { + "configured": None, + "resolved": 18, + "resolution": JOBLIB_FALLBACK, + }, + } + _validate_binding(binding) + + +def test_overridden_thread_controls_are_recorded_as_configured( + monkeypatch: pytest.MonkeyPatch, +) -> None: + binding = _binding_under(monkeypatch, OVERRIDDEN) + + assert binding["audit_thread_controls"] == { + FIT_JOBS_ENV: {"configured": "2", "resolved": 2}, + PREDICT_WORKERS_ENV: { + "configured": "9", + "resolved": 9, + "resolution": "environment_override", + }, + } + + +def test_thread_controls_leave_the_compared_worker_identity_unchanged( + monkeypatch: pytest.MonkeyPatch, +) -> None: + bindings = [_binding_under(monkeypatch, setting) for setting in THREAD_SETTINGS] + + recorded_thread_controls = { + json.dumps(binding["audit_thread_controls"], sort_keys=True) + for binding in bindings + } + assert len(recorded_thread_controls) == len(THREAD_SETTINGS) + first = bindings[0] + first_projection = worker_identity_module.primary_qrf_worker_semantic_projection( + first, boundary="first thread setting" + ) + for other in bindings[1:]: + assert other["semantic_identity"] == first["semantic_identity"] + assert other["semantic_identity_sha256"] == first["semantic_identity_sha256"] + assert worker_identity_module.primary_qrf_worker_bindings_semantically_equal( + first, other, boundary="thread settings" + ) + assert ( + worker_identity_module.primary_qrf_worker_semantic_projection( + other, boundary="other thread setting" + ) + == first_projection + ) + + +@pytest.mark.parametrize( + "release_setting", + ( + pytest.param(RELEASE_UNDER_CPU_CAP, id="release-capped-at-16-cpus"), + pytest.param(OVERRIDDEN, id="release-overrides-both-counts"), + ), +) +def test_pool_recorded_on_another_host_loads_with_the_live_worker( + monkeypatch: pytest.MonkeyPatch, + release_setting: tuple[str | None, str | None, int], +) -> None: + """The release and scoring loaders compare the recorded worker this way.""" + _apply_thread_setting(monkeypatch, BASE_HOST) + recorded = _fixture_primary_execution_config_binding() + _apply_thread_setting(monkeypatch, release_setting) + live_controls = worker_identity_module.primary_qrf_worker_execution_binding()[ + "audit_thread_controls" + ] + assert recorded["qrf"]["worker_execution"]["audit_thread_controls"] != ( + live_controls + ) + + _validate_primary_config_against_live_worker( + recorded, boundary="pool load on another host" + ) + + +def test_primary_checkpoint_resources_resume_under_other_thread_controls( + monkeypatch: pytest.MonkeyPatch, +) -> None: + donor = pd.DataFrame( + {"income": np.array([10.0, 20.0], dtype=np.float64)}, + index=pd.Index([3, 9], name="donor_id"), + ) + arguments = { + "primary_qrf_checkpoint_identity_sha256": "a" * 64, + "clone_attachment_fraction": 1.0, + "clone_attachment_seed": 578, + "seed": 0, + "n_estimators": 100, + "fit_records_enabled": True, + "tail_bound_diagnostics_enabled": True, + } + config_key = "tax_unit.@primary_puf_execution_config" + + _apply_thread_setting(monkeypatch, BASE_HOST) + recorded = stacked_spine_module.stacked_late_primary_resource_receipts( + donor, **arguments + ) + _apply_thread_setting(monkeypatch, OVERRIDDEN) + live = stacked_spine_module.stacked_late_primary_resource_receipts( + donor, **arguments + ) + + assert ( + recorded[config_key]["binding"]["qrf"]["worker_execution"][ + "audit_thread_controls" + ] + != ( + live[config_key]["binding"]["qrf"]["worker_execution"][ + "audit_thread_controls" + ] + ) + ) + assert stacked_spine_module._late_primary_resource_receipts_semantically_equal( + recorded, live, boundary="primary-QRF checkpoint resume" + ) + + +def test_primary_qrf_checkpoint_resumes_under_other_thread_controls( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """A checkpoint started on one host resumes on another, sidecar untouched. + + The chain itself is stubbed, as in the relocated-resume test in + ``test_us_stacked_spine.py``; this exercises the sidecar comparison. + """ + checkpoint_identity = "a" * 64 + checkpoint_dir = tmp_path / checkpoint_identity + donor = pd.DataFrame({"fixture_donor": [1.0]}) + + def initialize(_frame: Frame, _donor: pd.DataFrame, root: Path, **_kwargs) -> None: + root.mkdir(parents=True) + (root / stacked_spine_module.PRIMARY_QRF_MANIFEST_FILENAME).write_text( + "{}", + encoding="utf-8", + ) + + monkeypatch.setattr( + stacked_spine_module, "initialize_primary_puf_qrf_chain", initialize + ) + monkeypatch.setattr( + stacked_spine_module, + "primary_puf_qrf_recipient_predictor_universe_receipt", + lambda _root: {"fixture": "recipient-universe"}, + ) + monkeypatch.setattr( + stacked_spine_module, "run_primary_puf_qrf_chain", lambda _root, **_kwargs: None + ) + monkeypatch.setattr( + stacked_spine_module, + "finalize_primary_puf_qrf_chain", + lambda frame, _root, **_kwargs: (frame, frame.resolve_weights("tax_unit").kind), + ) + + def input_binding() -> dict[str, object]: + resources = stacked_spine_module.stacked_late_primary_resource_receipts( + donor, + primary_qrf_checkpoint_identity_sha256=checkpoint_identity, + clone_attachment_fraction=1.0, + clone_attachment_seed=578, + seed=0, + n_estimators=100, + fit_records_enabled=True, + tail_bound_diagnostics_enabled=True, + ) + return stacked_spine_module.stacked_late_primary_checkpoint_input_binding( + resources + ) + + def run(binding: dict[str, object]): + return stacked_spine_module._run_stacked_puf_pass_without_tail_for_test( + _late_primary_entry(_stacked_gap_fixture()), + donor, + clone_attachment_fraction=1.0, + clone_attachment_seed=578, + fit_records=[], + tail_bound_diagnostics=[], + primary_qrf_checkpoint_dir=checkpoint_dir, + primary_qrf_input_binding=binding, + ) + + _apply_thread_setting(monkeypatch, BASE_HOST) + initialized = run(input_binding()).receipt["primary_puf_qrf"] + sidecar_path = checkpoint_dir / "late-producer-input-binding.json" + sidecar_bytes = sidecar_path.read_bytes() + assert initialized["resume_status"] == "initialized" + + _apply_thread_setting(monkeypatch, OVERRIDDEN) + live_binding = input_binding() + assert live_binding["sha256"] != json.loads(sidecar_bytes)["sha256"], ( + "the recorded thread controls must move the live sidecar digest" + ) + resumed = run(live_binding).receipt["primary_puf_qrf"] + + assert resumed["resume_status"] == "resumed" + assert sidecar_path.read_bytes() == sidecar_bytes + + +def test_pool_checkpoint_identity_ignores_thread_controls( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The pool's checkpoint identity hashes this resource-semantics receipt.""" + arguments = { + "clone_attachment_fraction": 1.0, + "clone_attachment_seed": 578, + "primary_seed": 0, + "primary_n_estimators": 100, + "transfer_seed": 0, + "transfer_n_estimators": 100, + "transfer_max_targets_per_fit": ( + acs_transfer_module.DEFAULT_ACS_TRANSFER_MAX_TARGETS_PER_FIT + ), + } + receipt_digests = set() + for setting in THREAD_SETTINGS: + _apply_thread_setting(monkeypatch, setting) + receipt = stacked_spine_module.stacked_late_producer_resource_semantics_receipt( + **arguments + ) + receipt_digests.add(receipt["sha256"]) + + assert len(receipt_digests) == 1 + + +def test_spec_engine_worker_resolution_ignores_thread_controls( + monkeypatch: pytest.MonkeyPatch, +) -> None: + template = imputation_semantics._worker_execution_template() + resolutions = [] + for setting in THREAD_SETTINGS: + _apply_thread_setting(monkeypatch, setting) + resolutions.append(imputation_semantics._resolve_worker_execution(template)) + + assert all(resolution == resolutions[0] for resolution in resolutions) + assert resolutions[0]["schema_version"] == 2 + + +def test_spec_engine_worker_template_names_every_binding_field( + monkeypatch: pytest.MonkeyPatch, +) -> None: + template = imputation_semantics._worker_execution_template()["template"] + binding = _binding_under(monkeypatch, BASE_HOST) + + assert set(template) == set(binding) + assert template["schema_version"] == binding["schema_version"] + assert template["audit_thread_controls"] == { + "resolver_op": "primary_qrf_worker_audit_thread_controls" + } + + +@pytest.mark.parametrize("label", [JOBLIB_FALLBACK, SCHEMA_4_FALLBACK]) +def test_schema_1_worker_records_still_validate( + monkeypatch: pytest.MonkeyPatch, label: str +) -> None: + record = _as_schema_1_record(_binding_under(monkeypatch, BASE_HOST)) + record["semantic_identity"]["environment"]["semantic_controls"][ + PREDICT_WORKERS_ENV + ]["resolution"] = label + record["semantic_identity_sha256"] = worker_identity_module._canonical_sha256( + record["semantic_identity"] + ) + + _validate_binding(record) + assert ( + worker_identity_module.current_worker_execution_authentication_receipt( + record, + manifest_schema_version=10, + execution_config_schema_version=6, + boundary="schema-1 record", + )["worker_execution_schema_version"] + == 1 + ) + + +def test_pool_recorded_with_a_schema_1_worker_is_refused_as_changed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _apply_thread_setting(monkeypatch, BASE_HOST) + recorded = _fixture_primary_execution_config_binding() + recorded["qrf"]["worker_execution"] = _as_schema_1_record( + recorded["qrf"]["worker_execution"] + ) + + assert not worker_identity_module.primary_qrf_worker_bindings_semantically_equal( + recorded["qrf"]["worker_execution"], + worker_identity_module.primary_qrf_worker_execution_binding(), + boundary="schema-1 record", + ) + with pytest.raises(ValueError, match="semantic worker identity changed"): + _validate_primary_config_against_live_worker( + recorded, boundary="schema-1 pool load" + ) + + +def _schema_2_with_counts_in_the_semantic_identity( + binding: dict[str, object], +) -> dict[str, object]: + record = _as_schema_1_record(binding) + record["schema_version"] = 2 + record["audit_thread_controls"] = deepcopy(binding["audit_thread_controls"]) + return record + + +def _schema_2_without_audit_thread_controls( + binding: dict[str, object], +) -> dict[str, object]: + record = deepcopy(binding) + del record["audit_thread_controls"] + return record + + +def _schema_1_with_audit_thread_controls( + binding: dict[str, object], +) -> dict[str, object]: + record = _as_schema_1_record(binding) + record["audit_thread_controls"] = deepcopy(binding["audit_thread_controls"]) + return record + + +def _unknown_schema_version(binding: dict[str, object]) -> dict[str, object]: + record = deepcopy(binding) + record["schema_version"] = 3 + return record + + +@pytest.mark.parametrize( + "malform", + ( + _schema_2_with_counts_in_the_semantic_identity, + _schema_2_without_audit_thread_controls, + _schema_1_with_audit_thread_controls, + _unknown_schema_version, + ), +) +def test_worker_records_with_a_mixed_or_unknown_shape_are_refused( + monkeypatch: pytest.MonkeyPatch, malform +) -> None: + binding = _binding_under(monkeypatch, BASE_HOST) + + with pytest.raises(ValueError): + _validate_binding(malform(binding)) + + +@pytest.mark.parametrize( + ("variable", "field", "value"), + ( + (FIT_JOBS_ENV, "resolved", 0), + (FIT_JOBS_ENV, "resolved", -2), + (FIT_JOBS_ENV, "resolved", True), + (FIT_JOBS_ENV, "configured", 2), + (PREDICT_WORKERS_ENV, "resolved", 0), + (PREDICT_WORKERS_ENV, "resolved", "18"), + (PREDICT_WORKERS_ENV, "resolution", "process_cpu_count_fallback"), + (PREDICT_WORKERS_ENV, "unexpected", 1), + ), +) +def test_malformed_audit_thread_controls_are_refused( + monkeypatch: pytest.MonkeyPatch, variable: str, field: str, value: object +) -> None: + binding = _binding_under(monkeypatch, BASE_HOST) + binding["audit_thread_controls"][variable][field] = value + + with pytest.raises(ValueError): + _validate_binding(binding) + + +@pytest.mark.parametrize( + ("variable", "configured"), + ( + (FIT_JOBS_ENV, "0"), + (FIT_JOBS_ENV, "-1"), + (FIT_JOBS_ENV, "01"), + (FIT_JOBS_ENV, "four"), + (PREDICT_WORKERS_ENV, "0"), + (PREDICT_WORKERS_ENV, "2.0"), + (PREDICT_WORKERS_ENV, " 3"), + ), +) +def test_malformed_thread_environment_is_refused_when_binding_the_worker( + monkeypatch: pytest.MonkeyPatch, variable: str, configured: str +) -> None: + _apply_thread_setting(monkeypatch, BASE_HOST) + monkeypatch.setenv(variable, configured) + + with pytest.raises(ValueError, match=variable): + worker_identity_module.primary_qrf_worker_execution_binding() 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 b683fbbfbf..1250b73afd 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 @@ -3252,26 +3252,22 @@ def test_primary_qrf_worker_identity_memo_reuses_graph_and_clear_recomputes( @pytest.mark.parametrize( "name", ("POPULACE_FIT_N_JOBS", "POPULACE_FIT_PREDICT_WORKERS") ) -def test_primary_qrf_worker_identity_memo_binds_environment( +def test_primary_qrf_worker_identity_memo_ignores_thread_controls( _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch, name: str, ) -> None: + """Thread counts are recorded per binding, outside the cached identity.""" _source, calls = _worker_identity_memo_inputs monkeypatch.setenv(name, "1") - first = worker_identity_module.primary_qrf_worker_semantic_identity() + first = worker_identity_module.primary_qrf_worker_execution_binding() monkeypatch.setenv(name, "3") - second = worker_identity_module.primary_qrf_worker_semantic_identity() - assert second is not first - assert first["environment"]["semantic_controls"][name]["resolved"] == 1 - assert second["environment"]["semantic_controls"][name]["resolved"] == 3 - assert worker_identity_module._canonical_sha256( - first - ) != worker_identity_module._canonical_sha256(second) - assert len(calls) == 2 - monkeypatch.setenv(name, "1") - assert worker_identity_module.primary_qrf_worker_semantic_identity() is first - assert len(calls) == 2 + second = worker_identity_module.primary_qrf_worker_execution_binding() + assert first["audit_thread_controls"][name]["resolved"] == 1 + assert second["audit_thread_controls"][name]["resolved"] == 3 + assert first["semantic_identity"] == second["semantic_identity"] + assert first["semantic_identity_sha256"] == second["semantic_identity_sha256"] + assert len(calls) == 1 @pytest.mark.parametrize( @@ -3332,7 +3328,7 @@ def test_primary_qrf_worker_execution_binding_isolates_semantic_memo( def test_worker_identity_session_prime_matches_pipeline_binding( _session_primary_qrf_worker_identities, ) -> None: - key = worker_identity_module._primary_qrf_worker_identity_cache_key(None) + key = None memo = worker_identity_module._PRIMARY_QRF_WORKER_IDENTITY_CACHE assert key in memo first = memo[key] @@ -3812,8 +3808,6 @@ def changed_resource_bytes(path: Path) -> bytes: "uv_lock", "distribution_record", "environment_code", - "fit_jobs", - "predict_workers", "torch_backend_autoload", "python_dont_write_bytecode", "python_pycache_prefix", @@ -3870,15 +3864,6 @@ def test_late_primary_worker_authentication_rejects_semantic_matrix( refresh_environment_code = True elif semantic_change == "environment_code": semantic["transitive_environment_code_sha256"] = "0" * 64 - elif semantic_change == "fit_jobs": - semantic["environment"]["semantic_controls"]["POPULACE_FIT_N_JOBS"][ - "resolved" - ] = 1 - elif semantic_change == "predict_workers": - predict = semantic["environment"]["semantic_controls"][ - "POPULACE_FIT_PREDICT_WORKERS" - ] - predict["resolved"] = int(predict["resolved"]) + 1 elif semantic_change == "python_dont_write_bytecode": semantic["environment"]["overrides"]["PYTHONDONTWRITEBYTECODE"] = "0" elif semantic_change == "python_pycache_prefix": @@ -4165,8 +4150,9 @@ def test_late_primary_resources_bind_donor_content_and_execution_config( "semantic_identity", "semantic_identity_sha256", "audit_aliases", + "audit_thread_controls", } - assert worker["schema_version"] == 1 + assert worker["schema_version"] == 2 semantic = worker["semantic_identity"] assert semantic["worker_module"]["name"] == ( "microcosm.build.us_runtime.puf_qrf_worker" @@ -4221,7 +4207,8 @@ def test_late_primary_resources_bind_donor_content_and_execution_config( "PYTHONDONTWRITEBYTECODE", "PYTHONPYCACHEPREFIX", ] - assert environment["semantic_controls"] == { + assert "semantic_controls" not in environment + assert worker["audit_thread_controls"] == { "POPULACE_FIT_N_JOBS": {"configured": None, "resolved": -1}, "POPULACE_FIT_PREDICT_WORKERS": { "configured": "2", diff --git a/tools/us_bundle_generation/imputation.py b/tools/us_bundle_generation/imputation.py index d0f69f76ce..e934b268a5 100644 --- a/tools/us_bundle_generation/imputation.py +++ b/tools/us_bundle_generation/imputation.py @@ -954,7 +954,7 @@ def _worker_execution_template() -> dict[str, object]: "surface": "execution_profile", "resolve_as": "worker_execution", "template": { - "schema_version": 1, + "schema_version": 2, "semantic_identity": { "resolver_op": "primary_qrf_worker_semantic_identity" }, @@ -962,6 +962,9 @@ def _worker_execution_template() -> dict[str, object]: "resolver_op": "primary_qrf_worker_semantic_identity_sha256" }, "audit_aliases": {"resolver_op": "primary_qrf_worker_audit_aliases"}, + "audit_thread_controls": { + "resolver_op": "primary_qrf_worker_audit_thread_controls" + }, }, } From 4f2ae2a7d102a54db4e549d7e339164b8582400d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:28:43 +0400 Subject: [PATCH 5/8] Stop comparing QRF fit-job counts on resume POPULACE_FIT_N_JOBS sets how many threads fit each forest and changes no draw, so a resume no longer has to match it. - QRF.fit_draw_next no longer compares the count saved in the chain state, and QRFChainState equality ignores it. The state still records the value in force when the chain started, so saved states keep their bytes. - The ACS transfer target bank checks a saved target's predecessor digest with the count that target saved, so it reuses the target instead of rebuilding it. - The PUF support base builder keeps recording both QRF thread variables in its run configuration and skips them on resume, through StageRuntime's new resume_ignored_run_config_paths. BLAS and OpenMP thread counts and PYTHONHASHSEED stay compared. Also address review round 2: a live environment that cannot be bound now reports its own error instead of a malformed recorded worker, and the docstrings, operator docs and changelog describe the new behaviour. Co-Authored-By: Claude Opus 5.5 --- ...redict-workers-joblib-cpu-count.changed.md | 6 +- docs/evidence/spec-engine/us-f0-coverage.json | 16 +-- docs/us-modal-stage-runbook.md | 2 +- docs/us-multispine-operator-ordering.md | 19 ++-- .../microcosm/build/outer_stage_runtime.py | 30 +++++- .../build/spec_engine/inventory_coverage.py | 4 +- .../build/us_runtime/acs_transfer_bank.py | 21 ++-- .../build/us_runtime/stacked_spine.py | 10 +- .../build/us_runtime/worker_identity.py | 13 +-- packages/microcosm-build/tests/conftest.py | 2 +- .../shared/test_outer_stage_runtime.py | 33 ++++++ .../shared/test_spec_engine_loader.py | 2 +- .../engine_free/us/test_puf_qrf_chain.py | 42 ++++++++ .../engine_free/us/test_us_acs_transfer.py | 68 +++++++++++- .../us/test_us_puf_support_base_builder.py | 67 ++++++++++++ .../us/test_us_qrf_predict_worker_default.py | 20 +++- .../us/test_us_qrf_worker_thread_controls.py | 100 +++++++++++++++++- .../engine_free/us/test_us_stacked_spine.py | 8 +- .../us/test_us_multispine_pool_tool.py | 2 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 33 +++--- .../tests/engine_free/shared/test_qrf.py | 53 +++++++--- .../shared/test_qrf_worker_counts.py | 17 ++- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- tools/build_us_puf_support_base.py | 32 ++++-- 24 files changed, 509 insertions(+), 93 deletions(-) diff --git a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md index 36173314de..76f31138af 100644 --- a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md +++ b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md @@ -1,3 +1,5 @@ -Size the QRF draw's thread pool from the CPUs the process may use, and stop comparing thread counts when a recorded primary-QRF worker is checked against the live one. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, and 1 when joblib has turned multiprocessing off, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. A `LOKY_MAX_CPU_COUNT` that is not an integer, which joblib refuses, now fails with an error naming it. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. +Size the QRF draw's thread pool from the CPUs the process may use, and stop treating QRF thread counts as something a pool load or a resume must match. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, and 1 when joblib has turned multiprocessing off, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. A `LOKY_MAX_CPU_COUNT` that is not an integer is refused by joblib; the draw's pool sizing and the worker binding report it by name. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. -Because the default count now follows the machine, the primary-QRF worker binding (`worker_identity.py`, now schema 2) records `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` in a new `audit_thread_controls` field next to the interpreter paths in `audit_aliases`, and no longer in its semantic identity. Loading a pool for release or scoring, resuming the primary-QRF checkpoint, the pool's checkpoint identity and the spec engine's worker resolution compare only the semantic identity, so a pool built on a host with 18 usable CPUs now loads under the release tool's `LOKY_MAX_CPU_COUNT` cap of 16, and a pool build and a release may set different thread counts. Building the binding still refuses a malformed count. An unset prediction-worker count is recorded as `resolution: "joblib_cpu_count_fallback"`; `"os_cpu_count_fallback"` still validates. Schema-1 bindings still validate, and a pool that holds one is refused because its worker identity changed. The semantic identity is now cached per lock only. The spec template for the worker binding (`imputation.yaml` and `imputation.schema.json`) names schema 2 and the new field. The frozen schema-4 shape that the scoring-only relocation of schema-9 pools compares with their sealed records keeps the counts where that code recorded them, an unset count as the host's `os.cpu_count()`, so that comparison is unchanged and still includes the counts. The unused older binding in `stacked_spine.py` records the joblib default under the new label. A base run or pool build interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. +The primary-QRF worker binding (`worker_identity.py`, now schema 2) records `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` in a new `audit_thread_controls` field next to the interpreter paths in `audit_aliases`, and no longer in its semantic identity. Loading a pool for release or scoring, resuming the primary-QRF checkpoint, the pool's checkpoint identity and the spec engine's worker resolution compare only the semantic identity, so a pool built with one pair of counts loads under another, whether the counts come from the machine or from the two variables. Building the binding still refuses a malformed count. An unset prediction-worker count is recorded as `resolution: "joblib_cpu_count_fallback"`; `"os_cpu_count_fallback"` still validates. Schema-1 bindings still validate, and a pool that holds one is refused because its worker identity changed. The semantic identity is now cached per lock only. The spec template for the worker binding (`imputation.yaml` and `imputation.schema.json`) names schema 2 and the new field. The frozen schema-4 shape that the scoring-only relocation of schema-9 pools compares with their sealed records keeps the counts where that code recorded them, an unset count as the host's `os.cpu_count()`, so that comparison is unchanged and still includes the counts. The unused older binding in `stacked_spine.py` records the joblib default under the new label. + +A resume no longer compares `POPULACE_FIT_N_JOBS`. `QRF.fit_draw_next` accepts a chain state that recorded another count, and `QRFChainState` equality ignores the count; the state still records the value in force when the chain started, so saved states keep their bytes. The ACS transfer target bank checks a saved target's predecessor digest with the count that target saved, so it reuses the target where it used to rebuild it. The PUF support base builder records both QRF thread variables in its run configuration and no longer compares them on resume (`StageRuntime`'s new `resume_ignored_run_config_paths`); the BLAS and OpenMP thread counts and `PYTHONHASHSEED` stay compared. A base run or pool build interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 0d024b43ae..bf655f3c2f 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": "1452f5d308ed2119faf6cdf00d727c62d6888b677f3807f798c11b45e324c1be", - "protocol_sha256": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814" + "map_sha256": "4d2f90795e43ba1ca1170b08c90d75d40d8bf1ee101210d7eba0771a5817fc1b", + "protocol_sha256": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a" }, "failures": [], "observed": { - "map_sha256": "1452f5d308ed2119faf6cdf00d727c62d6888b677f3807f798c11b45e324c1be", - "protocol_sha256": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814" + "map_sha256": "4d2f90795e43ba1ca1170b08c90d75d40d8bf1ee101210d7eba0771a5817fc1b", + "protocol_sha256": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814", + "implementation_sha256": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814", + "implementation_sha256": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "bbee1e2239ed6fc47ab825c769a9f7364bc58030ed762c5eb24dcbf2e0e9af35" + "spec_sha256": "d663eccbf3b334da2520d6d89045742357a803daf01829adbad3ac7f3b6d6d98" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "bbee1e2239ed6fc47ab825c769a9f7364bc58030ed762c5eb24dcbf2e0e9af35" + "spec_sha256": "d663eccbf3b334da2520d6d89045742357a803daf01829adbad3ac7f3b6d6d98" }, "status": "pass" } diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index bb70b79e8a..52e66db486 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -1479,7 +1479,7 @@ archives. `experiments/us-acs-local-hours-rebuild-20260922/run-resources-and-staging-excerpt.json` measured 103,104.6 CPU-s over 7,218.1 s of wall, 14.3 cores on average. The QRF forest uses `n_jobs=-1` when `POPULACE_FIT_N_JOBS` is unset, and - prediction sizes its pool from `os.cpu_count()` when + prediction sizes its pool from `joblib.cpu_count()` when `POPULACE_FIT_PREDICT_WORKERS` is unset (`microcosm.fit.qrf`). Sixteen cores accommodate the observed average with 1.7 cores of headroom; the limit throttles use above sixteen. Neither the average nor the request diff --git a/docs/us-multispine-operator-ordering.md b/docs/us-multispine-operator-ordering.md index 19a1f4de37..1c68de774f 100644 --- a/docs/us-multispine-operator-ordering.md +++ b/docs/us-multispine-operator-ordering.md @@ -557,8 +557,8 @@ newly claimed outer route. #### Portable primary-QRF `worker_execution` identity -Worker identity schema v1 separates semantic authentication from launcher -aliases. `semantic_identity` binds the interpreter-launcher bytes, the exact +Worker identity schema v2 separates semantic authentication from launcher +aliases and thread counts. `semantic_identity` binds the interpreter-launcher bytes, the exact loaded Python runtime library (or the executable for a static build), and a digest of the source and extension bytes for stdlib modules observed during or present after a clean worker import. It also binds implementation, version and @@ -566,9 +566,9 @@ ABI, cache tag, canonical `pyvenv.cfg` fields, worker-module source, the statically resolved Python closure plus every Microcosm namespace file opened by that clean import, the exact approved `uv.lock`, installed-distribution/RECORD and combined -transitive environment/code digests, arguments after `argv[0]` with `argv[0]` -replaced by `{python_interpreter}`, and configured/resolved fit-job and -prediction-worker controls. `TORCH_DEVICE_BACKEND_AUTOLOAD=0` is a forced, +transitive environment/code digests, and arguments after `argv[0]` with +`argv[0]` replaced by `{python_interpreter}`. +`TORCH_DEVICE_BACKEND_AUTOLOAD=0` is a forced, bound worker-bootstrap override applied before the QRF runtime can import Torch. Before the clean import, identity construction enumerates all installed `torch.backends` entry-point declarations, refuses duplicate @@ -577,8 +577,13 @@ binds declarations belonging to selected distributions. Authentication compares that payload and its `semantic_identity_sha256`, so byte-identical interpreters reached through different worktrees remain the same worker. `audit_aliases` records absolute -`sys_executable`, `sys_prefix`, and raw `argv_template_0`, but those aliases are -never compared for authentication. +`sys_executable`, `sys_prefix`, and raw `argv_template_0`, and +`audit_thread_controls` records the configured and resolved fit-job and +prediction-worker counts. Neither field is compared for authentication: the +counts change no imputed value, and an unset prediction-worker count follows +the machine. Schema v1 records, which kept the counts in `semantic_identity`, +still validate, and a pool holding one is refused because its worker identity +changed. A schema-9 gate-failed pool receives no implicit alias exception. Its only relocation path is the scoring-only loader with an operator-supplied diff --git a/packages/microcosm-build/src/microcosm/build/outer_stage_runtime.py b/packages/microcosm-build/src/microcosm/build/outer_stage_runtime.py index 1fd9a9fbc7..e0e70006ab 100644 --- a/packages/microcosm-build/src/microcosm/build/outer_stage_runtime.py +++ b/packages/microcosm-build/src/microcosm/build/outer_stage_runtime.py @@ -12,7 +12,7 @@ import json import os import re -from collections.abc import Mapping, Sequence +from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass from pathlib import Path from typing import Any @@ -222,7 +222,12 @@ class LoadedStageCheckpoint: class StageRuntime: - """Advance and resume one exact prefix of an immutable stage pipeline.""" + """Advance and resume one exact prefix of an immutable stage pipeline. + + ``resume_ignored_run_config_paths`` names values inside ``run_config``, each + as its sequence of nested keys, that the first run records and a resume + does not compare. The recorded run config keeps the first run's values. + """ def __init__( self, @@ -230,11 +235,13 @@ def __init__( pipeline: StagePipeline, *, run_config: Mapping[str, object] | None = None, + resume_ignored_run_config_paths: Iterable[tuple[str, ...]] = (), ) -> None: if not isinstance(pipeline, StagePipeline): raise TypeError("pipeline must be a StagePipeline.") self._root = Path(checkpoint_dir) self._pipeline = pipeline + self._resume_ignored_run_config_paths = tuple(resume_ignored_run_config_paths) self._context_path = self._root / OUTER_STAGE_CONTEXT_FILENAME requested_config = ( None @@ -271,9 +278,10 @@ def metadata(self) -> dict[str, dict[str, object]]: def require_run_config(self, expected: Mapping[str, object]) -> dict[str, object]: """Require the resume arguments to equal the locked first-run config.""" - normalized = _normalize_json_mapping(expected, label="run_config") context = self._load_context() - if normalized != context.run_config: + if self._resume_compared_run_config( + expected + ) != self._resume_compared_run_config(context.run_config): raise ValueError( "outer-stage run_config differs from the locked run context; " "start a new checkpoint directory for changed build inputs." @@ -281,6 +289,20 @@ def require_run_config(self, expected: Mapping[str, object]) -> dict[str, object self._context = context return _normalize_json_mapping(context.run_config, label="run_config") + def _resume_compared_run_config( + self, run_config: Mapping[str, object] + ) -> dict[str, object]: + """Return a copy of ``run_config`` without the values a resume skips.""" + + compared = _normalize_json_mapping(run_config, label="run_config") + for *parent_keys, final_key in self._resume_ignored_run_config_paths: + parent: object = compared + for key in parent_keys: + parent = parent.get(key) if isinstance(parent, dict) else None + if isinstance(parent, dict): + parent.pop(final_key, None) + return compared + def require_ready(self, stage_name: str) -> None: """Require that exactly the named stage's predecessor prefix completed.""" 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 07b0d965ba..8d5ac2802c 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 @@ -404,8 +404,8 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The QRF draw's default thread count, joblib.cpu_count() in place of # os.cpu_count() in microcosm.fit.qrf, moves both again; no draw changes. - "seed_map": "1452f5d308ed2119faf6cdf00d727c62d6888b677f3807f798c11b45e324c1be", - "seed_protocol": "d75302d7bb53e9a83db1d733bbb3df9aec78130f046d1ade95689abaa1dda814", + "seed_map": "4d2f90795e43ba1ca1170b08c90d75d40d8bf1ee101210d7eba0771a5817fc1b", + "seed_protocol": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer_bank.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer_bank.py index 8e5ab63f44..b9222b4a39 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer_bank.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_transfer_bank.py @@ -9,7 +9,7 @@ import tempfile import time from collections.abc import Mapping, Sequence -from dataclasses import asdict, is_dataclass +from dataclasses import asdict, is_dataclass, replace from enum import Enum from pathlib import Path @@ -578,19 +578,24 @@ def _load_pattern_steps( raise ValueError( f"ACS transfer target carries unexpected pattern {pattern!r}." ) - state_before = expected_states[pattern] - expected_before_sha256 = _mapping_sha256(state_before.to_dict()) - if raw_step.get("state_before_sha256") != expected_before_sha256: - raise ValueError( - f"ACS transfer target pattern {pattern!r} does not continue the " - "expected predecessor state." - ) state_after_payload = raw_step.get("state_after") if not isinstance(state_after_payload, Mapping): raise ValueError( f"ACS transfer target pattern {pattern!r} lacks state_after." ) state_after = QRFChainState.from_dict(state_after_payload) + # A chain started in this process carries this process's fit-job count, + # and the saved digest covers the count the saved chain started with. + # The count changes no draw, so the digest is checked with the saved one. + state_before = replace( + expected_states[pattern], fit_n_jobs=state_after.fit_n_jobs + ) + expected_before_sha256 = _mapping_sha256(state_before.to_dict()) + if raw_step.get("state_before_sha256") != expected_before_sha256: + raise ValueError( + f"ACS transfer target pattern {pattern!r} does not continue the " + "expected predecessor state." + ) _validate_state_transition( state_before, state_after, diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py index a5b7b93ed9..0b4593254a 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/stacked_spine.py @@ -5679,10 +5679,13 @@ def require_positive_integer(value: object, *, label: str) -> int: f"{boundary}: attested legacy primary-QRF worker changed." ) else: + # Outside the ``try``: a live environment that cannot be bound + # reports its own error, not a malformed recorded binding. + live_worker = _late_primary_qrf_worker_execution_binding() try: semantically_equal = worker_identity_runtime.primary_qrf_worker_bindings_semantically_equal( recorded_worker, - _late_primary_qrf_worker_execution_binding(), + live_worker, boundary=f"{boundary}: late primary-QRF worker", ) except ValueError as exc: @@ -11963,8 +11966,9 @@ def _run_stacked_puf_pass_evaluate( resume_status = "resumed" # The sidecar's bytes are retained on resume, so the receipt must # carry the sidecar's own authenticated self-digest: the live - # binding's digest hashes the current audit aliases, which may - # differ from the relocated sidecar's without changing meaning. + # binding's digest hashes the current audit aliases and thread + # controls, which may differ from the sidecar's without changing + # meaning. reported_input_binding_sha256 = observed_input_binding["sha256"] else: if checkpoint_dir.exists() and any(checkpoint_dir.iterdir()): 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 cdf70c6cdb..d8ead25b93 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 @@ -25,11 +25,12 @@ from packaging.utils import canonicalize_name #: Schema 2 records the fit-job and prediction-worker counts in -#: ``audit_thread_controls``, outside the semantic identity that every -#: recorded-versus-live comparison reads. The counts change no imputed value -#: (``microcosm-fit``'s ``test_qrf_worker_counts.py``), and an unset -#: prediction-worker count follows the machine, so a pool built on one host -#: stays comparable on another. +#: ``audit_thread_controls``, outside the semantic identity that recorded-versus- +#: live comparisons read. The counts change no imputed value (``microcosm-fit``'s +#: ``test_qrf_worker_counts.py``), and an unset prediction-worker count follows +#: the machine, so a pool built on one host stays comparable on another. The one +#: exception is the frozen schema-4 record that the scoring-only relocation of a +#: sealed pool compares field by field, counts included. PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION = 2 #: Schema 1 kept the counts in ``semantic_identity.environment.semantic_controls``. #: Those records still validate; they never equal a schema-2 identity. @@ -1380,7 +1381,7 @@ def primary_qrf_worker_semantic_identity( """Return the shared canonical worker identity, excluding launcher aliases. A process's interpreter, source tree, and installed distributions are - attested once per process for each lock and bound-environment combination. + attested once per process for each lock. Anything that deliberately mutates them must call ``clear_primary_qrf_worker_identity_cache()`` before reattesting. The returned object graph is shared across calls and must be treated as read-only. diff --git a/packages/microcosm-build/tests/conftest.py b/packages/microcosm-build/tests/conftest.py index 8de2e3dc35..46276df194 100644 --- a/packages/microcosm-build/tests/conftest.py +++ b/packages/microcosm-build/tests/conftest.py @@ -223,7 +223,7 @@ def allow_logbook_network( def _session_primary_qrf_worker_identities(): """Attest the real installed worker once; retain pristine identities by key. - Additional lock/control keys (such as the sealed legacy lock) are populated + Additional lock keys (such as the sealed legacy lock) are populated by the real code on first use in ordinary tests, never by a fabricated identity. Import lazily so unrelated build tests need neither US extras nor a probe. """ diff --git a/packages/microcosm-build/tests/engine_free/shared/test_outer_stage_runtime.py b/packages/microcosm-build/tests/engine_free/shared/test_outer_stage_runtime.py index 00216ab451..047a7cbefb 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_outer_stage_runtime.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_outer_stage_runtime.py @@ -170,6 +170,39 @@ def test_runtime_requires_the_exact_predecessor_prefix(tmp_path: Path) -> None: StageRuntime(tmp_path, _pipeline(), run_config={"seed": 43}) +def test_resume_skips_only_the_named_run_config_values(tmp_path: Path) -> None: + ignored_paths = (("threads", "fit_jobs"),) + first_config = {"seed": 42, "threads": {"fit_jobs": "1", "numeric": "1"}} + StageRuntime( + tmp_path, + _pipeline(), + run_config=first_config, + resume_ignored_run_config_paths=ignored_paths, + ) + + resumed = StageRuntime( + tmp_path, + _pipeline(), + run_config={"seed": 42, "threads": {"fit_jobs": "8", "numeric": "1"}}, + resume_ignored_run_config_paths=ignored_paths, + ) + assert resumed.context.run_config == first_config + + with pytest.raises(ValueError, match="locked run context"): + StageRuntime( + tmp_path, + _pipeline(), + run_config={"seed": 42, "threads": {"fit_jobs": "1", "numeric": "2"}}, + resume_ignored_run_config_paths=ignored_paths, + ) + with pytest.raises(ValueError, match="locked run context"): + StageRuntime( + tmp_path, + _pipeline(), + run_config={"seed": 42, "threads": {"fit_jobs": "8", "numeric": "1"}}, + ) + + def test_runtime_carries_a_checkpoint_without_rewriting_it(tmp_path: Path) -> None: runtime = StageRuntime(tmp_path, _pipeline()) source = runtime.complete("source", _source_frame(), metadata={"source": "pool"}) 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 996f5c30cf..3441fcf197 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 @@ -35,7 +35,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # The QRF draw's default thread count, joblib.cpu_count() in # microcosm.fit.qrf, moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "1b9b05539a15598c392feeea440e460888afa19c974270945f4a1bd08a26af8e" + "9ea8f2db1ea7d522f2bd292d5ffcbdaaa4cb94d0770bd3eeca88c3c924fd82fd" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/us/test_puf_qrf_chain.py b/packages/microcosm-build/tests/engine_free/us/test_puf_qrf_chain.py index 3163cbbc81..e03d2f117c 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_puf_qrf_chain.py +++ b/packages/microcosm-build/tests/engine_free/us/test_puf_qrf_chain.py @@ -507,6 +507,48 @@ def test_target_subprocess_chain_matches_monolith_raw_bits_and_final_frame( run_primary_puf_qrf_chain(checkpoint_dir) +def test_primary_qrf_chain_resumes_under_changed_thread_counts( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Rebuilt targets are the same bytes under other thread counts.""" + monkeypatch.setenv("POPULACE_FIT_N_JOBS", "1") + monkeypatch.setenv("POPULACE_FIT_PREDICT_WORKERS", "1") + checkpoint_dir = tmp_path / "primary_qrf" + initialize_primary_puf_qrf_chain( + _expanded_frame(), + _donor(), + checkpoint_dir, + predictors=_PREDICTORS, + person_outputs=_PERSON_OUTPUTS, + tax_unit_outputs=_TAX_UNIT_OUTPUTS, + n_estimators=2, + seed=3, + ) + run_primary_puf_qrf_chain( + checkpoint_dir, + environment={ + "POPULACE_FIT_N_JOBS": "1", + "POPULACE_FIT_PREDICT_WORKERS": "1", + }, + ) + later_targets = sorted((checkpoint_dir / "targets").glob("*.h5"))[1:] + assert later_targets + original_bytes = {path: path.read_bytes() for path in later_targets} + for path in later_targets: + path.unlink() + + run_primary_puf_qrf_chain( + checkpoint_dir, + environment={ + "POPULACE_FIT_N_JOBS": "2", + "POPULACE_FIT_PREDICT_WORKERS": "3", + }, + ) + + assert {path: path.read_bytes() for path in later_targets} == original_bytes + + def test_resumed_earnings_chain_keeps_children_out_of_allocation( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_transfer.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_transfer.py index 9deedd116d..1680e29cbe 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_transfer.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_transfer.py @@ -491,12 +491,14 @@ def predict(self, frame: pd.DataFrame) -> pd.DataFrame: def _run_bank_fixture( target_bank: AcsTransferTargetBankStore | None = None, + *, + seed: int = 37, ) -> AcsTransferResult: return transfer_acs_inputs( _recipient_frame(), _donor_frame(), target_families={"person": {_BANK_FAMILY: _BANK_TARGETS}}, - seed=37, + seed=seed, n_estimators=1, target_bank=target_bank, regime_evidence_targets=tuple(("person", target) for target in _BANK_TARGETS), @@ -1275,6 +1277,70 @@ def interrupt_after_first_durable_target(checkpoint) -> None: ) +def test_target_bank_reuses_targets_under_a_changed_fit_job_count( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + _lock_bank_fixture_threads(monkeypatch) + uninterrupted = _run_bank_fixture(_bank_store(tmp_path / "uninterrupted-bank")) + + bank_root = tmp_path / "interrupted-bank" + interrupted_bank = _bank_store(bank_root) + durable_write = interrupted_bank.write_target + + def interrupt_after_first_durable_target(checkpoint) -> None: + durable_write(checkpoint) + if checkpoint.target_index == 0: + raise RuntimeError("fixture interrupt after durable ACS target 0") + + monkeypatch.setattr( + interrupted_bank, + "write_target", + interrupt_after_first_durable_target, + ) + with pytest.raises(RuntimeError, match="fixture interrupt"): + _run_bank_fixture(interrupted_bank) + + monkeypatch.setenv("POPULACE_FIT_N_JOBS", "2") + resumed_bank = _bank_store(bank_root) + resumed = _run_bank_fixture(resumed_bank) + _assert_transfer_results_exact(resumed, uninterrupted) + _assert_bank_receipt( + resumed_bank, + sources=("checkpoint", "rebuilt", "rebuilt"), + load_statuses=("resumed", "missing", "missing"), + ) + + monkeypatch.setenv("POPULACE_FIT_N_JOBS", "3") + complete_bank = _bank_store(bank_root) + reloaded = _run_bank_fixture(complete_bank) + _assert_transfer_results_exact(reloaded, uninterrupted) + _assert_bank_receipt( + complete_bank, + sources=("checkpoint", "checkpoint", "checkpoint"), + load_statuses=("resumed", "resumed", "resumed"), + ) + + +def test_target_bank_rebuilds_targets_saved_from_another_chain_state( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + _lock_bank_fixture_threads(monkeypatch) + bank_root = tmp_path / "bank" + _run_bank_fixture(_bank_store(bank_root), seed=37) + + other_seed_bank = _bank_store(bank_root) + _run_bank_fixture(other_seed_bank, seed=38) + + targets = _assert_bank_receipt( + other_seed_bank, + sources=("rebuilt", "rebuilt", "rebuilt"), + load_statuses=("invalid_rebuild", "invalid_rebuild", "invalid_rebuild"), + ) + assert "predecessor state" in targets["0"]["invalid_checkpoint"]["message"] + + def test_target_bank_identity_mismatch_rebuilds_only_stale_target( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_builder.py index 31a612a3d7..d141097858 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_puf_support_base_builder.py @@ -1296,6 +1296,73 @@ def test_outer_stage_resume_rejects_changed_builder_code( ) +def _resumable_builder_args( + builder, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +): + monkeypatch.setattr( + builder, + "_builder_code_identity", + lambda: {"source_sha256": "builder"}, + ) + return builder._parse_args( + [ + "--base-h5", + str(tmp_path / "base.h5"), + "--puf-h5", + str(tmp_path / "puf.h5"), + "--out", + str(tmp_path / "out"), + "--without-block-ladder", + "--checkpoint-dir", + str(tmp_path / "checkpoints"), + ] + ) + + +@pytest.mark.parametrize( + "variable", + ("POPULACE_FIT_N_JOBS", "POPULACE_FIT_PREDICT_WORKERS"), +) +def test_outer_stage_resume_accepts_a_changed_qrf_thread_count( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + variable: str, +) -> None: + builder = _load_support_builder_module() + args = _resumable_builder_args(builder, monkeypatch, tmp_path) + monkeypatch.delenv(variable, raising=False) + first_config = builder._open_stage_runtime(args).context.run_config + assert first_config["thread_environment"][variable] is None + + monkeypatch.setenv(variable, "3") + resumed = builder._open_stage_runtime(args) + + assert resumed.context.run_config == first_config + + +@pytest.mark.parametrize( + ("variable", "first_value", "changed_value"), + (("OMP_NUM_THREADS", "1", "2"), ("PYTHONHASHSEED", "0", "1")), +) +def test_outer_stage_resume_refuses_other_changed_environment_values( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + variable: str, + first_value: str, + changed_value: str, +) -> None: + builder = _load_support_builder_module() + args = _resumable_builder_args(builder, monkeypatch, tmp_path) + monkeypatch.setenv(variable, first_value) + builder._open_stage_runtime(args) + + monkeypatch.setenv(variable, changed_value) + with pytest.raises(ValueError, match="run_config differs"): + builder._open_stage_runtime(args) + + def test_puf_donor_builder_threads_explicit_source_year_agi( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py index f376c54c2b..c5851f2bde 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_predict_worker_default.py @@ -34,7 +34,8 @@ def _patch_joblib_cpu_count(monkeypatch: pytest.MonkeyPatch, value: int) -> None: def patched_cpu_count(only_physical_cores: bool = False) -> int: - return value + # A physical-core count that differs, so a caller asking for it shows. + return value + 100 if only_physical_cores else value monkeypatch.setattr(joblib, "cpu_count", patched_cpu_count) @@ -221,15 +222,26 @@ def test_schema_4_projection_records_an_unset_count_as_schema_4_code_did( recorded = deepcopy(projected) recorded["argv_template"][0] = relocated_python recorded["interpreter"]["executable"] = relocated_python - recorded["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] = dict( - schema_4_controls - ) assert ( worker_identity_module._legacy_worker_execution_mismatch_paths( recorded, projected ) == worker_identity_module.LEGACY_WORKER_PERMITTED_MISMATCHES ) + # The frozen comparison still includes the counts: a sealed record with + # another count is not just the two permitted interpreter paths. + recorded["environment"]["semantic_controls"][PREDICT_WORKERS_ENV] = { + "configured": "18", + "resolved": 18, + "resolution": "environment_override", + } + mismatches = worker_identity_module._legacy_worker_execution_mismatch_paths( + recorded, projected + ) + assert mismatches != worker_identity_module.LEGACY_WORKER_PERMITTED_MISMATCHES + assert ( + f"environment.semantic_controls.{PREDICT_WORKERS_ENV}.configured" in mismatches + ) def test_schema_4_projection_keeps_an_override_label( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py index bea978d4e4..15626f74af 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py @@ -10,7 +10,8 @@ with the live one reads only the semantic identity: loading a pool for release or scoring, resuming the primary-QRF checkpoint, the pool's checkpoint identity, and the spec engine's worker resolution. A pool built on -an 18-CPU host therefore loads under the release tool's 16-CPU cap. +an 18-CPU host therefore loads under the release tool's 16-CPU cap, and a +checkpoint started under one pair of counts resumes under another. Schema-1 bindings, which kept the counts in ``semantic_identity.environment.semantic_controls``, still validate, so a pool @@ -29,6 +30,7 @@ from microcosm.build.spec_engine import imputation_semantics from test_support.microcosm_build.us_stacked_spine import * +REAL_JOBLIB_CPU_COUNT = joblib.cpu_count FIT_JOBS_ENV = "POPULACE_FIT_N_JOBS" PREDICT_WORKERS_ENV = "POPULACE_FIT_PREDICT_WORKERS" JOBLIB_FALLBACK = "joblib_cpu_count_fallback" @@ -45,6 +47,7 @@ BASE_HOST = (None, None, 18) RELEASE_UNDER_CPU_CAP = (None, None, 16) OVERRIDDEN = ("2", "9", 4) +RESUME_ON_ANOTHER_HOST = ("5", "9", 4) THREAD_SETTINGS = (BASE_HOST, RELEASE_UNDER_CPU_CAP, OVERRIDDEN) @@ -63,11 +66,21 @@ def _apply_thread_setting( monkeypatch.setenv(name, value) def patched_cpu_count(only_physical_cores: bool = False) -> int: - return joblib_cpu_count + # A physical-core count that differs, so a caller asking for it shows. + return joblib_cpu_count + 100 if only_physical_cores else joblib_cpu_count monkeypatch.setattr(joblib, "cpu_count", patched_cpu_count) +def _use_real_joblib_cpu_count( + monkeypatch: pytest.MonkeyPatch, loky_max_cpu_count: str +) -> None: + for name in (FIT_JOBS_ENV, PREDICT_WORKERS_ENV): + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(joblib, "cpu_count", REAL_JOBLIB_CPU_COUNT) + monkeypatch.setenv("LOKY_MAX_CPU_COUNT", loky_max_cpu_count) + + def _binding_under( monkeypatch: pytest.MonkeyPatch, setting: tuple[str | None, str | None, int], @@ -224,7 +237,7 @@ def test_primary_checkpoint_resources_resume_under_other_thread_controls( recorded = stacked_spine_module.stacked_late_primary_resource_receipts( donor, **arguments ) - _apply_thread_setting(monkeypatch, OVERRIDDEN) + _apply_thread_setting(monkeypatch, RESUME_ON_ANOTHER_HOST) live = stacked_spine_module.stacked_late_primary_resource_receipts( donor, **arguments ) @@ -314,7 +327,7 @@ def run(binding: dict[str, object]): sidecar_bytes = sidecar_path.read_bytes() assert initialized["resume_status"] == "initialized" - _apply_thread_setting(monkeypatch, OVERRIDDEN) + _apply_thread_setting(monkeypatch, RESUME_ON_ANOTHER_HOST) live_binding = input_binding() assert live_binding["sha256"] != json.loads(sidecar_bytes)["sha256"], ( "the recorded thread controls must move the live sidecar digest" @@ -325,6 +338,85 @@ def run(binding: dict[str, object]): assert sidecar_path.read_bytes() == sidecar_bytes +@pytest.mark.parametrize("loky_max_cpu_count", ["1", "2"]) +def test_unset_prediction_workers_record_the_real_joblib_cpu_count( + monkeypatch: pytest.MonkeyPatch, loky_max_cpu_count: str +) -> None: + _use_real_joblib_cpu_count(monkeypatch, loky_max_cpu_count) + expected = REAL_JOBLIB_CPU_COUNT() + assert 1 <= expected <= int(loky_max_cpu_count) + + controls = worker_identity_module.primary_qrf_worker_execution_binding()[ + "audit_thread_controls" + ][PREDICT_WORKERS_ENV] + + assert controls == { + "configured": None, + "resolved": expected, + "resolution": JOBLIB_FALLBACK, + } + + +def test_pool_recorded_under_a_larger_loky_cap_loads_under_a_smaller_one( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The release tool's ``LOKY_MAX_CPU_COUNT`` cap, with joblib unpatched.""" + _use_real_joblib_cpu_count(monkeypatch, "2") + if REAL_JOBLIB_CPU_COUNT() < 2: + pytest.skip("needs at least two usable CPUs") + recorded = _fixture_primary_execution_config_binding() + _use_real_joblib_cpu_count(monkeypatch, "1") + live_controls = worker_identity_module.primary_qrf_worker_execution_binding()[ + "audit_thread_controls" + ] + + recorded_controls = recorded["qrf"]["worker_execution"]["audit_thread_controls"] + assert recorded_controls[PREDICT_WORKERS_ENV]["resolved"] == 2 + assert live_controls[PREDICT_WORKERS_ENV]["resolved"] == 1 + _validate_primary_config_against_live_worker( + recorded, boundary="pool load under a smaller CPU cap" + ) + + +@pytest.mark.parametrize( + ("variable", "configured", "message"), + ( + ("LOKY_MAX_CPU_COUNT", "four", "LOKY_MAX_CPU_COUNT"), + (FIT_JOBS_ENV, "0", FIT_JOBS_ENV), + (PREDICT_WORKERS_ENV, "two", PREDICT_WORKERS_ENV), + ), +) +def test_a_live_worker_that_cannot_be_bound_is_not_blamed_on_the_pool( + monkeypatch: pytest.MonkeyPatch, variable: str, configured: str, message: str +) -> None: + """The error names the live setting, not "worker binding is malformed".""" + _apply_thread_setting(monkeypatch, BASE_HOST) + recorded = _fixture_primary_execution_config_binding() + _use_real_joblib_cpu_count(monkeypatch, "2") + monkeypatch.setenv(variable, configured) + + with pytest.raises(ValueError, match=message) as refusal: + _validate_primary_config_against_live_worker( + recorded, boundary="pool load with a bad live setting" + ) + assert "malformed" not in str(refusal.value) + + +def test_identity_recomputed_under_other_thread_controls_is_unchanged( + _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch +) -> None: + """A later process attests afresh; its counts must not reach the identity.""" + _source, calls = _worker_identity_memo_inputs + _apply_thread_setting(monkeypatch, BASE_HOST) + first = deepcopy(worker_identity_module.primary_qrf_worker_semantic_identity()) + worker_identity_module.clear_primary_qrf_worker_identity_cache() + _apply_thread_setting(monkeypatch, RESUME_ON_ANOTHER_HOST) + second = worker_identity_module.primary_qrf_worker_semantic_identity() + + assert len(calls) == 2 + assert second == first + + def test_pool_checkpoint_identity_ignores_thread_controls( monkeypatch: pytest.MonkeyPatch, ) -> None: 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 1250b73afd..87c859e164 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 @@ -3274,17 +3274,17 @@ def test_primary_qrf_worker_identity_memo_ignores_thread_controls( "name", ("POPULACE_FIT_N_JOBS", "POPULACE_FIT_PREDICT_WORKERS") ) @pytest.mark.parametrize("value", ("0", "01", "invalid")) -def test_primary_qrf_worker_identity_memo_refuses_invalid_environment( +def test_primary_qrf_worker_binding_refuses_invalid_environment_before_attesting( _worker_identity_memo_inputs, monkeypatch: pytest.MonkeyPatch, name: str, value: str, ) -> None: - monkeypatch.setenv(name, "1") - worker_identity_module.primary_qrf_worker_semantic_identity() + _source, calls = _worker_identity_memo_inputs monkeypatch.setenv(name, value) with pytest.raises(ValueError, match=name): - worker_identity_module.primary_qrf_worker_semantic_identity() + worker_identity_module.primary_qrf_worker_execution_binding() + assert calls == [] def test_primary_qrf_worker_identity_memo_binds_lock( 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 e73deea4e8..cbe430ff63 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 @@ -365,7 +365,7 @@ def capture_equality(expected: object, actual: object) -> None: # solve and ssi_take_up, and the calibration contract's renamed modes. # The QRF draw's default thread count, joblib.cpu_count() in # microcosm.fit.qrf, moves it again. - "spec_sha256": "bbee1e2239ed6fc47ab825c769a9f7364bc58030ed762c5eb24dcbf2e0e9af35", + "spec_sha256": "d663eccbf3b334da2520d6d89045742357a803daf01829adbad3ac7f3b6d6d98", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index f6fd219c26..47db3319f9 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -62,7 +62,7 @@ import os from collections.abc import Callable, Mapping, Sequence from concurrent.futures import ThreadPoolExecutor -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace import joblib import numpy as np @@ -1387,10 +1387,12 @@ def _fit_n_jobs() -> int: negative ``n_jobs`` when it starts the fit's and ``apply``'s threads, as ``joblib.cpu_count() + 1 + n_jobs``, so ``-1`` already counts only the CPUs the process may use (see :func:`default_predict_workers`). Chain - states and the primary-QRF worker identity record the literal ``-1``, - not that count. If the environment variable is present it must be a - strict positive base-10 integer; in particular, an empty string is an - invalid configured value rather than a second spelling of "unset". + states and the ``audit_thread_controls`` of the primary-QRF worker binding + record the literal ``-1``, not that count, and no resume compares either + record: the count changes no draw. If the environment variable is present + it must be a strict positive base-10 integer; in particular, an empty + string is an invalid configured value rather than a second spelling of + "unset". Raises: ValueError: If ``POPULACE_FIT_N_JOBS`` is set to anything other than a @@ -1430,7 +1432,7 @@ def default_predict_workers() -> int: Raises: ValueError: If ``LOKY_MAX_CPU_COUNT`` is not an integer, which joblib - refuses, or joblib cannot read the cgroup CPU quota. + refuses, or joblib cannot parse the cgroup CPU quota. """ try: return joblib.cpu_count() @@ -1438,8 +1440,8 @@ def default_predict_workers() -> int: raise ValueError( "Cannot size the QRF draw's thread pool: joblib.cpu_count() failed " f"with LOKY_MAX_CPU_COUNT={os.environ.get('LOKY_MAX_CPU_COUNT')!r} " - f"({error}). Set LOKY_MAX_CPU_COUNT to an integer, or set " - f"{_PREDICT_WORKERS_ENV}." + f"({error}). LOKY_MAX_CPU_COUNT must be unset or an integer, and " + "the process's cgroup CPU quota must be readable." ) from error @@ -1724,6 +1726,11 @@ class QRFChainState: fingerprint only when the chain was started with ``groups``, so the state of an in-sample, ungrouped chain, and any state written before either existed, reads the same. + + ``fit_n_jobs`` records the ``POPULACE_FIT_N_JOBS`` value in force when the + chain started. It stays in :meth:`to_dict`, so saved states keep their + bytes, but it takes no part in equality and no step compares it: each step + fits with the live value, and the thread count changes no draw. """ predictors: tuple[str, ...] @@ -1737,7 +1744,7 @@ class QRFChainState: max_samples_leaf: int | float | None max_samples_leaf_kind: str seed: int - fit_n_jobs: int + fit_n_jobs: int = field(compare=False) donor_index: _IndexIdentity recipient_index: _IndexIdentity | None fit_rng_state_json: str @@ -2610,7 +2617,11 @@ def fit_draw_next( ) def _validate_chain_config(self, state: QRFChainState) -> None: - """Refuse any model configuration drift across subprocesses.""" + """Refuse drift in any setting that can change the draws. + + The fit thread count is not one of them, so a chain may continue under + another ``POPULACE_FIT_N_JOBS``. + """ if self.gate_level_columns: raise ValueError( "The checkpointed QRF chain does not carry gate_level_columns yet; " @@ -2622,7 +2633,6 @@ def _validate_chain_config(self, state: QRFChainState) -> None: self.max_samples_leaf, _max_samples_leaf_kind(self.max_samples_leaf), self.seed, - _fit_n_jobs(), self.gate_calibration, ) expected = ( @@ -2631,7 +2641,6 @@ def _validate_chain_config(self, state: QRFChainState) -> None: state.max_samples_leaf, state.max_samples_leaf_kind, state.seed, - state.fit_n_jobs, state.gate_calibration, ) if actual != expected or actual[3] != expected[3]: diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf.py index 285f10289a..bfe423b3b6 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf.py @@ -10,6 +10,7 @@ from __future__ import annotations import json +from dataclasses import replace import numpy as np import pandas as pd @@ -726,26 +727,54 @@ def test_targetwise_chain_refuses_config_prefix_order_and_index_drift( QRFChainState.from_dict(drifted_order) -def test_targetwise_chain_locks_resolved_fit_threading( +def test_targetwise_chain_continues_under_a_different_fit_width( correlated_targets_frame, monkeypatch, ) -> None: - """A subprocess cannot silently resume under a different fit width.""" + """Each step may use another width; draws and saved state do not change.""" monkeypatch.setenv("POPULACE_FIT_N_JOBS", "1") + monkeypatch.setenv("POPULACE_FIT_PREDICT_WORKERS", "1") frame, _ = correlated_targets_frame(seed=5, n=80) recipient = frame.table("person").iloc[:20].loc[:, ["x"]].copy() model = RegimeGatedQRF(n_estimators=3, seed=29) - state = model.start_chain(frame, ["x"], ["first", "second"]) - assert state.fit_n_jobs == 1 + initial_state = model.start_chain(frame, ["x"], ["first", "second"]) + assert initial_state.fit_n_jobs == 1 + + def run_chain(fit_jobs_per_step: tuple[str, str]): + state = initial_state + priors = pd.DataFrame(index=recipient.index) + draws = [] + for fit_jobs in fit_jobs_per_step: + monkeypatch.setenv("POPULACE_FIT_N_JOBS", fit_jobs) + step = model.fit_draw_next(frame, recipient, priors, state=state) + draws.append(step.raw_draw.tobytes()) + priors = priors.assign(**{step.target: step.raw_draw}) + state = step.state + return draws, state + + unchanged_draws, unchanged_state = run_chain(("1", "1")) + changed_draws, changed_state = run_chain(("2", "3")) + + assert changed_draws == unchanged_draws + assert changed_state.fit_n_jobs == 1 + assert changed_state.to_dict() == unchanged_state.to_dict() + + +def test_chain_state_equality_ignores_the_recorded_fit_width( + correlated_targets_frame, + monkeypatch, +) -> None: + """The width stays in the saved mapping but does not distinguish states.""" + monkeypatch.setenv("POPULACE_FIT_N_JOBS", "1") + frame, _ = correlated_targets_frame(seed=5, n=80) + state = RegimeGatedQRF(n_estimators=3, seed=29).start_chain( + frame, ["x"], ["first", "second"] + ) + other_width = replace(state, fit_n_jobs=2) - monkeypatch.setenv("POPULACE_FIT_N_JOBS", "2") - with pytest.raises(ValueError, match="model configuration changed"): - model.fit_draw_next( - frame, - recipient, - pd.DataFrame(index=recipient.index), - state=state, - ) + assert other_width == state + assert other_width.to_dict() != state.to_dict() + assert replace(state, seed=30) != state def test_fit_n_jobs_unset_preserves_historical_default(monkeypatch) -> None: diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py index 259bdb09ac..594a208b15 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py @@ -62,7 +62,8 @@ def _cpu_count_unlike_os(monkeypatch: pytest.MonkeyPatch) -> int: joblib_cpu_count = (os.cpu_count() or 1) + 3 def patched_cpu_count(only_physical_cores: bool = False) -> int: - return joblib_cpu_count + # A physical-core count that differs, so a caller asking for it shows. + return joblib_cpu_count + 100 if only_physical_cores else joblib_cpu_count monkeypatch.setattr(joblib, "cpu_count", patched_cpu_count) return joblib_cpu_count @@ -108,6 +109,20 @@ def test_malformed_loky_max_cpu_count_is_named_in_the_error( assert _predict_workers() == 2 +@pytest.mark.parametrize("loky_max_cpu_count", ["1", "2"]) +def test_unset_prediction_workers_follow_the_real_joblib_cpu_count( + loky_max_cpu_count: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Unpatched joblib honours ``LOKY_MAX_CPU_COUNT``, so the draw does too.""" + monkeypatch.delenv(PREDICT_WORKERS_ENV, raising=False) + monkeypatch.setenv("LOKY_MAX_CPU_COUNT", loky_max_cpu_count) + + width = _predict_workers() + + assert width == joblib.cpu_count() + assert 1 <= width <= int(loky_max_cpu_count) + + def test_fit_jobs_default_stays_minus_one_under_joblib_cpu_count( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index 27bfa4dd5c..a67131938a 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"0f04fbf25e743af4f09830c56dff10f497c9743dfc4def03193829da3115e00f","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"b7966fdb66ace4deb3074e651901b91d490f15ab09594e2bad9f1bdd1298c864","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"b7966fdb66ace4deb3074e651901b91d490f15ab09594e2bad9f1bdd1298c864"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"08c01581e921c997d591d86175287aa49420b40c3c09c43c7a2752b2c55eb94a"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"e1919c2c9c075115252f1ebd5756b49837e18a6716822e862d3a5c2c6bd9e84c"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"489d105402d1549aa48491cce22bb9a7cdce442b65ec0aa39516afabfbd032df","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"a36de9959de7591e7320ec37c5446e88d2bab11919a662ec3c6222bea424e957","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"a36de9959de7591e7320ec37c5446e88d2bab11919a662ec3c6222bea424e957"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"f60bdd2ba9e59eb577e918789ef447d8b9334a644c5127c9603ca304dbe500f9"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"70b6b0455b360897af8ab29848482793f2524aebffd5adec6361a8211d353aee"}},"seed":947} diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index b244dd7e10..332a769a69 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -929,11 +929,7 @@ def _run_staged_all( """ pipeline_steps = _pipeline_steps_for(args) - runtime = StageRuntime( - args.checkpoint_dir, - _pipeline_for(args), - run_config=_stage_run_config(args), - ) + runtime = _open_stage_runtime(args) completed_prefix = runtime.context.completed remaining = pipeline_steps[len(completed_prefix) :] if not remaining and completed_prefix == pipeline_steps: @@ -1067,6 +1063,26 @@ def _pooled_income_years(args: argparse.Namespace) -> tuple[int, ...]: return tuple(sorted(set(years))) +#: QRF thread counts the first run records and a resume does not compare: they +#: change no imputed value. The BLAS and OpenMP thread counts and +#: PYTHONHASHSEED in ``thread_environment`` stay compared. +_RESUME_IGNORED_RUN_CONFIG_PATHS = ( + ("thread_environment", "POPULACE_FIT_N_JOBS"), + ("thread_environment", "POPULACE_FIT_PREDICT_WORKERS"), +) + + +def _open_stage_runtime(args: argparse.Namespace) -> StageRuntime: + """Open the checkpoint directory, refusing a resume with changed settings.""" + + return StageRuntime( + args.checkpoint_dir, + _pipeline_for(args), + run_config=_stage_run_config(args), + resume_ignored_run_config_paths=_RESUME_IGNORED_RUN_CONFIG_PATHS, + ) + + def _stage_run_config(args: argparse.Namespace) -> dict[str, object]: """Return the canonical inputs and settings locked across stage resumes.""" @@ -2350,11 +2366,7 @@ def _run_outer_stage(args: argparse.Namespace) -> None: f"--location-rule {_location_rule(args)} pipeline " f"{list(pipeline_steps)}." ) - runtime = StageRuntime( - args.checkpoint_dir, - _pipeline_for(args), - run_config=_stage_run_config(args), - ) + runtime = _open_stage_runtime(args) if args.stage in runtime.context.completed: if args.stage == "source_construction" and args.asec_h5 is not None: _require_completed_source_receipt_matches_pins( From 3bd457620c18bcabad9a70b771548abc6493f6c6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:28:02 +0400 Subject: [PATCH 6/8] Address review round 3 of the QRF thread-count change Bring the operator documents, the runbook, the changelog and the docstrings in line with what is compared now: worker identity version 2, sidecars that may differ in their audit fields, and run-config values a resume skips. The runbook's staging plan is pinned to a commit that still uses os.cpu_count(), and the changelog's CPU-quota claim now names the cgroup files joblib reads. Add a test that changes the fit-job count between chain steps with real threads and checks each step fits with the live count. Co-Authored-By: Claude Opus 5.5 --- ...redict-workers-joblib-cpu-count.changed.md | 4 +-- docs/us-modal-stage-runbook.md | 7 ++-- docs/us-multispine-operator-ordering.md | 11 +++--- .../microcosm/build/outer_stage_runtime.py | 5 ++- .../build/us_runtime/worker_identity.py | 5 +++ .../engine_free/us/test_puf_qrf_chain.py | 7 +++- .../shared/test_qrf_worker_counts.py | 36 +++++++++++++++++-- tools/build_us_puf_support_base.py | 6 +++- tools/modal_us_stage_plan.py | 4 ++- 9 files changed, 68 insertions(+), 17 deletions(-) diff --git a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md index 76f31138af..bf94d79c91 100644 --- a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md +++ b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md @@ -1,5 +1,5 @@ -Size the QRF draw's thread pool from the CPUs the process may use, and stop treating QRF thread counts as something a pool load or a resume must match. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, and 1 when joblib has turned multiprocessing off, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container held to a CPU quota no longer starts one thread per host CPU. The variable still overrides the default. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. A `LOKY_MAX_CPU_COUNT` that is not an integer is refused by joblib; the draw's pool sizing and the worker binding report it by name. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. +Size the QRF draw's thread pool from the CPUs the process may use, and stop treating QRF thread counts as something a pool load or a resume must match. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, and 1 when joblib has turned multiprocessing off, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container whose quota appears in the cgroup files joblib reads (`cpu.max` or `cpu.cfs_quota_us`) no longer starts one thread per host CPU. The variable still overrides the default. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. A `LOKY_MAX_CPU_COUNT` that is not an integer is refused by joblib; the draw's pool sizing and the worker binding report it by name. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. The primary-QRF worker binding (`worker_identity.py`, now schema 2) records `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` in a new `audit_thread_controls` field next to the interpreter paths in `audit_aliases`, and no longer in its semantic identity. Loading a pool for release or scoring, resuming the primary-QRF checkpoint, the pool's checkpoint identity and the spec engine's worker resolution compare only the semantic identity, so a pool built with one pair of counts loads under another, whether the counts come from the machine or from the two variables. Building the binding still refuses a malformed count. An unset prediction-worker count is recorded as `resolution: "joblib_cpu_count_fallback"`; `"os_cpu_count_fallback"` still validates. Schema-1 bindings still validate, and a pool that holds one is refused because its worker identity changed. The semantic identity is now cached per lock only. The spec template for the worker binding (`imputation.yaml` and `imputation.schema.json`) names schema 2 and the new field. The frozen schema-4 shape that the scoring-only relocation of schema-9 pools compares with their sealed records keeps the counts where that code recorded them, an unset count as the host's `os.cpu_count()`, so that comparison is unchanged and still includes the counts. The unused older binding in `stacked_spine.py` records the joblib default under the new label. -A resume no longer compares `POPULACE_FIT_N_JOBS`. `QRF.fit_draw_next` accepts a chain state that recorded another count, and `QRFChainState` equality ignores the count; the state still records the value in force when the chain started, so saved states keep their bytes. The ACS transfer target bank checks a saved target's predecessor digest with the count that target saved, so it reuses the target where it used to rebuild it. The PUF support base builder records both QRF thread variables in its run configuration and no longer compares them on resume (`StageRuntime`'s new `resume_ignored_run_config_paths`); the BLAS and OpenMP thread counts and `PYTHONHASHSEED` stay compared. A base run or pool build interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. +A resume no longer compares `POPULACE_FIT_N_JOBS`. `QRF.fit_draw_next` accepts a chain state that recorded another count, and `QRFChainState` equality ignores the count; the state still records the value in force when the chain started, so saved states keep their bytes. The ACS transfer target bank checks a saved target's predecessor digest with the count that target saved, so it reuses the target where it used to rebuild it; a first target that is rebuilt starts its chain again and records the live count. The PUF support base builder records both QRF thread variables in its run configuration and no longer compares them on resume (`StageRuntime`'s new `resume_ignored_run_config_paths`); the BLAS and OpenMP thread counts and `PYTHONHASHSEED` stay compared. A base run or pool build interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index b8678645d2..83fa1b1656 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -1538,9 +1538,10 @@ archives. - *CPU.* `full-staging-a3` in `experiments/us-acs-local-hours-rebuild-20260922/run-resources-and-staging-excerpt.json` measured 103,104.6 CPU-s over 7,218.1 s of wall, 14.3 cores on average. - The QRF forest uses `n_jobs=-1` when `POPULACE_FIT_N_JOBS` is unset, and - prediction sizes its pool from `joblib.cpu_count()` when - `POPULACE_FIT_PREDICT_WORKERS` is unset (`microcosm.fit.qrf`). Sixteen + The QRF forest uses `n_jobs=-1` when `POPULACE_FIT_N_JOBS` is unset. With + `POPULACE_FIT_PREDICT_WORKERS` unset, prediction sizes its pool from + `os.cpu_count()` at this plan's pinned commit `74f5e6123`, and from + `joblib.cpu_count()` in later code (`microcosm.fit.qrf`). Sixteen cores accommodate the observed average with 1.7 cores of headroom; the limit throttles use above sixteen. Neither the average nor the request establishes the container's visible CPU count. The receipt records diff --git a/docs/us-multispine-operator-ordering.md b/docs/us-multispine-operator-ordering.md index 1c68de774f..85f13be74d 100644 --- a/docs/us-multispine-operator-ordering.md +++ b/docs/us-multispine-operator-ordering.md @@ -254,7 +254,7 @@ by_origin_battery contract 4, transition authority 2, and resource-semantics receipt 2. The primary execution config is version 6 (it binds the recipient-share bound, #1259), its portable worker identity is - version 1, and its checkpoint input sidecar is version 2. The companion pool + version 2, and its checkpoint input sidecar is version 2. The companion pool manifest uses schema version 10. Older outer authority or materializer payloads are stale; primary-QRF version 6 remains current. @@ -546,12 +546,13 @@ primary-QRF schema, manifest name, and exact target order; the physical checkpoint directory basename must independently equal that bound identity. The execution-config receipt resolves and hashes the actual predictor/output sequences, all 65 optional allocation/passthrough reads, clone fraction/seed, -QRF seed/estimator count, worker module/interpreter/argv and reviewed fit -environment, strict-recipient and null-preserving doctrines, the once-resolved +QRF seed/estimator count, worker module/interpreter/argv and environment +policy, strict-recipient and null-preserving doctrines, the once-resolved aggregate-disaggregation spec and SOI AGI-band bytes/semantics, every tail selection/topcode/five-times/concentration control, and enabled audit sinks. The same three receipts form an exact SHA-bound sidecar beside the primary-QRF -manifest; resume refuses a missing or different sidecar, including a +manifest; resume refuses a missing sidecar or one that differs in anything but +the worker's `audit_aliases` and `audit_thread_controls`, including a same-row-count donor with changed bytes. This closes stale-bank reuse under a newly claimed outer route. @@ -976,7 +977,7 @@ and valid. Neither receipt authorizes an upstream null. | PUF raw predictor sources | Every filing-status, count, and income component is observed in its declared source universe. Raw WAGP/SEMP authority is present and agrees with mapped leaves; a cross-grain source collision is rejected. A null on any eligible member fails before coercion. | Structure supplies status/count; ACS-native or ASEC-carried earnings supply earnings; early transfer supplies interest, dividends, and gains. | No. ACS under-15 WAGP/SEMP blanks are an exact source-universe state, not transfer starvation; all other source nulls fail. | | PUF tax-unit features | Every clone-1 recipient has a finite feature vector. Post-aggregation NaN, `+inf`, and `-inf` are counted by named predictor and rejected before fitting; none is coerced or snapped to zero. | Universe-aware person sums plus tax-unit structural inputs. | No. Eligible member values must be complete; the only special case is an all-child unit whose numeric-zero predictor is explicitly owned and counted by the named universe-zero rule. | | Primary QRF banks and chain | Donor/recipient banks are immutable; target order and RNG prefix are contiguous; all targets complete; live recipient identity, source-universe receipt, and feature digest match before finalization. | The processed full PUF donor and strict recipient checkpoint initialized above. | No. Mutation or missing receipt invalidates the bank; it cannot resume under legacy semantics. | -| Outer pool checkpoint identity and resume | Primary-QRF schema v6, primary execution config v5, portable worker identity v1, tail-manifest schema v2, late-registry schema v17/receipt contract v4, outer stacked materializer v13/authority v12, stacked pool-stage materializer v7, pool manifest schema v10, and the ACS-universe, QBI-mutation, tail-support, late-DAG, and signed virtual-resource-semantics identities must match exactly before any cached stage is discovered. The retiring legacy envelope remains manifest schema v4/materializer v3. | Fresh input pins, live stack receipt, scale controls, code identity, and all semantic contract identities. | No. An older stacked materializer or authority payload is stale; a self-consistent old receipt cannot reopen a checkpoint. Primary-QRF v6 remains current. | +| Outer pool checkpoint identity and resume | Primary-QRF schema v6, primary execution config v5, portable worker identity v2, tail-manifest schema v2, late-registry schema v17/receipt contract v4, outer stacked materializer v13/authority v12, stacked pool-stage materializer v7, pool manifest schema v10, and the ACS-universe, QBI-mutation, tail-support, late-DAG, and signed virtual-resource-semantics identities must match exactly before any cached stage is discovered. The retiring legacy envelope remains manifest schema v4/materializer v3. | Fresh input pins, live stack receipt, scale controls, code identity, and all semantic contract identities. | No. An older stacked materializer or authority payload is stale; a self-consistent old receipt cannot reopen a checkpoint. Primary-QRF v6 remains current. | | Clone-2 capital-gains tail | Each filing status requires as many eligible recipient households as selected q99.5 donors. Eligibility requires unique single-tax-unit PUF-detail lineage and half-weight capacity for the global maximum assigned donor weight. An adequate status assigns every selected donor once; a thin status skips as a whole with a named, counted `insufficient_support` receipt. | Completed clone-1 QRF output and full PUF tail donors. At 1%, `SINGLE` and `HEAD_OF_HOUSEHOLD` attach, `JOINT` and `SEPARATE` skip, and zero-requirement `SURVIVING_SPOUSE` is `not_applicable`. | No widening or partial attachment is permitted. All 22 AGI bands provide nearest-first fallback only inside a status. Universe-aware PUF recipients remain eligible, including explicitly receipted empty-universe tax units. | | Late producer DAG | Before any callback, all declared inputs are filled on their required scopes or carry an input-specific counted absence receipt; numeric inputs are finite. The exact derived order, readiness rows, once-only source finalizer, and bounded transfer receipts must validate. | ACS earnings-universe materialization, primary PUF/tail, 16 source producers, and 19 bounded transfer groups execute in six derived waves. | No. The refusing producer names the unfilled input and its declared producing stage. A cycle fails at import with its path. | | Late transfer completion | Every declared PUF-clone or ASEC source-producer cell is nonnull; all complementary recipients are filled; the allowed count for both unmodeled and residual rows is zero. | Forty-five PUF and 29 source targets, with two overlaps, supply the 72-target late surface. | No. A missing producer or recipient value is terminal at this boundary. | diff --git a/packages/microcosm-build/src/microcosm/build/outer_stage_runtime.py b/packages/microcosm-build/src/microcosm/build/outer_stage_runtime.py index e0e70006ab..207b15ea28 100644 --- a/packages/microcosm-build/src/microcosm/build/outer_stage_runtime.py +++ b/packages/microcosm-build/src/microcosm/build/outer_stage_runtime.py @@ -276,7 +276,10 @@ def metadata(self) -> dict[str, dict[str, object]]: return self.context.metadata def require_run_config(self, expected: Mapping[str, object]) -> dict[str, object]: - """Require the resume arguments to equal the locked first-run config.""" + """Require the resume arguments to equal the first-run config. + + Values named by ``resume_ignored_run_config_paths`` are not compared. + """ context = self._load_context() if self._resume_compared_run_config( 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 d8ead25b93..db78d26241 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 @@ -1359,6 +1359,11 @@ def _schema_4_thread_controls() -> dict[str, object]: def _semantic_environment() -> dict[str, object]: + """Return the environment policy, which names variables but holds no counts. + + ``bound_names`` lists the thread-count variables among those the worker + binding covers; their values are in ``audit_thread_controls``. + """ return { "policy": ( "inherit_parent_environment_with_bound_fit_controls_and_forced_overrides" diff --git a/packages/microcosm-build/tests/engine_free/us/test_puf_qrf_chain.py b/packages/microcosm-build/tests/engine_free/us/test_puf_qrf_chain.py index e03d2f117c..89b7b8b155 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_puf_qrf_chain.py +++ b/packages/microcosm-build/tests/engine_free/us/test_puf_qrf_chain.py @@ -511,7 +511,12 @@ def test_primary_qrf_chain_resumes_under_changed_thread_counts( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Rebuilt targets are the same bytes under other thread counts.""" + """A resume under other counts is accepted and rewrites the same files. + + The fixture is too small for the counts to change the draw's chunks; the + byte-identity tests with real thread pools are in ``microcosm-fit``'s + ``test_qrf_worker_counts.py``. + """ monkeypatch.setenv("POPULACE_FIT_N_JOBS", "1") monkeypatch.setenv("POPULACE_FIT_PREDICT_WORKERS", "1") checkpoint_dir = tmp_path / "primary_qrf" diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py index 594a208b15..29d88b0bb4 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py @@ -314,9 +314,8 @@ def test_chained_fit_draw_next_is_byte_identical_across_thread_counts( ) -> None: """Target-at-a-time chain steps draw the same bytes at any thread count. - Each run starts its own chain, because a chain state refuses a resume - under a different fit job count. The second target conditions on the - first target's raw draws, so a difference in the first would carry on. + The second target conditions on the first target's raw draws, so a + difference in the first would carry on. """ frame = make_person_frame(_donor_columns(seed=13), _donor_weights(seed=13)) recipients = _recipients(seed=13) @@ -341,6 +340,37 @@ def run() -> tuple[dict[str, np.ndarray], list[int]]: _assert_byte_identical(serial, _run_under(monkeypatch, setting, run)) +def test_chain_changing_fit_jobs_between_steps_draws_the_same_bytes( + make_person_frame, monkeypatch: pytest.MonkeyPatch +) -> None: + """Each step fits with the live count; draws and saved state do not move.""" + frame = make_person_frame(_donor_columns(seed=13), _donor_weights(seed=13)) + recipients = _recipients(seed=13) + targets = ["signed", "follower"] + monkeypatch.setenv(PREDICT_WORKERS_ENV, "1") + + def run_chain(fit_jobs_per_target: tuple[str, str]): + monkeypatch.setenv(FIT_JOBS_ENV, fit_jobs_per_target[0]) + model = RegimeGatedQRF(n_estimators=N_ESTIMATORS, seed=41) + state = model.start_chain(frame, ["x", "z"], targets) + raw_priors = pd.DataFrame(index=recipients.index) + draws: dict[str, np.ndarray] = {} + for fit_jobs in fit_jobs_per_target: + monkeypatch.setenv(FIT_JOBS_ENV, fit_jobs) + step = model.fit_draw_next(frame, recipients, raw_priors, state=state) + assert set(_forest_fit_jobs(step.fitted._target_models)) == {int(fit_jobs)} + draws[step.target] = np.array(step.raw_draw) + raw_priors[step.target] = step.raw_draw + state = step.state + return draws, state + + unchanged_draws, unchanged_state = run_chain(("1", "1")) + changed_draws, changed_state = run_chain(("1", str(SEVERAL))) + + _assert_byte_identical(unchanged_draws, changed_draws) + assert changed_state.to_dict() == unchanged_state.to_dict() + + def test_unset_prediction_workers_size_the_draw_pool_from_joblib( make_person_frame, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tools/build_us_puf_support_base.py b/tools/build_us_puf_support_base.py index 48296bb701..19eea90a22 100644 --- a/tools/build_us_puf_support_base.py +++ b/tools/build_us_puf_support_base.py @@ -1281,7 +1281,11 @@ def _open_stage_runtime(args: argparse.Namespace) -> StageRuntime: def _stage_run_config(args: argparse.Namespace) -> dict[str, object]: - """Return the canonical inputs and settings locked across stage resumes.""" + """Return the canonical inputs and settings recorded by the first run. + + A resume must supply equal values, except for + ``_RESUME_IGNORED_RUN_CONFIG_PATHS``. + """ def path(value: Path | None) -> str | None: return None if value is None else str(value.resolve()) diff --git a/tools/modal_us_stage_plan.py b/tools/modal_us_stage_plan.py index 82ce9328d2..f7c97c0f32 100644 --- a/tools/modal_us_stage_plan.py +++ b/tools/modal_us_stage_plan.py @@ -859,7 +859,9 @@ def _runner_smoke_argv( # from the completed prefix (_run_staged_all), with its whole run config # (input paths and digests, settings, code identity, thread variables) # locked in stage_run_context.json; a resume whose config differs is -# refused. Every path the tool records is the same in every attempt of a +# refused (the tool now records the two POPULACE_FIT_* thread variables +# without comparing them). Every path the tool records is the same in +# every attempt of a # run (/work/inputs/..., /work/state/...), and so are the image, the plan's # environment and the class, so a later attempt of the same run_id should # resume where the last one stopped. The placement is non-preemptible, so From 263c21cf23d8359519d12309cac83273716964e4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:15:37 +0400 Subject: [PATCH 7/8] Address review round 4 of the QRF thread-count change Add a test that writes a stacked pool under one pair of QRF thread counts and opens it through the ready, release and scoring loaders under another. It fails when the worker comparison also requires equal counts. Correct what the documents claim: why an older base run cannot resume, which thread variables a resume compares at which commit, the execution config and legacy materializer versions, and that only the thread counts stopped mattering, not the rest of the worker identity. Co-Authored-By: Claude Opus 5.5 --- ...redict-workers-joblib-cpu-count.changed.md | 4 +- docs/evidence/spec-engine/us-f0-coverage.json | 16 +++---- docs/us-modal-stage-runbook.md | 9 ++-- docs/us-multispine-operator-ordering.md | 4 +- .../build/spec_engine/inventory_coverage.py | 4 +- .../build/us_runtime/worker_identity.py | 6 +-- .../shared/test_spec_engine_loader.py | 2 +- .../us/test_us_multispine_pool_h5_io.py | 45 +++++++++++++++++++ .../us/test_us_qrf_worker_thread_controls.py | 18 ++++---- .../us/test_us_multispine_pool_tool.py | 2 +- .../microcosm-fit/src/microcosm/fit/qrf.py | 3 +- .../fixtures/parity/kernels/fit.qrf/pins.json | 2 +- tools/modal_us_stage_plan.py | 7 +-- 13 files changed, 87 insertions(+), 35 deletions(-) diff --git a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md index bf94d79c91..a766cf8574 100644 --- a/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md +++ b/changelog.d/qrf-predict-workers-joblib-cpu-count.changed.md @@ -1,5 +1,5 @@ Size the QRF draw's thread pool from the CPUs the process may use, and stop treating QRF thread counts as something a pool load or a resume must match. With `POPULACE_FIT_PREDICT_WORKERS` unset, the pool now has `joblib.cpu_count()` threads (`microcosm.fit.qrf.default_predict_workers`), the smallest of the machine's CPU count, the process's CPU affinity mask, a Linux cgroup CPU quota and `LOKY_MAX_CPU_COUNT`, and 1 when joblib has turned multiprocessing off, instead of `os.cpu_count()`, which counts only the machine's CPUs: a container whose quota appears in the cgroup files joblib reads (`cpu.max` or `cpu.cfs_quota_us`) no longer starts one thread per host CPU. The variable still overrides the default. Fit jobs keep `n_jobs=-1`, which joblib already resolves to `joblib.cpu_count()` threads, so chain states and run configurations record what they did before. A `LOKY_MAX_CPU_COUNT` that is not an integer is refused by joblib; the draw's pool sizing and the worker binding report it by name. Draws are unchanged: new tests require byte-identical draws for one and four prediction workers and for one and four fit jobs, for a single-forest target, a target with zero, positive and negative values, and a target-at-a-time chain. -The primary-QRF worker binding (`worker_identity.py`, now schema 2) records `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` in a new `audit_thread_controls` field next to the interpreter paths in `audit_aliases`, and no longer in its semantic identity. Loading a pool for release or scoring, resuming the primary-QRF checkpoint, the pool's checkpoint identity and the spec engine's worker resolution compare only the semantic identity, so a pool built with one pair of counts loads under another, whether the counts come from the machine or from the two variables. Building the binding still refuses a malformed count. An unset prediction-worker count is recorded as `resolution: "joblib_cpu_count_fallback"`; `"os_cpu_count_fallback"` still validates. Schema-1 bindings still validate, and a pool that holds one is refused because its worker identity changed. The semantic identity is now cached per lock only. The spec template for the worker binding (`imputation.yaml` and `imputation.schema.json`) names schema 2 and the new field. The frozen schema-4 shape that the scoring-only relocation of schema-9 pools compares with their sealed records keeps the counts where that code recorded them, an unset count as the host's `os.cpu_count()`, so that comparison is unchanged and still includes the counts. The unused older binding in `stacked_spine.py` records the joblib default under the new label. +The primary-QRF worker binding (`worker_identity.py`, now schema 2) records `POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` in a new `audit_thread_controls` field next to the interpreter paths in `audit_aliases`, and no longer in its semantic identity. Loading a pool for release or scoring, resuming the primary-QRF checkpoint, the pool's checkpoint identity and the spec engine's worker resolution compare only the semantic identity, so a difference in either count, whether it comes from the machine or from the two variables, no longer stops a pool from loading. The rest of the semantic identity, such as the interpreter and the installed distributions, must still match. Building the binding still refuses a malformed count. An unset prediction-worker count is recorded as `resolution: "joblib_cpu_count_fallback"`; `"os_cpu_count_fallback"` still validates. Schema-1 bindings still validate, and a pool that holds one is refused because its worker identity changed. The semantic identity is now cached per lock only. The spec template for the worker binding (`imputation.yaml` and `imputation.schema.json`) names schema 2 and the new field. The frozen schema-4 shape that the scoring-only relocation of schema-9 pools compares with their sealed records keeps the counts where that code recorded them, an unset count as the host's `os.cpu_count()`, so that comparison is unchanged and still includes the counts. The unused older binding in `stacked_spine.py` records the joblib default under the new label. -A resume no longer compares `POPULACE_FIT_N_JOBS`. `QRF.fit_draw_next` accepts a chain state that recorded another count, and `QRFChainState` equality ignores the count; the state still records the value in force when the chain started, so saved states keep their bytes. The ACS transfer target bank checks a saved target's predecessor digest with the count that target saved, so it reuses the target where it used to rebuild it; a first target that is rebuilt starts its chain again and records the live count. The PUF support base builder records both QRF thread variables in its run configuration and no longer compares them on resume (`StageRuntime`'s new `resume_ignored_run_config_paths`); the BLAS and OpenMP thread counts and `PYTHONHASHSEED` stay compared. A base run or pool build interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`. +A resume no longer compares `POPULACE_FIT_N_JOBS`. `QRF.fit_draw_next` accepts a chain state that recorded another count, and `QRFChainState` equality ignores the count; the state still records the value in force when the chain started, so saved states keep their bytes. The ACS transfer target bank checks a saved target's predecessor digest with the count that target saved, so it reuses the target where it used to rebuild it; a first target that is rebuilt starts its chain again and records the live count. The PUF support base builder records both QRF thread variables in its run configuration and no longer compares them on resume (`StageRuntime`'s new `resume_ignored_run_config_paths`); the BLAS and OpenMP thread counts and `PYTHONHASHSEED` stay compared. A pool build interrupted before this change cannot resume after it, because its recorded worker identity hashes the edited `qrf.py`, `worker_identity.py` and `stacked_spine.py`; a base run cannot either, because its run configuration records a digest of the builder and the packaged source. A compatibility attestation written for the scoring-only relocation of a sealed pool before this change no longer validates, so that relocation needs a new one. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index a59d9a2090..6f16405d4c 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": "4d2f90795e43ba1ca1170b08c90d75d40d8bf1ee101210d7eba0771a5817fc1b", - "protocol_sha256": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a" + "map_sha256": "867b2ecfc84279744eced0ba7d70bbc55da99b30dcc39a4ea5f40f5198ff1132", + "protocol_sha256": "f5ca111b8e17024e542cf959a65fd616328a1e28b81570acbe137ce632f351c1" }, "failures": [], "observed": { - "map_sha256": "4d2f90795e43ba1ca1170b08c90d75d40d8bf1ee101210d7eba0771a5817fc1b", - "protocol_sha256": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a" + "map_sha256": "867b2ecfc84279744eced0ba7d70bbc55da99b30dcc39a4ea5f40f5198ff1132", + "protocol_sha256": "f5ca111b8e17024e542cf959a65fd616328a1e28b81570acbe137ce632f351c1" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a", + "implementation_sha256": "f5ca111b8e17024e542cf959a65fd616328a1e28b81570acbe137ce632f351c1", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a", + "implementation_sha256": "f5ca111b8e17024e542cf959a65fd616328a1e28b81570acbe137ce632f351c1", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "e087d0cc9e10df986d191814d3e8736b71a252390e6c88466346bc297ab785d4" + "spec_sha256": "949a51fca973a095b2d0752c147f02704f06d205343cbdfce964389a66c7ba20" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "e087d0cc9e10df986d191814d3e8736b71a252390e6c88466346bc297ab785d4" + "spec_sha256": "949a51fca973a095b2d0752c147f02704f06d205343cbdfce964389a66c7ba20" }, "status": "pass" } diff --git a/docs/us-modal-stage-runbook.md b/docs/us-modal-stage-runbook.md index 83fa1b1656..93f273c18c 100644 --- a/docs/us-modal-stage-runbook.md +++ b/docs/us-modal-stage-runbook.md @@ -1160,11 +1160,14 @@ without checkpoints would lose the whole run. With them, `--stage all` resumes from the last completed outer stage (`_run_staged_all`). The tool locks its whole run config in `stage_run_context.json` (input paths and digests, settings, its code identity and the thread variables it sees) and -refuses a resume whose config differs. Every path in it is the same in +refuses a resume whose config differs. Code newer than the pinned +`4b57d15a2` that contains the QRF thread-count change records +`POPULACE_FIT_N_JOBS` and `POPULACE_FIT_PREDICT_WORKERS` without comparing +them. Every path in the config is the same in every attempt of the run, and so are the image, the plan's environment and the class, so a relaunch of the same plan should resume. If Modal gave the -new container different thread variables, the tool would refuse, and the -run would need a new `run_id`. The cost has three parts: +new container different compared thread variables, the tool would refuse, +and the run would need a new `run_id`. The cost has three parts: - one copy of about 46 GB when the tool stops, hashed as it is copied; - the same pulled back by a resuming attempt, hashed and verified in that diff --git a/docs/us-multispine-operator-ordering.md b/docs/us-multispine-operator-ordering.md index 85f13be74d..04a07cbbb5 100644 --- a/docs/us-multispine-operator-ordering.md +++ b/docs/us-multispine-operator-ordering.md @@ -955,7 +955,7 @@ the full payload SHA-256 is Reversing registry iteration produces those same bytes. The virtual-resource payload ledger is independently versioned: ACS-universe -config v2, primary execution config v5, source execution config v3, source +config v2, primary execution config v6, source execution config v3, source finalizer config v2, and transfer model config v3. Donor content, primary-checkpoint routing, source callback receipts, and transfer-bank routing remain v1. The outer all-producer resource-semantics receipt is v2 and binds @@ -977,7 +977,7 @@ and valid. Neither receipt authorizes an upstream null. | PUF raw predictor sources | Every filing-status, count, and income component is observed in its declared source universe. Raw WAGP/SEMP authority is present and agrees with mapped leaves; a cross-grain source collision is rejected. A null on any eligible member fails before coercion. | Structure supplies status/count; ACS-native or ASEC-carried earnings supply earnings; early transfer supplies interest, dividends, and gains. | No. ACS under-15 WAGP/SEMP blanks are an exact source-universe state, not transfer starvation; all other source nulls fail. | | PUF tax-unit features | Every clone-1 recipient has a finite feature vector. Post-aggregation NaN, `+inf`, and `-inf` are counted by named predictor and rejected before fitting; none is coerced or snapped to zero. | Universe-aware person sums plus tax-unit structural inputs. | No. Eligible member values must be complete; the only special case is an all-child unit whose numeric-zero predictor is explicitly owned and counted by the named universe-zero rule. | | Primary QRF banks and chain | Donor/recipient banks are immutable; target order and RNG prefix are contiguous; all targets complete; live recipient identity, source-universe receipt, and feature digest match before finalization. | The processed full PUF donor and strict recipient checkpoint initialized above. | No. Mutation or missing receipt invalidates the bank; it cannot resume under legacy semantics. | -| Outer pool checkpoint identity and resume | Primary-QRF schema v6, primary execution config v5, portable worker identity v2, tail-manifest schema v2, late-registry schema v17/receipt contract v4, outer stacked materializer v13/authority v12, stacked pool-stage materializer v7, pool manifest schema v10, and the ACS-universe, QBI-mutation, tail-support, late-DAG, and signed virtual-resource-semantics identities must match exactly before any cached stage is discovered. The retiring legacy envelope remains manifest schema v4/materializer v3. | Fresh input pins, live stack receipt, scale controls, code identity, and all semantic contract identities. | No. An older stacked materializer or authority payload is stale; a self-consistent old receipt cannot reopen a checkpoint. Primary-QRF v6 remains current. | +| Outer pool checkpoint identity and resume | Primary-QRF schema v6, primary execution config v6, portable worker identity v2, tail-manifest schema v2, late-registry schema v17/receipt contract v4, outer stacked materializer v13/authority v12, stacked pool-stage materializer v7, pool manifest schema v10, and the ACS-universe, QBI-mutation, tail-support, late-DAG, and signed virtual-resource-semantics identities must match exactly before any cached stage is discovered. The retiring legacy envelope remains manifest schema v4/materializer v4. | Fresh input pins, live stack receipt, scale controls, code identity, and all semantic contract identities. | No. An older stacked materializer or authority payload is stale; a self-consistent old receipt cannot reopen a checkpoint. Primary-QRF v6 remains current. | | Clone-2 capital-gains tail | Each filing status requires as many eligible recipient households as selected q99.5 donors. Eligibility requires unique single-tax-unit PUF-detail lineage and half-weight capacity for the global maximum assigned donor weight. An adequate status assigns every selected donor once; a thin status skips as a whole with a named, counted `insufficient_support` receipt. | Completed clone-1 QRF output and full PUF tail donors. At 1%, `SINGLE` and `HEAD_OF_HOUSEHOLD` attach, `JOINT` and `SEPARATE` skip, and zero-requirement `SURVIVING_SPOUSE` is `not_applicable`. | No widening or partial attachment is permitted. All 22 AGI bands provide nearest-first fallback only inside a status. Universe-aware PUF recipients remain eligible, including explicitly receipted empty-universe tax units. | | Late producer DAG | Before any callback, all declared inputs are filled on their required scopes or carry an input-specific counted absence receipt; numeric inputs are finite. The exact derived order, readiness rows, once-only source finalizer, and bounded transfer receipts must validate. | ACS earnings-universe materialization, primary PUF/tail, 16 source producers, and 19 bounded transfer groups execute in six derived waves. | No. The refusing producer names the unfilled input and its declared producing stage. A cycle fails at import with its path. | | Late transfer completion | Every declared PUF-clone or ASEC source-producer cell is nonnull; all complementary recipients are filled; the allowed count for both unmodeled and residual rows is zero. | Forty-five PUF and 29 source targets, with two overlaps, supply the 72-target late surface. | No. A missing producer or recipient value is terminal at this boundary. | 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 8d5ac2802c..f7a5f9b0c3 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 @@ -404,8 +404,8 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The QRF draw's default thread count, joblib.cpu_count() in place of # os.cpu_count() in microcosm.fit.qrf, moves both again; no draw changes. - "seed_map": "4d2f90795e43ba1ca1170b08c90d75d40d8bf1ee101210d7eba0771a5817fc1b", - "seed_protocol": "7324b71fd3a8349e51cf9ad6de5076288bccef678bd1fd39bdfa5ddf6f10197a", + "seed_map": "867b2ecfc84279744eced0ba7d70bbc55da99b30dcc39a4ea5f40f5198ff1132", + "seed_protocol": "f5ca111b8e17024e542cf959a65fd616328a1e28b81570acbe137ce632f351c1", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", 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 db78d26241..132772297e 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 @@ -28,9 +28,9 @@ #: ``audit_thread_controls``, outside the semantic identity that recorded-versus- #: live comparisons read. The counts change no imputed value (``microcosm-fit``'s #: ``test_qrf_worker_counts.py``), and an unset prediction-worker count follows -#: the machine, so a pool built on one host stays comparable on another. The one -#: exception is the frozen schema-4 record that the scoring-only relocation of a -#: sealed pool compares field by field, counts included. +#: the machine, so a different CPU count no longer makes a pool's worker differ. +#: The one exception is the frozen schema-4 record that the scoring-only +#: relocation of a sealed pool compares field by field, counts included. PRIMARY_QRF_WORKER_IDENTITY_SCHEMA_VERSION = 2 #: Schema 1 kept the counts in ``semantic_identity.environment.semantic_controls``. #: Those records still validate; they never equal a schema-2 identity. 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 3441fcf197..54bf0f354b 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 @@ -35,7 +35,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # The QRF draw's default thread count, joblib.cpu_count() in # microcosm.fit.qrf, moves the fit kernels' bytes again. assert first.spec_sha256 == ( - "9ea8f2db1ea7d522f2bd292d5ffcbdaaa4cb94d0770bd3eeca88c3c924fd82fd" + "d0234106b134856bd903fc8f518d7ec2c2e87c67ffc10d4071d041834818df90" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py index ed2abbc8fd..45c80b44ae 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_multispine_pool_h5_io.py @@ -1887,6 +1887,51 @@ def test_ready_stacked_pool_loader_binds_terminal_gate_aliases( ) +def _load_pool_for_release(manifest_path: Path): + return load_authenticated_us_multispine_pool_for_release( + manifest_path, + allow_terminal_gate_failure=False, + ) + + +@pytest.mark.parametrize( + "load_pool", + ( + pytest.param(load_simulation_ready_us_multispine_pool, id="ready"), + pytest.param(_load_pool_for_release, id="release"), + pytest.param(load_authenticated_us_multispine_pool_for_scoring, id="scoring"), + ), +) +def test_stacked_pool_loads_under_other_qrf_thread_counts( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + load_pool: Callable[[Path], tuple[Frame, dict[str, object], object]], +) -> None: + pytest.importorskip("tables") + monkeypatch.setenv("POPULACE_FIT_N_JOBS", "2") + monkeypatch.setenv("POPULACE_FIT_PREDICT_WORKERS", "3") + manifest_path = _write_ready_pool(tmp_path, stacked=True) + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + primary_producer = next( + row + for row in manifest["stage_receipts"]["impute"]["stacked_late_producer_dag"][ + "execution" + ] + if row["producer"] == stacked_spine_module.US_LATE_PRIMARY_PUF_STAGE + ) + recorded_controls = primary_producer["available_input_receipts"][ + "tax_unit.@primary_puf_execution_config" + ]["binding"]["qrf"]["worker_execution"]["audit_thread_controls"] + assert recorded_controls["POPULACE_FIT_N_JOBS"]["resolved"] == 2 + assert recorded_controls["POPULACE_FIT_PREDICT_WORKERS"]["resolved"] == 3 + + monkeypatch.setenv("POPULACE_FIT_N_JOBS", "5") + monkeypatch.setenv("POPULACE_FIT_PREDICT_WORKERS", "9") + frame, _loaded_manifest, _authenticated_h5 = load_pool(manifest_path) + + assert frame.n("household") == 3 + + def test_ready_stacked_pool_loader_restores_sampled_rung_manifest( tmp_path: Path, ) -> None: diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py index 15626f74af..05368107a6 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_qrf_worker_thread_controls.py @@ -9,9 +9,11 @@ and out of the semantic identity. Everything that compares a recorded worker with the live one reads only the semantic identity: loading a pool for release or scoring, resuming the primary-QRF checkpoint, the pool's -checkpoint identity, and the spec engine's worker resolution. A pool built on -an 18-CPU host therefore loads under the release tool's 16-CPU cap, and a -checkpoint started under one pair of counts resumes under another. +checkpoint identity, and the spec engine's worker resolution. A worker recorded +with 18 prediction threads therefore matches one under the release tool's +16-CPU cap, and a checkpoint started under one pair of counts resumes under +another. The rest of the identity, such as the interpreter and the installed +distributions, must still match. Schema-1 bindings, which kept the counts in ``semantic_identity.environment.semantic_controls``, still validate, so a pool @@ -195,7 +197,7 @@ def test_thread_controls_leave_the_compared_worker_identity_unchanged( pytest.param(OVERRIDDEN, id="release-overrides-both-counts"), ), ) -def test_pool_recorded_on_another_host_loads_with_the_live_worker( +def test_worker_recorded_under_other_thread_counts_matches_the_live_worker( monkeypatch: pytest.MonkeyPatch, release_setting: tuple[str | None, str | None, int], ) -> None: @@ -211,7 +213,7 @@ def test_pool_recorded_on_another_host_loads_with_the_live_worker( ) _validate_primary_config_against_live_worker( - recorded, boundary="pool load on another host" + recorded, boundary="pool load under other thread counts" ) @@ -261,7 +263,7 @@ def test_primary_qrf_checkpoint_resumes_under_other_thread_controls( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: - """A checkpoint started on one host resumes on another, sidecar untouched. + """A checkpoint resumes under other thread counts, its sidecar untouched. The chain itself is stubbed, as in the relocated-resume test in ``test_us_stacked_spine.py``; this exercises the sidecar comparison. @@ -357,7 +359,7 @@ def test_unset_prediction_workers_record_the_real_joblib_cpu_count( } -def test_pool_recorded_under_a_larger_loky_cap_loads_under_a_smaller_one( +def test_worker_recorded_under_a_larger_loky_cap_matches_under_a_smaller_one( monkeypatch: pytest.MonkeyPatch, ) -> None: """The release tool's ``LOKY_MAX_CPU_COUNT`` cap, with joblib unpatched.""" @@ -493,7 +495,7 @@ def test_schema_1_worker_records_still_validate( ) -def test_pool_recorded_with_a_schema_1_worker_is_refused_as_changed( +def test_recorded_schema_1_worker_is_refused_as_changed( monkeypatch: pytest.MonkeyPatch, ) -> None: _apply_thread_setting(monkeypatch, BASE_HOST) 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 959a1a68b1..32789d29ef 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 @@ -366,7 +366,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1585's us/gates.json row in country_package.json moves it. # The QRF draw's default thread count, joblib.cpu_count() in # microcosm.fit.qrf, moves it again. - "spec_sha256": "e087d0cc9e10df986d191814d3e8736b71a252390e6c88466346bc297ab785d4", + "spec_sha256": "949a51fca973a095b2d0752c147f02704f06d205343cbdfce964389a66c7ba20", }, } diff --git a/packages/microcosm-fit/src/microcosm/fit/qrf.py b/packages/microcosm-fit/src/microcosm/fit/qrf.py index 47db3319f9..be579a9473 100644 --- a/packages/microcosm-fit/src/microcosm/fit/qrf.py +++ b/packages/microcosm-fit/src/microcosm/fit/qrf.py @@ -1460,7 +1460,8 @@ def _predict_workers() -> int: overrides it with a positive integer. Raises: - ValueError: If the override is set but not a positive integer. + ValueError: If the override is set but not a positive integer, or + :func:`default_predict_workers` fails with the override unset. """ override = os.environ.get(_PREDICT_WORKERS_ENV) if override is None or not override.strip(): diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json index a67131938a..0341456afe 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/fit.qrf/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"489d105402d1549aa48491cce22bb9a7cdce442b65ec0aa39516afabfbd032df","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"a36de9959de7591e7320ec37c5446e88d2bab11919a662ec3c6222bea424e957","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"a36de9959de7591e7320ec37c5446e88d2bab11919a662ec3c6222bea424e957"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"f60bdd2ba9e59eb577e918789ef447d8b9334a644c5127c9603ca304dbe500f9"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"70b6b0455b360897af8ab29848482793f2524aebffd5adec6361a8211d353aee"}},"seed":947} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","quantile-forest":"1.4.2","scikit-learn":"1.8.0"},"implementation_hash":"6c0d9ecf35de0fbd9735e0a7f9402364b960f608d44ce9d84418b0abe45d2e8c","kernel":"fit.qrf@1","node":"fit_qrf","node_key":"ff60c64439c51b8f510203af5aa3b691361a8fb1e3c7b18f56d0a7f1333d607c","numeric":"platform_bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"ff60c64439c51b8f510203af5aa3b691361a8fb1e3c7b18f56d0a7f1333d607c"},"x86_64/linux/py3.13":{"direct":"platforms/x86_64-linux-py3_13/direct.csv","node_key":"420bc924771a24fd9de6adef6ed2131c93c7a8405cacbf47d2ef9745aeb25a8d"},"x86_64/linux/py3.14":{"direct":"platforms/x86_64-linux-py3_14/direct.csv","node_key":"953079e85861eedc8ddc063c57fdffe03e3eaa66086c06e1c119104b767fefce"}},"seed":947} diff --git a/tools/modal_us_stage_plan.py b/tools/modal_us_stage_plan.py index f7c97c0f32..3385708954 100644 --- a/tools/modal_us_stage_plan.py +++ b/tools/modal_us_stage_plan.py @@ -859,9 +859,10 @@ def _runner_smoke_argv( # from the completed prefix (_run_staged_all), with its whole run config # (input paths and digests, settings, code identity, thread variables) # locked in stage_run_context.json; a resume whose config differs is -# refused (the tool now records the two POPULACE_FIT_* thread variables -# without comparing them). Every path the tool records is the same in -# every attempt of a +# refused. At 4b57d15a2 that covers every thread variable; code containing +# the later QRF thread-count change records the two POPULACE_FIT_* variables +# without comparing them. Every path the tool records is the same in every +# attempt of a # run (/work/inputs/..., /work/state/...), and so are the image, the plan's # environment and the class, so a later attempt of the same run_id should # resume where the last one stopped. The placement is non-preemptible, so From 827be5ae6e732f33dc69c14a86835e77b3cd3e7c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:36:47 +0400 Subject: [PATCH 8/8] Test byte-identical QRF draws for forests with a leaf-size cap A leaf-size cap (max_samples_leaf) makes the fit keep a seeded subsample of each larger leaf, taken with Python's global random: for each tree, one random.seed with the tree's seed, then one random.shuffle per leaf. None of the existing byte-identity tests used a cap, so a subsample that changed with the fit-job or prediction-worker count would have passed them. The new tests fit and draw two capped cases under 1 and 4 fit jobs and prediction workers and require equal float64 bytes: - an explicit max_samples_leaf=5 on a continuous target; - the automatic 4,096 cap the fit applies to a target with 24 distinct values. Each fit wraps random.seed and random.shuffle and requires one seed per tree followed by one shuffle per leaf of that tree, all on the thread that called the fit. A second test shows the draws change when other leaf samples are kept (984 and 86 of 1,001 rows), so equal bytes are not vacuous. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_qrf_worker_counts.py | 282 +++++++++++++++++- 1 file changed, 279 insertions(+), 3 deletions(-) diff --git a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py index 29d88b0bb4..4c52e0ef4e 100644 --- a/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py +++ b/packages/microcosm-fit/tests/engine_free/shared/test_qrf_worker_counts.py @@ -11,13 +11,25 @@ several of either, and require the float64 bytes of every draw to be equal. Each run records the thread pool the draw used, so a draw that silently ran on one thread fails, and the ``n_jobs`` each forest was configured with. + +Forests with a leaf-size cap (``max_samples_leaf``) keep a seeded subsample of +each larger leaf, taken with Python's global :mod:`random`: for each tree in +turn, the fit seeds it with the tree's seed and shuffles that tree's leaves. +Their tests also record that every leaf was subsampled, on the thread that +called the fit, and show that keeping other samples changes the draw, so equal +bytes are not vacuous. """ from __future__ import annotations +import collections +import functools import os +import random +import threading from collections.abc import Callable, Iterator from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass import joblib import numpy as np @@ -27,6 +39,7 @@ from microcosm.fit import QRF, Regime, RegimeGatedQRF from microcosm.fit import qrf as qrf_module from microcosm.fit.qrf import _fit_n_jobs, _predict_workers +from microcosm.frame import Frame PREDICT_WORKERS_ENV = "POPULACE_FIT_PREDICT_WORKERS" FIT_JOBS_ENV = "POPULACE_FIT_N_JOBS" @@ -166,16 +179,21 @@ def map(self, function, chunk_bounds, *args, **kwargs) -> Iterator: return RecordingThreadPoolExecutor -def _forest_fit_jobs(target_models: dict) -> list[int]: - """The ``n_jobs`` of every forest in a fitted model's targets.""" +def _fitted_forests(target_models: dict) -> list: + """Every forest of a fitted model's targets, in target order.""" return [ - forest.model.n_jobs + forest for target_model in target_models.values() for forest in (target_model.positive, target_model.negative) if forest is not None ] +def _forest_fit_jobs(target_models: dict) -> list[int]: + """The ``n_jobs`` of every forest in a fitted model's targets.""" + return [forest.model.n_jobs for forest in _fitted_forests(target_models)] + + def _run_under( monkeypatch: pytest.MonkeyPatch, setting: tuple[str, str], @@ -371,6 +389,264 @@ def run_chain(fit_jobs_per_target: tuple[str, str]): assert changed_state.to_dict() == unchanged_state.to_dict() +# ---------------------------------------------------------------------------- +# Capped leaves: the seeded leaf subsample ignores thread counts +# ---------------------------------------------------------------------------- + +#: The cap of the explicit-cap case. Its two features take six combinations of +#: values, so each tree's leaves hold about 200 bootstrap rows of mixed target +#: values, and every leaf is subsampled to 5. +EXPLICIT_LEAF_CAP = 5 + +#: Donor rows of the near-discrete case. Its one feature takes two values, so +#: each tree's leaves hold about 6,000 bootstrap rows, more than the automatic +#: cap of ``_DISCRETE_Y_LEAF_BOUND`` (4,096) that a near-discrete target gets. +NEAR_DISCRETE_DONOR_ROWS = 12_000 + +#: Distinct target values of the near-discrete case. +NEAR_DISCRETE_VALUE_COUNT = 24 + + +@dataclass(frozen=True) +class _CappedLeafCase: + """Donors, recipients and settings for one capped-leaf fit and draw.""" + + donor_columns: dict[str, np.ndarray] + donor_weights: np.ndarray + recipients: pd.DataFrame + features: list[str] + #: What the case passes to :class:`QRF` (``None`` lets the fit choose). + configured_leaf_cap: int | None + #: The cap the forest must end up with. + expected_leaf_cap: int + + +def _explicit_cap_case(seed: int) -> _CappedLeafCase: + """A continuous positive target with ``max_samples_leaf`` set to 5.""" + rng = np.random.default_rng(seed) + three_value_feature = rng.integers(0, 3, DONOR_ROWS).astype(np.float64) + two_value_feature = rng.integers(0, 2, DONOR_ROWS).astype(np.float64) + value = np.exp( + 1.0 + + 0.5 * three_value_feature + - 0.3 * two_value_feature + + rng.normal(0.0, 0.6, DONOR_ROWS) + ) + recipient_rng = np.random.default_rng(seed + 2) + recipients = pd.DataFrame( + { + "three_value_feature": recipient_rng.integers(0, 3, RECIPIENT_ROWS).astype( + np.float64 + ), + "two_value_feature": recipient_rng.integers(0, 2, RECIPIENT_ROWS).astype( + np.float64 + ), + }, + index=pd.RangeIndex(10_000, 10_000 + RECIPIENT_ROWS), + ) + return _CappedLeafCase( + donor_columns={ + "three_value_feature": three_value_feature, + "two_value_feature": two_value_feature, + "value": value, + }, + donor_weights=np.random.default_rng(seed + 1).uniform(0.5, 4.0, DONOR_ROWS), + recipients=recipients, + features=["three_value_feature", "two_value_feature"], + configured_leaf_cap=EXPLICIT_LEAF_CAP, + expected_leaf_cap=EXPLICIT_LEAF_CAP, + ) + + +def _near_discrete_case(seed: int) -> _CappedLeafCase: + """A target with 24 values, which the fit caps at 4,096 per leaf itself. + + The fit applies that cap to a target with 2 to ``_DISCRETE_Y_UNIQUE_MAX`` + (32) distinct values. With only a few values, keeping other leaf samples + moved few draws (5 of 1,001 rows with three values); with 24 it moves 86. + """ + rng = np.random.default_rng(seed) + two_value_feature = rng.integers(0, 2, NEAR_DISCRETE_DONOR_ROWS).astype(np.float64) + target_values = np.arange(1.0, NEAR_DISCRETE_VALUE_COUNT + 1.0) + rising_weights = np.linspace(1.0, 3.0, NEAR_DISCRETE_VALUE_COUNT) + value_where_feature_is_zero = rng.choice( + target_values, size=NEAR_DISCRETE_DONOR_ROWS + ) + value_where_feature_is_one = rng.choice( + target_values, + size=NEAR_DISCRETE_DONOR_ROWS, + p=rising_weights / rising_weights.sum(), + ) + value = np.where( + two_value_feature == 0.0, + value_where_feature_is_zero, + value_where_feature_is_one, + ) + recipient_feature = np.random.default_rng(seed + 2).integers(0, 2, RECIPIENT_ROWS) + recipients = pd.DataFrame( + {"two_value_feature": recipient_feature.astype(np.float64)}, + index=pd.RangeIndex(10_000, 10_000 + RECIPIENT_ROWS), + ) + return _CappedLeafCase( + donor_columns={"two_value_feature": two_value_feature, "value": value}, + donor_weights=np.random.default_rng(seed + 1).uniform( + 0.5, 4.0, NEAR_DISCRETE_DONOR_ROWS + ), + recipients=recipients, + features=["two_value_feature"], + configured_leaf_cap=None, + expected_leaf_cap=qrf_module._DISCRETE_Y_LEAF_BOUND, + ) + + +CAPPED_LEAF_CASES = ( + pytest.param(_explicit_cap_case, id="explicit_cap"), + pytest.param(_near_discrete_case, id="near_discrete_automatic_cap"), +) + + +def _capped_leaf_fit_and_draw( + case: _CappedLeafCase, + frame: Frame, + *, + keep_other_samples: bool = False, +) -> tuple[dict[str, np.ndarray], list[int]]: + """Fit and draw one capped-leaf case, recording the leaf-subsample calls. + + For each tree in turn, the fit seeds the global :mod:`random` once with the + tree's seed, then subsamples each leaf longer than the cap by calling + :func:`random.shuffle` on the leaf's sample list and keeping the first + ``cap`` entries, so each leaf's shuffle continues the random stream the + previous one left. The fit runs with both functions wrapped, and the run + fails unless: + + - each tree was seeded once with its own seed, and that seed was followed + by exactly one shuffle per leaf of that tree before the next seed. So + every leaf was subsampled and no tree's shuffles were mixed into another + tree's; the order of the trees is not checked, since it changes nothing; + - every call ran on the thread that called the fit. Worker threads sharing + the global :mod:`random` could interleave the trees' calls, and in these + small fixtures a tree's calls usually finish before a thread switch, so + the recorded seeds and shuffles alone would rarely show it. + + With ``keep_other_samples`` the shuffle wrapper also reverses each shuffled + list, so the fit keeps a different subsample. + """ + # [seed, shuffles made after that seed and before the next one], in call + # order. A shuffle before any seed is recorded under the seed ``None``. + shuffles_after_each_seed: list[list] = [] + subsample_threads: set[int] = set() + original_seed = random.seed + original_shuffle = random.shuffle + + def recording_seed(seed_value, *args, **kwargs) -> None: + original_seed(seed_value, *args, **kwargs) + shuffles_after_each_seed.append([seed_value, 0]) + subsample_threads.add(threading.get_ident()) + + def recording_shuffle(samples, *args, **kwargs) -> None: + original_shuffle(samples, *args, **kwargs) + if keep_other_samples: + samples[:] = samples[::-1] + if not shuffles_after_each_seed: + shuffles_after_each_seed.append([None, 0]) + shuffles_after_each_seed[-1][1] += 1 + subsample_threads.add(threading.get_ident()) + + fitting_thread = threading.get_ident() + with pytest.MonkeyPatch.context() as fit_patch: + fit_patch.setattr(random, "seed", recording_seed) + fit_patch.setattr(random, "shuffle", recording_shuffle) + fitted = QRF( + n_estimators=N_ESTIMATORS, + seed=47, + max_samples_leaf=case.configured_leaf_cap, + ).fit(frame, case.features, ["value"]) + + assert fitted.regimes() == {"value": Regime.POSITIVE_ONLY} + forests = _fitted_forests(fitted._target_models) + assert {forest.model.max_samples_leaf for forest in forests} == { + case.expected_leaf_cap + } + seed_and_leaf_count_per_tree = collections.Counter( + (tree.random_state, tree.tree_.n_leaves) + for forest in forests + for tree in forest.model.estimators_ + ) + recorded_seed_and_shuffle_counts = collections.Counter( + (seed_value, shuffle_count) + for seed_value, shuffle_count in shuffles_after_each_seed + ) + assert recorded_seed_and_shuffle_counts == seed_and_leaf_count_per_tree, ( + "the leaf subsample did not seed each tree once and then shuffle each " + "of that tree's leaves before seeding another tree" + ) + assert subsample_threads == {fitting_thread}, ( + "the leaf subsample ran on another thread than the one that called the fit" + ) + draws = fitted.predict(case.recipients) + return ( + {"value": draws["value"].to_numpy()}, + _forest_fit_jobs(fitted._target_models), + ) + + +@pytest.mark.parametrize("setting", COMPARED_SETTINGS) +@pytest.mark.parametrize("build_case", CAPPED_LEAF_CASES) +def test_capped_leaf_draws_are_byte_identical_across_thread_counts( + build_case: Callable[[int], _CappedLeafCase], + setting: tuple[str, str], + make_person_frame, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Forests that subsample their leaves draw the same bytes at any count.""" + case = build_case(seed=15) + frame = make_person_frame(case.donor_columns, case.donor_weights) + + def run() -> tuple[dict[str, np.ndarray], list[int]]: + return _capped_leaf_fit_and_draw(case, frame) + + serial = _run_under(monkeypatch, SERIAL, run) + _assert_byte_identical(serial, _run_under(monkeypatch, setting, run)) + + +@pytest.mark.parametrize("build_case", CAPPED_LEAF_CASES) +def test_capped_leaf_draws_change_when_other_leaf_samples_are_kept( + build_case: Callable[[int], _CappedLeafCase], + make_person_frame, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The capped-leaf draws depend on which samples each leaf keeps. + + So if a thread count changed the subsample, the byte comparison above would + fail rather than pass on draws that ignore the subsample. + """ + case = build_case(seed=15) + frame = make_person_frame(case.donor_columns, case.donor_weights) + + def run_keeping( + *, other_samples: bool + ) -> Callable[[], tuple[dict[str, np.ndarray], list[int]]]: + return functools.partial( + _capped_leaf_fit_and_draw, + case, + frame, + keep_other_samples=other_samples, + ) + + seeded_subsample_draws = _run_under( + monkeypatch, SERIAL, run_keeping(other_samples=False) + ) + other_subsample_draws = _run_under( + monkeypatch, SERIAL, run_keeping(other_samples=True) + ) + + assert ( + other_subsample_draws["value"].tobytes() + != seeded_subsample_draws["value"].tobytes() + ) + + def test_unset_prediction_workers_size_the_draw_pool_from_joblib( make_person_frame, monkeypatch: pytest.MonkeyPatch ) -> None: