From a2c1006739b7301135446605151b1563f4a048b7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:38:20 +0400 Subject: [PATCH 01/16] Add failing tests for the shared worker pool and per-reform rule-module removal Tests for microcosm.build.worker_pool (spawned workers, the initializer's state sent once per worker, worker replacement after a unit limit, a per-worker memory cap, re-running a unit whose worker died, ran out of memory or went over its cap, results in unit order, a per-worker environment) and for a 1-vs-N byte-identity helper. The head-to-head scorer's parallel tests now expect the shared pool and run worker replacement on every interpreter. Post-export scoring tests expect each reform's policyengine-core rule modules to be removed once its consumer opens the next reform or finishes. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_worker_pool.py | 431 ++++++++++++++++++ .../us/test_us_post_export_scoring.py | 108 +++++ .../us/test_us_release_head_to_head_scorer.py | 148 +----- .../us/test_us_post_export_scoring.py | 63 +++ .../microcosm_build/us_post_export_scoring.py | 50 +- .../us_release_head_to_head_scorer.py | 10 +- .../us_release_head_to_head_worker_death.py | 4 +- .../microcosm_build/worker_pool_units.py | 132 ++++++ 8 files changed, 808 insertions(+), 138 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py create mode 100644 test_support/microcosm_build/worker_pool_units.py diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py new file mode 100644 index 0000000000..9dd2131c44 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -0,0 +1,431 @@ +"""The shared worker pool for household-batched work, in spawned processes.""" + +from __future__ import annotations + +import multiprocessing +import os +import signal +from collections import Counter + +import numpy as np +import pytest + +from microcosm.build.worker_pool import ( + WorkerPool, + WorkerPoolError, + WorkerPoolSettings, + WorkerPoolUnitError, + process_memory_bytes, +) +from test_support.microcosm_build import worker_pool_units as units +from test_support.microcosm_build.worker_pool_identity import ( + assert_identical_across_worker_counts, + canonical_result_bytes, +) + +MIB = 1024 * 1024 +TEST_SECONDS_LIMIT = 120 + + +@pytest.fixture(autouse=True) +def no_worker_left_behind(): + """Stop a hung test, and check every test leaves no worker running.""" + + def expire(signum, frame): + raise TimeoutError(f"worker-pool test ran past {TEST_SECONDS_LIMIT} seconds") + + previous_handler = signal.signal(signal.SIGALRM, expire) + signal.setitimer(signal.ITIMER_REAL, TEST_SECONDS_LIMIT) + try: + yield + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, previous_handler) + leftover = multiprocessing.active_children() + for process in leftover: + process.kill() + process.join(5) + assert leftover == [] + + +def test_results_come_back_in_unit_order_whatever_order_they_finish() -> None: + # Earlier units sleep longer, so they finish after later ones. + work = [(index, 0.6 - 0.15 * index) for index in range(4)] + with WorkerPool( + WorkerPoolSettings(workers=3), unit_function=units.sleep_then_return + ) as pool: + assert list(pool.map(work)) == [0, 1, 2, 3] + + +def test_the_initializer_runs_once_in_each_worker_and_its_state_reaches_each_unit() -> ( + None +): + payload = np.arange(1_000, dtype=np.float64) + with WorkerPool( + WorkerPoolSettings(workers=2), + initializer=units.initialize_with_payload, + initargs=(payload,), + unit_function=units.describe_worker, + ) as pool: + results = list(pool.map(range(6))) + report = pool.report() + + assert [result["unit"] for result in results] == list(range(6)) + assert all(result["initializer_calls"] == 1 for result in results) + assert all(result["payload_total"] == float(payload.sum()) for result in results) + worker_pids = {result["pid"] for result in results} + assert os.getpid() not in worker_pids + assert len(worker_pids) <= report.worker_starts == 2 + assert report.units_completed == 6 + + +def test_workers_are_replaced_after_their_unit_limit_and_never_outnumber_the_setting() -> ( + None +): + with WorkerPool( + WorkerPoolSettings(workers=2, max_units_per_worker=2), + initializer=units.initialize_with_payload, + initargs=(np.ones(10),), + unit_function=units.describe_worker, + ) as pool: + results = list(pool.map(range(7))) + report = pool.report() + + assert [result["unit"] for result in results] == list(range(7)) + units_per_worker = Counter(result["pid"] for result in results) + assert max(units_per_worker.values()) <= 2 + assert len(units_per_worker) >= 4 + # Each replacement worker ran its own initializer once. + assert all(result["initializer_calls"] == 1 for result in results) + assert report.worker_starts >= len(units_per_worker) + assert report.max_live_workers <= 2 + + +def test_a_second_map_reuses_the_live_workers() -> None: + with WorkerPool( + WorkerPoolSettings(workers=1), + initializer=units.initialize_with_payload, + initargs=(np.ones(3),), + unit_function=units.describe_worker, + ) as pool: + first = list(pool.map(range(2))) + second = list(pool.map(range(2, 4))) + report = pool.report() + + assert [result["unit"] for result in first + second] == [0, 1, 2, 3] + assert len({result["pid"] for result in first + second}) == 1 + assert report.worker_starts == 1 + + +def test_no_unit_starts_further_ahead_than_the_window_allows() -> None: + # Unit 0 runs long. With a window of two units, unit 2 may not start until + # unit 0's result has been handed back, although a third worker is idle. + work = [(0, 1.0), (1, 0.0), (2, 0.0), (3, 0.0)] + with WorkerPool( + WorkerPoolSettings(workers=3, max_units_ahead=2), + unit_function=units.record_run_times, + ) as pool: + results = list(pool.map(work)) + + assert [value for value, _, _ in results] == [0, 1, 2, 3] + unit_zero_ended = results[0][2] + assert all(started >= unit_zero_ended for _, started, _ in results[2:]) + + +def test_a_worker_that_dies_has_its_unit_run_again_in_a_fresh_worker(tmp_path) -> None: + markers = [tmp_path / f"unit-{index}" for index in range(3)] + # Only unit 1 finds no marker, so only its first attempt kills its worker. + markers[0].write_text("not this one") + markers[2].write_text("not this one") + work = [(index, str(marker)) for index, marker in enumerate(markers)] + with WorkerPool( + WorkerPoolSettings(workers=2, max_attempts=2), + unit_function=units.die_on_first_attempt, + ) as pool: + results = list(pool.map(work)) + report = pool.report() + + assert [value for value, _ in results] == [0, 1, 2] + dead_worker = int(markers[1].read_text()) + assert results[1][1] != dead_worker + assert len(report.failed_attempts) == 1 + failure = report.failed_attempts[0] + assert (failure.unit_index, failure.attempt, failure.worker_pid) == ( + 1, + 1, + dead_worker, + ) + assert "exited with code 97" in failure.cause + + +def test_a_unit_that_keeps_killing_its_worker_stops_the_run_with_its_label() -> None: + with WorkerPool( + WorkerPoolSettings(workers=2, max_attempts=2), + unit_function=units.always_die, + describe_unit=lambda index, unit: f"fixture batch {index + 1}", + ) as pool: + with pytest.raises( + WorkerPoolUnitError, match=r"fixture batch 1 failed on all 2 attempts" + ) as failure: + list(pool.map([0])) + + assert failure.value.unit_index == 0 + assert failure.value.label == "fixture batch 1" + assert len(failure.value.causes) == 2 + assert all("exited with code 97" in cause for cause in failure.value.causes) + + +def test_a_worker_over_its_memory_cap_is_stopped_and_its_unit_run_again( + tmp_path, +) -> None: + marker = tmp_path / "held" + cap = 512 * MIB + with WorkerPool( + WorkerPoolSettings(workers=1, memory_cap_bytes=cap, memory_poll_seconds=0.05), + unit_function=units.hold_memory_on_first_attempt, + ) as pool: + results = list(pool.map([(7, str(marker), 1_024)])) + report = pool.report() + + assert results[0][0] == 7 + assert results[0][1] != int(marker.read_text()) + assert len(report.failed_attempts) == 1 + assert "memory cap" in report.failed_attempts[0].cause + assert report.peak_worker_memory_bytes > cap + + +def test_a_unit_that_needs_more_than_the_memory_cap_stops_the_run() -> None: + with WorkerPool( + WorkerPoolSettings( + workers=1, memory_cap_bytes=512 * MIB, memory_poll_seconds=0.05 + ), + unit_function=units.always_hold_memory, + ) as pool: + with pytest.raises(WorkerPoolUnitError, match="unit 1/1") as failure: + list(pool.map([1_024])) + + assert len(failure.value.causes) == 2 + assert all("memory cap" in cause for cause in failure.value.causes) + + +def test_a_memory_error_runs_the_unit_again_in_a_fresh_worker(tmp_path) -> None: + marker = tmp_path / "memory-error" + with WorkerPool( + WorkerPoolSettings(workers=1), unit_function=units.memory_error_on_first_attempt + ) as pool: + results = list(pool.map([(5, str(marker))])) + report = pool.report() + + assert results[0][0] == 5 + assert results[0][1] != int(marker.read_text()) + assert "MemoryError: fixture allocation failed" in report.failed_attempts[0].cause + + +def test_a_unit_exception_stops_the_run_without_running_it_again() -> None: + pool = WorkerPool( + WorkerPoolSettings(workers=2), unit_function=units.refuse_unit_two + ) + with pool: + with pytest.raises( + WorkerPoolUnitError, match=r"unit 3/4 .*ValueError: fixture unit 2 refuses" + ) as failure: + list(pool.map(range(4))) + + assert len(failure.value.causes) == 1 + assert "Traceback" in str(failure.value.__cause__) + with pytest.raises(WorkerPoolError, match="closed"): + list(pool.map(range(1))) + + +def test_a_result_the_worker_cannot_send_stops_the_run() -> None: + with WorkerPool( + WorkerPoolSettings(workers=1), unit_function=units.return_unpicklable + ) as pool: + with pytest.raises(WorkerPoolUnitError, match="unit 1/1 .*could not be sent"): + list(pool.map([0])) + + +def test_an_initializer_failure_stops_the_run_before_any_unit() -> None: + with WorkerPool( + WorkerPoolSettings(workers=2), + initializer=units.fail_to_start, + unit_function=units.describe_worker, + ) as pool: + with pytest.raises(WorkerPoolError, match="fixture initializer refuses"): + list(pool.map(range(3))) + + +def test_the_worker_environment_is_set_before_the_worker_imports_anything( + monkeypatch, +) -> None: + monkeypatch.delenv(units.ENVIRONMENT_VARIABLE, raising=False) + settings = WorkerPoolSettings( + workers=1, worker_environment={units.ENVIRONMENT_VARIABLE: "set for workers"} + ) + with WorkerPool(settings, unit_function=units.report_environment) as pool: + (result,) = pool.map([0]) + + assert result["at_import"] == "set for workers" + assert result["at_unit"] == "set for workers" + assert units.ENVIRONMENT_VARIABLE not in os.environ + + +def test_without_a_worker_environment_workers_inherit_the_parents(monkeypatch) -> None: + monkeypatch.setenv(units.ENVIRONMENT_VARIABLE, "the parent's value") + with WorkerPool( + WorkerPoolSettings(workers=1), unit_function=units.report_environment + ) as pool: + (result,) = pool.map([0]) + + assert result["at_import"] == "the parent's value" + assert os.environ[units.ENVIRONMENT_VARIABLE] == "the parent's value" + + +def test_closing_an_unfinished_map_stops_every_worker() -> None: + pool = WorkerPool( + WorkerPoolSettings(workers=2), unit_function=units.sleep_then_return + ) + results = pool.map([(index, 0.3) for index in range(6)]) + assert next(results) == 0 + results.close() + + assert multiprocessing.active_children() == [] + with pytest.raises(WorkerPoolError, match="closed"): + list(pool.map([(0, 0.0)])) + + +@pytest.mark.parametrize( + "setting", + [ + {"workers": 0}, + {"max_units_per_worker": 0}, + {"max_attempts": 0}, + {"memory_cap_bytes": 0}, + {"max_units_ahead": 0}, + {"memory_poll_seconds": 0.0}, + ], +) +def test_settings_refuse_values_that_cannot_run(setting) -> None: + with pytest.raises(ValueError, match=next(iter(setting))): + WorkerPoolSettings(**{"workers": 2, **setting}) + + +def test_functions_a_worker_cannot_import_are_refused_before_any_worker_starts() -> ( + None +): + with pytest.raises(TypeError, match="importable"): + WorkerPool( + WorkerPoolSettings(workers=1), unit_function=lambda state, unit: unit + ) + with pytest.raises(TypeError, match="importable"): + WorkerPool( + WorkerPoolSettings(workers=1), + initializer=lambda: None, + unit_function=units.describe_worker, + ) + + +def test_process_memory_bytes_sees_this_process_grow() -> None: + before = process_memory_bytes(os.getpid()) + held = np.ones(256 * MIB // 8) + after = process_memory_bytes(os.getpid()) + assert before is not None and before > 10 * MIB + assert after - before >= 200 * MIB + del held + + +# --------------------------------------------------------------------------- +# The 1-vs-N byte-identity helper +# --------------------------------------------------------------------------- + +_HOUSEHOLDS = 5_003 +_BATCH_SIZE = 500 + + +def _household_arrays(): + generator = np.random.default_rng(20261125) + values = generator.lognormal(10.0, 1.5, _HOUSEHOLDS) + weights = generator.uniform(0.5, 3.0, _HOUSEHOLDS) + return values, weights + + +def _household_batches(): + return [ + (start, min(start + _BATCH_SIZE, _HOUSEHOLDS)) + for start in range(0, _HOUSEHOLDS, _BATCH_SIZE) + ] + + +def _join_in_batch_order(parts): + """Concatenate per-household arrays and sum totals in batch order.""" + total = np.float64(parts[0]["weighted_total"]) + for part in parts[1:]: + total = np.add(total, part["weighted_total"]) + return { + "per_household": np.concatenate([part["per_household"] for part in parts]), + "weighted_total": total, + "batches": len(parts), + } + + +def _pooled_household_run(workers: int, *, max_units_per_worker=None): + with WorkerPool( + WorkerPoolSettings(workers=workers, max_units_per_worker=max_units_per_worker), + initializer=units.initialize_household_arrays, + initargs=_household_arrays(), + unit_function=units.score_household_batch, + ) as pool: + return _join_in_batch_order(list(pool.map(_household_batches()))) + + +def test_one_and_several_workers_give_byte_identical_results() -> None: + pooled = assert_identical_across_worker_counts( + _pooled_household_run, worker_counts=(1, 3) + ) + state = units.initialize_household_arrays(*_household_arrays()) + in_process = _join_in_batch_order( + [units.score_household_batch(state, batch) for batch in _household_batches()] + ) + + assert pooled["batches"] == 11 + assert canonical_result_bytes(pooled) == canonical_result_bytes(in_process) + + +def test_replacing_workers_after_every_unit_keeps_results_byte_identical() -> None: + assert_identical_across_worker_counts( + lambda workers: _pooled_household_run(workers, max_units_per_worker=1), + worker_counts=(1, 4), + ) + + +def test_the_identity_helper_names_the_first_difference() -> None: + def run(workers: int): + return { + "label": "same", + "totals": np.array([1.0, 0.0 if workers == 1 else -0.0]), + } + + with pytest.raises(AssertionError, match=r"workers=3 .*\['totals'\]"): + assert_identical_across_worker_counts(run, worker_counts=(1, 3)) + + +def test_canonical_bytes_tell_apart_what_equality_hides() -> None: + assert canonical_result_bytes(np.float64(0.0)) != canonical_result_bytes( + np.float64(-0.0) + ) + assert canonical_result_bytes(np.array([np.nan])) != canonical_result_bytes( + -np.array([np.nan]) + ) + assert canonical_result_bytes( + np.array([1, 2], dtype=np.int64) + ) != canonical_result_bytes(np.array([1, 2], dtype=np.int32)) + assert canonical_result_bytes(np.zeros((2, 3))) != canonical_result_bytes( + np.zeros((3, 2)) + ) + assert canonical_result_bytes({"a": 1, "b": 2}) != canonical_result_bytes( + {"b": 2, "a": 1} + ) + assert canonical_result_bytes(1.0) != canonical_result_bytes(1) + assert canonical_result_bytes((1, 2)) != canonical_result_bytes([1, 2]) + with pytest.raises(TypeError, match="object"): + canonical_result_bytes(object()) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index deeeb97a7f..69b621fa22 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py @@ -1928,3 +1928,111 @@ def recording_dataset_from_frame(frame, **kwargs): assert scorer._dataset_from_frame(first_batch) is first_batch assert calls == [{"assert_no_formula_owned_columns": False}] + + +# --------------------------------------------------------------------------- +# Rule modules: each reform's are removed once the consumer moves on +# --------------------------------------------------------------------------- + + +def _stand_in_rule_modules_left(variables_dir) -> list[str]: + return [ + name + for name, module in tuple(sys.modules.items()) + if str(getattr(module, "__file__", "")).startswith(str(variables_dir)) + ] + + +def test_each_reform_releases_its_rule_modules_once_the_next_reform_opens( + builder, fake_reforms, stand_in_rule_modules, tmp_path +) -> None: + """policyengine-core never removes the variable modules a rules build adds + to ``sys.modules``. The scorer removes a reform's once its consumer opens + the next reform or finishes, refuses to score a finished reform again, and + scores the same values.""" + frame = _nested_frame() + log = _EngineLog() + scorer = _scorer( + builder, + frame, + log, + 3, + tmp_path / "released", + variables_dir=stand_in_rule_modules, + ) + consumer = scorer.open_consumer("fixture", ()) + first = consumer.simulate(_FakeReform("first")) + first_values = first.calculate("income_tax", builder.PERIOD) + first_module = _rule_module_name(log.systems[0]) + assert first_module in sys.modules + + second = consumer.simulate(_FakeReform("second")) + assert first_module not in sys.modules + with pytest.raises(RuntimeError, match="finished reform"): + first.calculate("income_tax", builder.PERIOD + 1) + second_values = second.calculate("income_tax", builder.PERIOD) + second_module = _rule_module_name(log.systems[1]) + assert second_module in sys.modules + + scorer.finish_consumer(consumer) + assert second_module not in sys.modules + assert _stand_in_rule_modules_left(stand_in_rule_modules) == [] + + reference = _scorer(builder, frame, _EngineLog(), 3, tmp_path / "reference") + reference_consumer = reference.open_consumer("fixture", ()) + for label, values in (("first", first_values), ("second", second_values)): + expected = reference_consumer.simulate(_FakeReform(label)).calculate( + "income_tax", builder.PERIOD + ) + assert np.asarray(values).tobytes() == np.asarray(expected).tobytes() + assert values.weights.tobytes() == expected.weights.tobytes() + + +def test_closing_the_scorer_releases_an_unfinished_consumers_rule_modules( + builder, fake_reforms, stand_in_rule_modules, tmp_path +) -> None: + log = _EngineLog() + scorer = _scorer( + builder, _nested_frame(), log, 3, tmp_path, variables_dir=stand_in_rule_modules + ) + consumer = scorer.open_consumer("fixture", ()) + consumer.simulate(_FakeReform("only")).calculate("income_tax", builder.PERIOD) + assert _rule_module_name(log.systems[0]) in sys.modules + + scorer.close() + + assert _stand_in_rule_modules_left(stand_in_rule_modules) == [] + + +def test_the_shipped_consumers_leave_no_rule_modules_and_score_the_same( + builder, fake_reforms, stand_in_rule_modules, tmp_path +) -> None: + frame = _nested_frame() + reference, _, _, _ = _batched_run(builder, frame, 3, tmp_path / "reference") + log = _EngineLog() + scorer = _scorer( + builder, + frame, + log, + 3, + tmp_path / "released", + variables_dir=stand_in_rule_modules, + ) + consumers: dict[str, object] = {} + + def simulate_for(name, consumer): + plan = builder._record_post_export_baseline_plan(consumer) + consumers[name] = scorer.open_consumer(name, plan) + return consumers[name].simulate + + gate, payload, demographics = _run_consumers(builder, simulate_for) + for consumer in consumers.values(): + scorer.finish_consumer(consumer) + + reference_gate, reference_payload, reference_demographics = reference + assert gate.passed == reference_gate.passed + assert gate.details == reference_gate.details + assert payload == reference_payload + assert demographics == reference_demographics + assert len(log.systems) > 43 + assert _stand_in_rule_modules_left(stand_in_rule_modules) == [] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_head_to_head_scorer.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_head_to_head_scorer.py index 16c16c7fc6..7e4cfbaada 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_head_to_head_scorer.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_head_to_head_scorer.py @@ -5,12 +5,11 @@ import multiprocessing import signal import time -from concurrent.futures import ProcessPoolExecutor -from concurrent.futures.process import BrokenProcessPool from hypothesis import HealthCheck, example, given, settings from hypothesis import strategies as st +from microcosm.build.worker_pool import WorkerPool, WorkerPoolUnitError from test_support.microcosm_build.us_release_head_to_head_scorer import * @@ -32,63 +31,14 @@ def test_head_to_head_signature_has_no_target_membership_switches() -> None: } -@pytest.mark.parametrize( - ("version", "supported"), - [ - ((3, 13, 9), False), - ((3, 13, 14), False), - ((3, 13, 15), True), - ((3, 14, 0), False), - ((3, 14, 6), False), - ((3, 14, 7), True), - ((3, 15, 0), True), - ((3, 12, 11), False), - # 3.15 prereleases: the fix landed in beta 4. - ((3, 15, 0, "alpha", 7), False), - ((3, 15, 0, "beta", 3), False), - ((3, 15, 0, "beta", 4), True), - ((3, 15, 0, "candidate", 1), True), - ((3, 15, 0, "final", 0), True), - # A prerelease of a fixed patch is not yet the fixed release. - ((3, 14, 7, "candidate", 1), False), - ((3, 14, 7, "final", 0), True), - ((3, 16, 0, "alpha", 1), True), - ], -) -def test_worker_recycling_refuses_interpreters_that_can_deadlock( - version: tuple, supported: bool -) -> None: +def test_parallel_scoring_runs_on_the_shared_worker_pool() -> None: module = _load_head_to_head_module() - if supported: - module._assert_worker_recycling_supported(version) - else: - with pytest.raises(RuntimeError, match="--worker-max-slices needs Python"): - module._assert_worker_recycling_supported(version) - - -def test_scoring_checks_the_interpreter_only_when_recycling_is_requested( - monkeypatch, -) -> None: - module = _load_head_to_head_module() - calls: list[str] = [] - - def refuse(version_info=None) -> None: - calls.append("checked") - raise RuntimeError("--worker-max-slices needs Python 3.13.15 or later") - - monkeypatch.setattr(module, "_assert_worker_recycling_supported", refuse) - - with pytest.raises(RuntimeError, match="--worker-max-slices needs Python"): - module.score_loaded_artifact( - artifact=None, - artifact_name="incumbent", - yardstick=None, - maximum_microsim_batch_size=2, - workers=2, - worker_max_slices=1, - ) - assert calls == ["checked"] + assert module.WorkerPool is WorkerPool + assert not hasattr(module, "ProcessPoolExecutor") + # Worker replacement needs no interpreter check: the shared pool replaces + # workers itself instead of through ProcessPoolExecutor. + assert not hasattr(module, "_assert_worker_recycling_supported") def _parallel_fixture(module, monkeypatch): @@ -136,13 +86,6 @@ def capture_estimates(**kwargs): # Six tasks per artifact force a replacement even for two workers with K=2. # The single-worker recycling case also verifies K opts into spawn by itself. configurations = [(1, None), (3, None), (2, 1), (2, 2), (1, 2)] - try: - module._assert_worker_recycling_supported() - except RuntimeError: - # This interpreter can deadlock replacing a recycled worker, so the CLI - # refuses --worker-max-slices on it, as the refusal tests above check. - # The configurations without recycling still run. - configurations = [config for config in configurations if config[1] is None] for workers, worker_max_slices in configurations: prefix = tmp_path / f"workers-{workers}-max-slices-{worker_max_slices}" worker_log_dir = tmp_path / f"{prefix.name}-slice-logs" @@ -252,48 +195,13 @@ def test_abrupt_worker_death_is_labelled_and_leaves_no_children(monkeypatch) -> ) module = _load_head_to_head_module() - executors = [] - - class TrackingExecutor(ProcessPoolExecutor): - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.children = {} - self.shutdown_completed = False - self.shutdown_waited = False - executors.append(self) - - def submit(self, *args, **kwargs): - try: - return super().submit(*args, **kwargs) - finally: - self.children.update(self._processes or {}) - - def shutdown(self, wait=True, *, cancel_futures=False): - self.children.update(self._processes or {}) - self.shutdown_waited = wait - super().shutdown(wait=wait, cancel_futures=cancel_futures) - self.shutdown_completed = True - monkeypatch.setattr(module, "MATERIALIZE_SCORE_CHUNK_SPECS", 1) - monkeypatch.setattr(module, "ProcessPoolExecutor", TrackingExecutor) monkeypatch.setattr(module, "_initialize_slice_worker", initialize_slice_worker) monkeypatch.setattr(module, "_score_slice_worker", exit_slice_worker) - def kill_alive_workers() -> None: - for executor in executors: - for process in executor.children.values(): - try: - if process.is_alive(): - process.kill() - except ProcessLookupError: - pass - - timed_out = False - def timeout_handler(signum, frame) -> None: - nonlocal timed_out - timed_out = True - kill_alive_workers() + for process in multiprocessing.active_children(): + process.kill() raise TimeoutError("worker death pool did not shut down within 60 seconds") old_handler = signal.getsignal(signal.SIGALRM) @@ -302,8 +210,8 @@ def timeout_handler(signum, frame) -> None: signal.signal(signal.SIGALRM, timeout_handler) signal.setitimer(signal.ITIMER_REAL, 60) with pytest.raises( - RuntimeError, - match=r"fixture chunk [12]/2 slice 1/1 worker (?:submission )?failed:", + WorkerPoolUnitError, + match=r"fixture chunk [12]/2 slice 1/1 failed on all 2 attempts", ) as failure: list( module._score_chunks_parallel( @@ -316,31 +224,16 @@ def timeout_handler(signum, frame) -> None: ) ) - # Check production shutdown before our defensive cleanup can run. - assert timed_out is False - assert isinstance(failure.value.__cause__, BrokenProcessPool) - assert len(executors) == 1 - executor = executors[0] - assert executor.shutdown_completed is True - assert executor.shutdown_waited is True - children = list(executor.children.values()) - assert children - assert any(process.exitcode == 97 for process in children) - assert all( - not process.is_alive() and process.exitcode is not None - for process in children - ) + assert len(failure.value.causes) == 2 + assert all("exited with code 97" in cause for cause in failure.value.causes) assert multiprocessing.active_children() == [] finally: signal.setitimer(signal.ITIMER_REAL, 0) - try: - kill_alive_workers() - for executor in executors: - for process in executor.children.values(): - process.join(timeout=5) - finally: - signal.signal(signal.SIGALRM, old_handler) - signal.setitimer(signal.ITIMER_REAL, *old_timer) + for process in multiprocessing.active_children(): + process.kill() + process.join(timeout=5) + signal.signal(signal.SIGALRM, old_handler) + signal.setitimer(signal.ITIMER_REAL, *old_timer) @pytest.mark.parametrize("workers", [0, -1]) @@ -412,11 +305,10 @@ def assert_full_slice_guard(frame, specs, **kwargs): monkeypatch.setattr( module.release, "_materialize_target_frame", assert_full_slice_guard ) - monkeypatch.setattr(module, "_SLICE_WORKER_STATE", None) - module._initialize_slice_worker( + state = module._initialize_slice_worker( frame, yardstick.registry.specs, yardstick.loss_weights, "fixture", 2, None ) - worker_result = module._score_slice_worker((0, 0)) + worker_result = module._score_slice_worker(state, (0, 0)) parallel = module._reduce_scored_slices( [worker_result], slice_count=1, diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py index 7721dc0c67..d193a1530a 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py @@ -36,6 +36,7 @@ def test_watched_formula_lists_match_the_installed_engine(builder) -> None: for response, subtree in builder.POST_EXPORT_BEHAVIORAL_RESPONSE_PARAMETERS.items(): assert f"parameters(period).{subtree}" in sources[response], response + @pytest.mark.slow def test_batched_scoring_matches_whole_pool_policyengine_us(builder, tmp_path) -> None: """(l) On a small written H5 with Maryland households, three probes and @@ -181,6 +182,7 @@ def smoke(simulate): ) scorer.close() + @pytest.mark.slow def test_additivity_guards_fire_on_the_installed_engine(builder, tmp_path) -> None: """The three additivity guards refuse on policyengine-us itself. @@ -265,6 +267,7 @@ def test_additivity_guards_fire_on_the_installed_engine(builder, tmp_path) -> No assert (record["reform_systems"], record["reform_passes"]) == (2, 1) scorer.close() + @pytest.mark.slow def test_shipped_baseline_plans_match_whole_file_policyengine_us( builder, tmp_path @@ -291,3 +294,63 @@ def test_shipped_baseline_plans_match_whole_file_policyengine_us( sweep._score_baselines(builder, scorer, path, plans) finally: scorer.close() + + +@pytest.mark.slow +def test_reform_passes_leave_no_rule_modules_behind_and_score_the_same( + builder, tmp_path, monkeypatch +) -> None: + """Each reform's rules build adds about 6,000 variable modules to + ``sys.modules`` that policyengine-core never removes (about 0.04 GiB a + reform pass on this fixture). The scorer removes them once the consumer + opens the next reform or finishes, and the scored arrays are byte-identical + to scoring without the removal.""" + import contextlib + + import policyengine_us + + from microcosm.build.us_runtime.reform_coverage_smoke import _build_reform + + source = _write_engine_h5(builder, tmp_path / "export", _GUARD_HOUSEHOLDS) + probes = {probe.id: probe for probe in us_release_reform_coverage_probes()} + chosen = [ + probes["keogh_distribution_neutralization"], + probes["collectibles_gain_neutralization"], + ] + variables_dir = str( + Path(policyengine_us.CountryTaxBenefitSystem.variables_dir).absolute() + ) + + def rule_modules() -> set[str]: + return { + name + for name, module in tuple(sys.modules.items()) + if re.fullmatch(r"\d+_-?\d+_\w+", name) + and str(getattr(module, "__file__", "")).startswith(variables_dir) + } + + def score(): + scorer = builder._HouseholdBatchedPostExportScorer( + source, maximum_microsim_batch_size=None + ) + consumer = scorer.open_consumer("fixture", ()) + before = rule_modules() + scored = [] + for probe in chosen: + values = consumer.simulate(_build_reform(probe)).calculate( + probe.budget_measure, period=probe.period + ) + scored.append((np.asarray(values).tobytes(), values.weights.tobytes())) + scorer.finish_consumer(consumer) + scorer.close() + return before, rule_modules(), scored + + before, after, released = score() + assert after == before + + monkeypatch.setattr( + builder, "temporary_engine_variable_modules", contextlib.nullcontext + ) + kept_before, kept_after, kept = score() + assert len(kept_after - kept_before) >= 2 * 1_000 + assert released == kept diff --git a/test_support/microcosm_build/us_post_export_scoring.py b/test_support/microcosm_build/us_post_export_scoring.py index ae4f7bbbee..ca6b83e7a6 100644 --- a/test_support/microcosm_build/us_post_export_scoring.py +++ b/test_support/microcosm_build/us_post_export_scoring.py @@ -36,7 +36,7 @@ import warnings import zlib from pathlib import Path -from types import SimpleNamespace +from types import ModuleType, SimpleNamespace import numpy as np import pandas as pd @@ -347,7 +347,20 @@ def __init__(self) -> None: self.stored_inputs: dict[str, tuple[int, ...]] = {} -def _fake_engine(log: _EngineLog): +def _rule_module_name(system) -> str: + """The name policyengine-core gives a system's variable module.""" + return f"{id(system)}_-1_income_tax" + + +def _fake_engine(log: _EngineLog, *, variables_dir: Path | None = None): + """A fake engine; with ``variables_dir``, each rules build registers a module. + + policyengine-core registers every variable module of every system it builds + in ``sys.modules`` under ``__`` and never + removes it. A fake system built with ``variables_dir`` registers one such + module, whose file is under ``variables_dir``. + """ + class FakeSystem: def __init__(self, reform=None) -> None: self.reform = reform @@ -355,6 +368,10 @@ def __init__(self, reform=None) -> None: {} if reform is None else reform.parameters ) log.systems.append(self) + if variables_dir is not None: + module = ModuleType(_rule_module_name(self)) + module.__file__ = str(variables_dir / "income_tax.py") + sys.modules[module.__name__] = module class FakeHolder: def __init__(self, periods) -> None: @@ -421,6 +438,29 @@ def calculate(self, variable, period, map_to=None): return FakeMicrosimulation +@pytest.fixture +def stand_in_rule_modules(monkeypatch, tmp_path): + """A stand-in installed policyengine-us whose variables live in a fixture dir. + + The module-removal helper finds the installed engine's variables directory + through ``sys.modules["policyengine_us"]``. Returns that directory, to pass + as ``_scorer(..., variables_dir=...)``. + """ + variables_dir = tmp_path / "stand-in-variables" + engine = ModuleType("policyengine_us") + engine.CountryTaxBenefitSystem = SimpleNamespace(variables_dir=variables_dir) + engine.Microsimulation = SimpleNamespace( + default_tax_benefit_system_instance=SimpleNamespace() + ) + monkeypatch.setitem(sys.modules, "policyengine_us", engine) + registered_before = set(sys.modules) + yield variables_dir + for name in set(sys.modules) - registered_before: + module = sys.modules.get(name) + if str(getattr(module, "__file__", "")).startswith(str(variables_dir)): + del sys.modules[name] + + @pytest.fixture def fake_reforms(monkeypatch, builder): """Engine-free reform objects for the shipped probes and specs. @@ -477,7 +517,9 @@ def _written_h5(tmp_path: Path) -> Path: return path -def _scorer(builder, frame, log, batch_size, tmp_path, *, loads=None): +def _scorer( + builder, frame, log, batch_size, tmp_path, *, loads=None, variables_dir=None +): path = _written_h5(tmp_path) def load_frame(load_path, *, expected_sha256): @@ -488,7 +530,7 @@ def load_frame(load_path, *, expected_sha256): return builder._HouseholdBatchedPostExportScorer( path, maximum_microsim_batch_size=batch_size, - microsimulation_cls=_fake_engine(log), + microsimulation_cls=_fake_engine(log, variables_dir=variables_dir), dataset_from_frame=lambda batch_frame: batch_frame, load_frame=load_frame, ) diff --git a/test_support/microcosm_build/us_release_head_to_head_scorer.py b/test_support/microcosm_build/us_release_head_to_head_scorer.py index 878ce5e3e7..5469c292dc 100644 --- a/test_support/microcosm_build/us_release_head_to_head_scorer.py +++ b/test_support/microcosm_build/us_release_head_to_head_scorer.py @@ -241,10 +241,10 @@ def _fixture_materialize(frame, specs, **kwargs): ) -def _initialize_fixture_slice_worker(*args) -> None: +def _initialize_fixture_slice_worker(*args): """Install test seams explicitly because spawn inherits no monkeypatches.""" module = _load_head_to_head_module() - module._initialize_slice_worker(*args) + state = module._initialize_slice_worker(*args) _patch_release_seams(module, pytest.MonkeyPatch()) log_dir = os.environ.get("MICROCOSM_TEST_H2H_SLICE_LOG_DIR") if log_dir is not None: @@ -257,6 +257,7 @@ def record_slice(*args, **kwargs): return result module._score_household_slice = record_slice + return state def _failing_fixture_materialize(frame, specs, **kwargs): @@ -265,10 +266,11 @@ def _failing_fixture_materialize(frame, specs, **kwargs): return _fixture_materialize(frame, specs, **kwargs) -def _initialize_failing_fixture_slice_worker(*args) -> None: - _initialize_fixture_slice_worker(*args) +def _initialize_failing_fixture_slice_worker(*args): + state = _initialize_fixture_slice_worker(*args) module = _load_head_to_head_module() module.release._materialize_target_frame = _failing_fixture_materialize + return state def _three_household_fixture_artifact(module, *, sha256: str, measure_values): diff --git a/test_support/microcosm_build/us_release_head_to_head_worker_death.py b/test_support/microcosm_build/us_release_head_to_head_worker_death.py index 954cd7992c..ce764685d1 100644 --- a/test_support/microcosm_build/us_release_head_to_head_worker_death.py +++ b/test_support/microcosm_build/us_release_head_to_head_worker_death.py @@ -9,8 +9,8 @@ def n(self, entity: str) -> int: def initialize_slice_worker(*args) -> None: - pass + return None -def exit_slice_worker(task: tuple[int, int]) -> None: +def exit_slice_worker(state, task: tuple[int, int]) -> None: os._exit(97) diff --git a/test_support/microcosm_build/worker_pool_units.py b/test_support/microcosm_build/worker_pool_units.py new file mode 100644 index 0000000000..63423edd8d --- /dev/null +++ b/test_support/microcosm_build/worker_pool_units.py @@ -0,0 +1,132 @@ +"""Initializers and unit functions that spawned worker-pool workers import by name. + +Spawned workers start a fresh interpreter, so everything a test hands the pool +must be importable from a module, not defined inside a test. +""" + +from __future__ import annotations + +import os +import time +from pathlib import Path + +import numpy as np + +ENVIRONMENT_VARIABLE = "MICROCOSM_TEST_WORKER_POOL_VARIABLE" + +#: Read when a worker imports this module, before any pool code runs a unit. +ENVIRONMENT_AT_IMPORT = os.environ.get(ENVIRONMENT_VARIABLE) + +_INITIALIZER_CALLS = 0 + + +def initialize_with_payload(payload): + """Count this process's initializer calls and keep the payload.""" + global _INITIALIZER_CALLS + _INITIALIZER_CALLS += 1 + return {"payload": payload, "initializer_calls": _INITIALIZER_CALLS} + + +def describe_worker(state, unit): + return { + "unit": unit, + "pid": os.getpid(), + "initializer_calls": state["initializer_calls"], + "payload_total": float(np.sum(state["payload"])), + } + + +def sleep_then_return(state, unit): + value, seconds = unit + time.sleep(seconds) + return value + + +def record_run_times(state, unit): + """Sleep, then report when this unit started and ended in the worker.""" + value, seconds = unit + started = time.monotonic() + time.sleep(seconds) + return value, started, time.monotonic() + + +def _first_attempt(marker: str) -> bool: + path = Path(marker) + if path.exists(): + return False + path.write_text(str(os.getpid())) + return True + + +def die_on_first_attempt(state, unit): + value, marker = unit + if _first_attempt(marker): + os._exit(97) + return value, os.getpid() + + +def always_die(state, unit): + os._exit(97) + + +def hold_memory_on_first_attempt(state, unit): + value, marker, mebibytes = unit + if _first_attempt(marker): + held = np.ones(mebibytes * 1024 * 1024 // 8) + # The pool stops this worker for its memory long before this returns. + time.sleep(60) + return float(held[0]) + return value, os.getpid() + + +def always_hold_memory(state, unit): + mebibytes = unit + held = np.ones(mebibytes * 1024 * 1024 // 8) + time.sleep(60) + return float(held[0]) + + +def memory_error_on_first_attempt(state, unit): + value, marker = unit + if _first_attempt(marker): + raise MemoryError("fixture allocation failed") + return value, os.getpid() + + +def refuse_unit_two(state, unit): + if unit == 2: + raise ValueError(f"fixture unit {unit} refuses") + return unit + + +def return_unpicklable(state, unit): + return lambda: unit + + +def fail_to_start(*args): + raise RuntimeError("fixture initializer refuses") + + +def report_environment(state, unit): + return { + "at_import": ENVIRONMENT_AT_IMPORT, + "at_unit": os.environ.get(ENVIRONMENT_VARIABLE), + "pid": os.getpid(), + } + + +def initialize_household_arrays(values, weights): + """Stand-in for a worker's frame: whole-population arrays sent once.""" + return {"values": values, "weights": weights} + + +def score_household_batch(state, positions): + """Per-household and summed results for one contiguous household batch.""" + start, stop = positions + values = state["values"][start:stop] + weights = state["weights"][start:stop] + per_household = np.power(values, 1.5) * weights - np.sqrt(values) + return { + "per_household": per_household, + "weighted_total": np.sum(per_household * weights, dtype=np.float64), + } From a5cf47e8836eef1c2c33473bd791d85eb351d555 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:04:40 +0400 Subject: [PATCH 02/16] Add failing tests for an explicit engine variable module scope A post-export reform's rule modules must be removed when its consumer moves on, which spans several calls. A suspended temporary_engine_variable_modules generator would run its cleanup whenever the garbage collector closed it and could remove a later scope's modules. These tests expect an explicit scope that does nothing when dropped unclosed, and one open reform per post-export scorer. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_scoring.py | 61 +++++++++++++++++++ .../us/test_us_release_slice_memory.py | 44 +++++++++++++ .../us/test_us_post_export_scoring.py | 18 ++++-- 3 files changed, 118 insertions(+), 5 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index 69b621fa22..cb5deb1c68 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py @@ -2036,3 +2036,64 @@ def simulate_for(name, consumer): assert demographics == reference_demographics assert len(log.systems) > 43 assert _stand_in_rule_modules_left(stand_in_rule_modules) == [] + + +def test_an_abandoned_scorers_reform_never_removes_a_later_scorers_modules( + builder, fake_reforms, stand_in_rule_modules, tmp_path +) -> None: + """A scorer dropped with a reform open leaves its modules, harmlessly, and + the garbage collector never makes it remove a later reform's modules.""" + abandoned_log = _EngineLog() + abandoned = _scorer( + builder, + _nested_frame(), + abandoned_log, + 3, + tmp_path / "abandoned", + variables_dir=stand_in_rule_modules, + ) + abandoned.open_consumer("fixture", ()).simulate(_FakeReform("dropped")).calculate( + "income_tax", builder.PERIOD + ) + del abandoned + log = _EngineLog() + scorer = _scorer( + builder, + _nested_frame(), + log, + 3, + tmp_path / "later", + variables_dir=stand_in_rule_modules, + ) + consumer = scorer.open_consumer("fixture", ()) + consumer.simulate(_FakeReform("kept")).calculate("income_tax", builder.PERIOD) + later_module = _rule_module_name(log.systems[0]) + gc.collect() + assert later_module in sys.modules + + scorer.finish_consumer(consumer) + assert later_module not in sys.modules + + +def test_a_scorer_keeps_one_reform_open_across_its_consumers( + builder, fake_reforms, stand_in_rule_modules, tmp_path +) -> None: + log = _EngineLog() + scorer = _scorer( + builder, _nested_frame(), log, 3, tmp_path, variables_dir=stand_in_rule_modules + ) + first_consumer = scorer.open_consumer("first", ()) + first_consumer.simulate(_FakeReform("first")).calculate( + "income_tax", builder.PERIOD + ) + second_consumer = scorer.open_consumer("second", ()) + second_consumer.simulate(_FakeReform("second")).calculate( + "income_tax", builder.PERIOD + ) + + assert _rule_module_name(log.systems[0]) not in sys.modules + assert _rule_module_name(log.systems[1]) in sys.modules + scorer.finish_consumer(first_consumer) + assert _rule_module_name(log.systems[1]) in sys.modules + scorer.finish_consumer(second_consumer) + assert _stand_in_rule_modules_left(stand_in_rule_modules) == [] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py index b51bf125db..dcffc78123 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py @@ -12,6 +12,7 @@ import pytest from microcosm.build.us_runtime.engine_lifecycle import ( + EngineVariableModuleScope, temporary_engine_variable_modules, ) from test_support.microcosm_build.us_release_head_to_head_scorer import ( @@ -214,3 +215,46 @@ def test_temporary_variable_modules_clean_up_first_lazy_engine_import( assert all(reference() is None for reference in transient_refs) finally: sys.modules.pop(transient_name, None) + + +def test_an_explicit_scope_spans_calls_and_closes_once(tmp_path) -> None: + """The explicit scope removes what was registered between open and close.""" + variables_dir = tmp_path / "variables" + name = "7470001_-123_income_tax" + try: + scope = EngineVariableModuleScope(variables_dir).open() + retained = _register_variable_module(name, variables_dir) + assert sys.modules[name].IncomeTax().formula() == 42.0 + scope.close() + gc.collect() + assert name not in sys.modules + assert all(reference() is None for reference in retained) + scope.close() # Closing again does nothing. + finally: + sys.modules.pop(name, None) + + +def test_an_unclosed_scope_removes_nothing_when_it_is_collected(tmp_path) -> None: + """A scope left open and dropped never removes a later scope's modules. + + A suspended ``temporary_engine_variable_modules`` generator would run its + cleanup whenever the garbage collector closed it, removing modules that a + later scope registered and still uses. + """ + variables_dir = tmp_path / "variables" + abandoned_name = "7480001_-123_income_tax" + later_name = "7480002_-123_income_tax" + try: + abandoned = EngineVariableModuleScope(variables_dir).open() + _register_variable_module(abandoned_name, variables_dir) + del abandoned + later = EngineVariableModuleScope(variables_dir).open() + _register_variable_module(later_name, variables_dir) + gc.collect() + assert later_name in sys.modules + assert abandoned_name in sys.modules + later.close() + assert later_name not in sys.modules + finally: + sys.modules.pop(abandoned_name, None) + sys.modules.pop(later_name, None) diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py index d193a1530a..d4e2154ee7 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py @@ -305,8 +305,6 @@ def test_reform_passes_leave_no_rule_modules_behind_and_score_the_same( reform pass on this fixture). The scorer removes them once the consumer opens the next reform or finishes, and the scored arrays are byte-identical to scoring without the removal.""" - import contextlib - import policyengine_us from microcosm.build.us_runtime.reform_coverage_smoke import _build_reform @@ -348,9 +346,19 @@ def score(): before, after, released = score() assert after == before - monkeypatch.setattr( - builder, "temporary_engine_variable_modules", contextlib.nullcontext - ) + class KeepEveryModule: + """A scope that removes nothing: post-export scoring before the fix.""" + + def __init__(self, variables_dir=None) -> None: + pass + + def open(self): + return self + + def close(self) -> None: + pass + + monkeypatch.setattr(builder, "EngineVariableModuleScope", KeepEveryModule) kept_before, kept_after, kept = score() assert len(kept_after - kept_before) >= 2 * 1_000 assert released == kept From b8cb4a664516bfcbef0b037942187b9e4bce9822 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:10:44 +0400 Subject: [PATCH 03/16] Add a shared worker pool; move the head-to-head scorer onto it; free post-export rule modules microcosm.build.worker_pool runs units of household-batched work in spawned worker processes it starts and tracks itself: the initializer's state is sent once per worker, workers can be replaced after K units with never more than the worker count alive, a parent thread stops a worker over its memory cap (resident plus compressed or swapped-out pages), a unit whose worker dies, goes over the cap or raises MemoryError runs again in a fresh worker up to max_attempts, results come back in unit order within a bounded window, and optional environment variables are set in each worker as it starts. The worker_pool_identity test helper requires byte-identical results at 1 and N workers. The head-to-head scorer's --workers slices run on the pool, so its ProcessPoolExecutor code and its Python-version refusal of --worker-max-slices go away. Post-export scoring opens an EngineVariableModuleScope (the explicit form of temporary_engine_variable_modules) when it builds a reform's system, and closes it when the scorer hands out its next reform, the consumer finishes or the scorer closes, removing the ~6,000 variable modules policyengine-core registers per system and never removes. Co-Authored-By: Claude Opus 5.5 --- .../us-head-to-head-shared-pool.changed.md | 1 + .../us-post-export-rule-modules.fixed.md | 1 + changelog.d/us-shared-worker-pool.added.md | 1 + .../build/us_runtime/engine_lifecycle.py | 143 ++- .../src/microcosm/build/worker_pool.py | 906 ++++++++++++++++++ .../microcosm_build/worker_pool_identity.py | 204 ++++ tools/build_us_fiscal_refresh_release.py | 73 +- tools/score_us_release_head_to_head.py | 167 +--- 8 files changed, 1320 insertions(+), 176 deletions(-) create mode 100644 changelog.d/us-head-to-head-shared-pool.changed.md create mode 100644 changelog.d/us-post-export-rule-modules.fixed.md create mode 100644 changelog.d/us-shared-worker-pool.added.md create mode 100644 packages/microcosm-build/src/microcosm/build/worker_pool.py create mode 100644 test_support/microcosm_build/worker_pool_identity.py diff --git a/changelog.d/us-head-to-head-shared-pool.changed.md b/changelog.d/us-head-to-head-shared-pool.changed.md new file mode 100644 index 0000000000..31f76a9a0f --- /dev/null +++ b/changelog.d/us-head-to-head-shared-pool.changed.md @@ -0,0 +1 @@ +The US head-to-head scorer (`tools/score_us_release_head_to_head.py`) runs its `--workers` slices on the shared worker pool instead of `ProcessPoolExecutor`, so the repository has one worker-pool implementation. `--worker-max-slices` now works on every supported Python: the scorer no longer refuses it on interpreters where `ProcessPoolExecutor` could hang replacing a worker. A slice whose worker dies or runs out of memory runs once more in a fresh worker before the run stops with the slice's label. Scorecards are unchanged. diff --git a/changelog.d/us-post-export-rule-modules.fixed.md b/changelog.d/us-post-export-rule-modules.fixed.md new file mode 100644 index 0000000000..0178762886 --- /dev/null +++ b/changelog.d/us-post-export-rule-modules.fixed.md @@ -0,0 +1 @@ +US post-export scoring removes the variable modules that each reform's tax-benefit system build adds to `sys.modules`, which policyengine-core never removes, once the reform's consumer opens its next reform or finishes, or the scorer closes. On the eight-household guard fixture the modules held about 0.04 GiB per reform pass, about 4 GiB over a full build's 98 reform passes (estimate). `EngineVariableModuleScope` in `microcosm.build.us_runtime.engine_lifecycle` is the explicit open/close form of `temporary_engine_variable_modules` that this uses; a scope left unclosed does nothing when garbage-collected. Scored values are unchanged. diff --git a/changelog.d/us-shared-worker-pool.added.md b/changelog.d/us-shared-worker-pool.added.md new file mode 100644 index 0000000000..4ad82813e9 --- /dev/null +++ b/changelog.d/us-shared-worker-pool.added.md @@ -0,0 +1 @@ +`microcosm.build.worker_pool` runs independent units of household-batched work, such as policyengine-us passes over household batches, in spawned worker processes and returns their results in unit order, so callers join them in the order one process would use and get byte-identical outputs. Each worker runs the caller's initializer once, so start-up data such as a frame crosses once per worker; a worker can be replaced after a set number of units; a thread in the parent stops a worker whose memory footprint (resident plus compressed or swapped-out pages) goes over a per-worker cap; a unit whose worker dies, goes over the cap or raises `MemoryError` runs again in a fresh worker, up to a set number of attempts; and optional environment variables are set in each worker as it starts, before it imports anything. The caller sets the worker count and the cap. `test_support/microcosm_build/worker_pool_identity.py` adds a test helper that runs a pooled computation at several worker counts and requires byte-identical results. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py b/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py index a5b7727470..0197b84c04 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py @@ -36,7 +36,95 @@ from types import ModuleType from typing import Any -__all__ = ["release_engine_simulation", "temporary_engine_variable_modules"] +__all__ = [ + "EngineVariableModuleScope", + "release_engine_simulation", + "temporary_engine_variable_modules", +] + + +def _loaded_variables_dir() -> str | Path | None: + engine = sys.modules.get("policyengine_us") + system_cls = getattr(engine, "CountryTaxBenefitSystem", None) + return getattr(system_cls, "variables_dir", None) + + +def _registrations(directory: Path | None) -> dict[str, ModuleType]: + """Core's per-system variable-module registrations under ``directory``.""" + found = {} + for name, module in tuple(sys.modules.items()): + parts = name.split("_", 2) + if ( + len(parts) != 3 + or not parts[0].isdigit() + or not parts[1].removeprefix("-").isdigit() + or not isinstance(module, ModuleType) + ): + continue + filename = getattr(module, "__file__", None) + if not isinstance(filename, str): + continue + path = Path(filename).absolute() + if parts[2] == path.stem and ( + directory is None or path.is_relative_to(directory) + ): + found[name] = module + return found + + +class EngineVariableModuleScope: + """Remove Core's variable-module registrations made between open and close. + + The explicit form of :func:`temporary_engine_variable_modules`, for a scope + that spans several calls: post-export scoring builds a reform's system on + the reform's first key and closes the scope when its consumer moves on. A + suspended context manager would run its cleanup whenever the garbage + collector closed it, at an arbitrary later moment, and remove modules a + later scope registered and still uses. A scope left unclosed here does + nothing when collected; its modules simply stay registered, as they would + without it. ``close`` does nothing the second time. + """ + + def __init__(self, variables_dir: str | Path | None = None) -> None: + self._variables_dir = variables_dir + self._previous: dict[str, ModuleType] | None = None + self._closed = False + + def open(self) -> EngineVariableModuleScope: + """Take the snapshot of registrations that ``close`` keeps.""" + if self._previous is not None or self._closed: + raise RuntimeError("An engine variable module scope opens only once.") + initial_directory = self._variables_dir or _loaded_variables_dir() + directory = ( + None if initial_directory is None else Path(initial_directory).absolute() + ) + self._previous = _registrations(directory) + return self + + def close(self) -> None: + """Remove the registrations made since ``open``, except the shared system's.""" + previous, self._previous = self._previous, None + if self._closed or previous is None: + self._closed = True + return + self._closed = True + final_directory = self._variables_dir or _loaded_variables_dir() + if final_directory is None: + return + # The first slice may import the engine lazily. Its newly built shared + # default system remains live for every later simulation; retain those + # registrations along with the entry snapshot. + engine = sys.modules.get("policyengine_us") + simulation_cls = getattr(engine, "Microsimulation", None) + shared_system = getattr( + simulation_cls, "default_tax_benefit_system_instance", None + ) + shared_prefix = f"{id(shared_system)}_" + for name in _registrations(Path(final_directory).absolute()): + if name in previous: + sys.modules[name] = previous[name] + elif shared_system is None or not name.startswith(shared_prefix): + sys.modules.pop(name, None) @contextmanager @@ -59,60 +147,15 @@ def temporary_engine_variable_modules( The default discovers an already imported US engine, so importing this helper remains engine-free. An explicit directory supports stand-ins. - Use only around a completed slice whose engine objects do not escape. + Use only around a completed slice whose engine objects do not escape; for + a scope that spans calls, use :class:`EngineVariableModuleScope`. """ - def loaded_variables_dir(): - engine = sys.modules.get("policyengine_us") - system_cls = getattr(engine, "CountryTaxBenefitSystem", None) - return getattr(system_cls, "variables_dir", None) - - initial_directory = variables_dir or loaded_variables_dir() - directory = ( - None if initial_directory is None else Path(initial_directory).absolute() - ) - - def registrations(directory: Path | None) -> dict[str, ModuleType]: - found = {} - for name, module in tuple(sys.modules.items()): - parts = name.split("_", 2) - if ( - len(parts) != 3 - or not parts[0].isdigit() - or not parts[1].removeprefix("-").isdigit() - or not isinstance(module, ModuleType) - ): - continue - filename = getattr(module, "__file__", None) - if not isinstance(filename, str): - continue - path = Path(filename).absolute() - if parts[2] == path.stem and ( - directory is None or path.is_relative_to(directory) - ): - found[name] = module - return found - - previous = registrations(directory) + scope = EngineVariableModuleScope(variables_dir).open() try: yield finally: - final_directory = variables_dir or loaded_variables_dir() - if final_directory is not None: - # The first slice may import the engine lazily. Its newly built - # shared default system remains live for every later simulation; - # retain those registrations along with the entry snapshot. - engine = sys.modules.get("policyengine_us") - simulation_cls = getattr(engine, "Microsimulation", None) - shared_system = getattr( - simulation_cls, "default_tax_benefit_system_instance", None - ) - shared_prefix = f"{id(shared_system)}_" - for name in registrations(Path(final_directory).absolute()): - if name in previous: - sys.modules[name] = previous[name] - elif shared_system is None or not name.startswith(shared_prefix): - del sys.modules[name] + scope.close() #: Instance attributes whose only post-mortem job is to keep big object diff --git a/packages/microcosm-build/src/microcosm/build/worker_pool.py b/packages/microcosm-build/src/microcosm/build/worker_pool.py new file mode 100644 index 0000000000..bfcd847975 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/worker_pool.py @@ -0,0 +1,906 @@ +"""A pool of spawned worker processes for household-batched engine work. + +The US build runs policyengine-us over its households one batch at a time. +This pool runs those batches, or any other independent units of work, in +separate worker processes and hands their results back in unit order, so a +caller can join them (concatenate arrays, add totals) in exactly the order a +single process would use and get byte-identical outputs. + +How it works: + +* **Spawned workers.** Each worker is a fresh Python process started with the + ``spawn`` start method. Engine objects never cross between processes; each + worker builds its own. Workers must be processes, not threads, because every + policyengine-us construction sets a back-reference on the engine's shared + default rules (``us_runtime/engine_lifecycle.py``). +* **Start-up data sent once per worker.** ``initializer(*initargs)`` runs once + in each worker, and whatever it returns is passed to every unit that worker + runs as ``unit_function(state, unit)``. Spawn pickles ``initargs`` once per + worker start, so a frame passed there crosses once per worker, not once per + unit. A unit itself should be small (indices, a request descriptor). +* **Worker replacement.** With ``max_units_per_worker``, a worker is stopped + after that many units and a fresh one takes its place, so memory that an + engine leaves behind does not build up. The pool starts the replacement only + after the old worker has exited, so no more than ``workers`` processes are + ever alive at once. The pool manages its own processes, so worker + replacement has none of the interpreter restrictions of + ``ProcessPoolExecutor(max_tasks_per_child=...)``. +* **A memory cap per worker.** With ``memory_cap_bytes``, a thread in the + parent reads each worker's memory every ``memory_poll_seconds`` and stops a + worker that goes over the cap. The reading is the process's footprint: its + resident memory plus pages the operating system has compressed (macOS) or + swapped out (Linux), from :func:`process_memory_bytes`. +* **Running a failed unit again.** A unit whose worker exits before returning + its result (a crash, the operating system killing it, the memory cap) or + whose unit function raises ``MemoryError`` runs again in a fresh worker, up + to ``max_attempts`` attempts in all. Any other exception from the unit + function stops the run at once: the same inputs would raise it again. +* **Results in unit order.** :meth:`WorkerPool.map` yields results in the + order of its units, whatever order the workers finish in. At most + ``max_units_ahead`` units, counted from the oldest result not yet handed + back, are running or waiting with a finished result, which bounds the + results the parent holds. +* **A worker environment.** ``worker_environment`` sets environment variables + in each worker as it starts, before the worker imports anything, so a caller + can, for example, give workers different numeric thread counts from the + parent's. The pool chooses no values; without it, workers inherit the + parent's environment. + +The pool decides nothing about sizing: the caller sets the number of workers +and the memory cap. A unit function must not start ``multiprocessing`` child +processes, because the workers are daemonic. +""" + +from __future__ import annotations + +import ctypes +import heapq +import math +import multiprocessing +import os +import pickle +import signal +import sys +import threading +import time +import traceback +import weakref +from collections import deque +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +from multiprocessing.connection import wait as wait_for_any +from multiprocessing.reduction import ForkingPickler + +__all__ = [ + "FailedAttempt", + "WorkerPool", + "WorkerPoolError", + "WorkerPoolReport", + "WorkerPoolSettings", + "WorkerPoolUnitError", + "process_memory_bytes", +] + +#: The longest the parent waits for a worker message before it checks the +#: workers again. +_WAIT_SECONDS = 0.5 +#: How long :meth:`WorkerPool.close` waits for a stopped worker to exit before +#: killing it. +_SHUTDOWN_SECONDS = 10.0 + +# Environment changes for a worker start are made in this process's own +# environment, so two pools starting workers at once must take turns. +_ENVIRONMENT_LOCK = threading.Lock() + + +def _require_positive_integer(name: str, value: object) -> None: + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer; got {value!r}.") + + +@dataclass(frozen=True) +class WorkerPoolSettings: + """How many workers to run and the limits each one runs under. + + Attributes: + workers: Worker processes alive at most at any time. + memory_cap_bytes: Stop a worker whose memory footprint goes over this, + and run its unit again. ``None`` sets no cap. + max_units_per_worker: Replace a worker after this many units. ``None`` + keeps each worker for the whole run. + max_attempts: Attempts in all for a unit whose worker fails (see the + module docstring); the run stops when a unit fails this many times. + max_units_ahead: Units, counted from the oldest result not yet handed + back, that may be running or waiting with a finished result. + ``None`` means twice ``workers``. + memory_poll_seconds: Seconds between readings of each worker's memory. + worker_environment: Environment variables set in each worker as it + starts. ``None`` leaves the parent's environment unchanged. + """ + + workers: int + memory_cap_bytes: int | None = None + max_units_per_worker: int | None = None + max_attempts: int = 2 + max_units_ahead: int | None = None + memory_poll_seconds: float = 0.5 + worker_environment: Mapping[str, str] | None = None + + def __post_init__(self) -> None: + _require_positive_integer("workers", self.workers) + for name in ("memory_cap_bytes", "max_units_per_worker", "max_units_ahead"): + value = getattr(self, name) + if value is not None: + _require_positive_integer(name, value) + _require_positive_integer("max_attempts", self.max_attempts) + seconds = self.memory_poll_seconds + if ( + isinstance(seconds, bool) + or not isinstance(seconds, int | float) + or not math.isfinite(seconds) + or seconds <= 0 + ): + raise ValueError( + f"memory_poll_seconds must be a positive number; got {seconds!r}." + ) + if self.worker_environment is not None: + environment = dict(self.worker_environment) + for key, value in environment.items(): + if ( + not isinstance(key, str) + or not key + or "=" in key + or "\0" in key + or not isinstance(value, str) + or "\0" in value + ): + raise ValueError( + "worker_environment must map variable names to string " + f"values; got {key!r}: {value!r}." + ) + object.__setattr__(self, "worker_environment", environment) + + @property + def units_ahead(self) -> int: + """The window of units in flight that ``max_units_ahead`` sets.""" + if self.max_units_ahead is None: + return 2 * self.workers + return self.max_units_ahead + + +@dataclass(frozen=True) +class FailedAttempt: + """One attempt at a unit that ended without a result.""" + + unit_index: int + label: str + attempt: int + worker_pid: int | None + cause: str + + +@dataclass(frozen=True) +class WorkerPoolReport: + """What a pool has done so far. + + Attributes: + worker_starts: Worker processes started, replacements included. + units_completed: Units whose result came back. + failed_attempts: Every attempt at a unit that ended without a result, + in the order the parent saw them. + max_live_workers: The most worker processes alive at once. + peak_worker_memory_bytes: The highest memory footprint read from any + worker, or ``None`` before the first reading. + """ + + worker_starts: int + units_completed: int + failed_attempts: tuple[FailedAttempt, ...] + max_live_workers: int + peak_worker_memory_bytes: int | None + + +class WorkerPoolError(RuntimeError): + """The pool could not run its units.""" + + +class WorkerPoolUnitError(WorkerPoolError): + """A unit failed, so the run stopped. + + Attributes: + unit_index: The unit's position in the sequence given to ``map``. + label: The unit's label, from ``describe_unit``. + causes: Why each attempt at the unit ended without a result. + """ + + def __init__( + self, message: str, *, unit_index: int, label: str, causes: Sequence[str] + ) -> None: + super().__init__(message) + self.unit_index = unit_index + self.label = label + self.causes = tuple(causes) + + +class _RemoteTracebackError(Exception): + """The formatted traceback of an exception raised in a worker.""" + + def __init__(self, text: str) -> None: + super().__init__(text) + self.text = text + + def __str__(self) -> str: + return self.text + + +# --------------------------------------------------------------------------- +# Reading a process's memory +# --------------------------------------------------------------------------- + + +class _RusageInfoV0(ctypes.Structure): + # struct rusage_info_v0, on macOS. + _fields_ = [ + ("ri_uuid", ctypes.c_uint8 * 16), + ("ri_user_time", ctypes.c_uint64), + ("ri_system_time", ctypes.c_uint64), + ("ri_pkg_idle_wkups", ctypes.c_uint64), + ("ri_interrupt_wkups", ctypes.c_uint64), + ("ri_pageins", ctypes.c_uint64), + ("ri_wired_size", ctypes.c_uint64), + ("ri_resident_size", ctypes.c_uint64), + ("ri_phys_footprint", ctypes.c_uint64), + ("ri_proc_start_abstime", ctypes.c_uint64), + ("ri_proc_exit_abstime", ctypes.c_uint64), + ] + + +_RUSAGE_INFO_V0 = 0 +_LIBPROC: ctypes.CDLL | None = None + + +def _darwin_footprint(pid: int) -> int | None: + global _LIBPROC + if _LIBPROC is None: + _LIBPROC = ctypes.CDLL("/usr/lib/libproc.dylib", use_errno=True) + _LIBPROC.proc_pid_rusage.argtypes = [ + ctypes.c_int, + ctypes.c_int, + ctypes.POINTER(_RusageInfoV0), + ] + _LIBPROC.proc_pid_rusage.restype = ctypes.c_int + info = _RusageInfoV0() + if _LIBPROC.proc_pid_rusage(pid, _RUSAGE_INFO_V0, ctypes.byref(info)) != 0: + return None + return int(info.ri_phys_footprint) + + +def _linux_footprint(pid: int) -> int | None: + try: + with open(f"/proc/{pid}/status", encoding="ascii", errors="replace") as status: + lines = status.read().splitlines() + except OSError: + return None + kibibytes = {} + for line in lines: + name, _, rest = line.partition(":") + if name in ("VmRSS", "VmSwap"): + kibibytes[name] = int(rest.split()[0]) + if "VmRSS" not in kibibytes: + # A process that has exited but not been reaped reports no memory. + return None + return (kibibytes["VmRSS"] + kibibytes.get("VmSwap", 0)) * 1024 + + +def _memory_reading_supported() -> bool: + return sys.platform == "darwin" or sys.platform.startswith("linux") + + +def process_memory_bytes(pid: int) -> int | None: + """A process's memory footprint in bytes, or ``None`` if it can't be read. + + This is the memory the process holds whether or not it is in RAM: on Linux + its resident memory plus its swapped-out pages (``VmRSS + VmSwap`` from + ``/proc//status``); on macOS its physical footprint + (``proc_pid_rusage``'s ``ri_phys_footprint``), which counts compressed + pages. Resident memory alone falls when the system is short of memory and + compresses or swaps pages out, so it would let a worker pass its cap. + Returns ``None`` for a process that has exited, one this process may not + read, and on other platforms. + """ + if sys.platform == "darwin": + return _darwin_footprint(pid) + if sys.platform.startswith("linux"): + return _linux_footprint(pid) + return None + + +# --------------------------------------------------------------------------- +# The worker process +# --------------------------------------------------------------------------- + + +def _summary(error: BaseException) -> str: + return "".join(traceback.format_exception_only(error)).strip() + + +def _formatted(error: BaseException) -> str: + return "".join(traceback.format_exception(error)) + + +def _send_quietly(connection, message) -> bool: + """Send ``message``; False if the parent has gone.""" + try: + connection.send(message) + except OSError: + return False + return True + + +def _worker_main(connection, initializer, initargs, unit_function) -> None: + """Run in each worker: start up once, then run units until told to stop.""" + try: + state = None if initializer is None else initializer(*initargs) + except Exception as error: + _send_quietly(connection, ("start_error", _summary(error), _formatted(error))) + return + if not _send_quietly(connection, ("ready", os.getpid())): + return + while True: + try: + message = connection.recv() + except (EOFError, OSError): + return + if message is None: + return + index, unit = message + try: + result = unit_function(state, unit) + except MemoryError as error: + # The worker's memory may be in a bad state: report, then exit so + # a fresh worker runs the unit again. + _send_quietly( + connection, ("memory_error", index, _summary(error), _formatted(error)) + ) + return + except Exception as error: + if not _send_quietly( + connection, ("error", index, _summary(error), _formatted(error)) + ): + return + continue + try: + connection.send(("result", index, result)) + except OSError: + return + except Exception as error: + summary = f"its result could not be sent to the parent: {_summary(error)}" + if not _send_quietly( + connection, ("error", index, summary, _formatted(error)) + ): + return + del message, unit, result + + +# --------------------------------------------------------------------------- +# The parent's side +# --------------------------------------------------------------------------- + + +@dataclass(eq=False) +class _Worker: + process: multiprocessing.process.BaseProcess + connection: object + ready: bool = False + unit_index: int | None = None + units_run: int = 0 + retiring: bool = False + connection_lost: bool = False + + @property + def pid(self) -> int | None: + return self.process.pid + + +@dataclass(eq=False) +class _Run: + """One ``map``'s units and what has happened to each.""" + + units: list[object] + attempts: list[int] + causes: list[list[str]] + results: dict[int, object] + retries: list[int] + undispatched: deque[int] + start_failures: list[str] + + +@contextmanager +def _environment_for_start(environment: Mapping[str, str] | None) -> Iterator[None]: + """Hold ``environment`` in this process's environment while a worker starts. + + A spawned worker gets a copy of the parent's environment when its + interpreter starts, before it imports the parent's main module or anything + else, so this is the only point at which every library in the worker sees + the values. They are restored as soon as the worker has started. + """ + if not environment: + yield + return + with _ENVIRONMENT_LOCK: + previous = {name: os.environ.get(name) for name in environment} + os.environ.update(environment) + try: + yield + finally: + for name, value in previous.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + + +def _require_importable(name: str, function: Callable) -> None: + if not callable(function): + raise TypeError(f"{name} must be callable; got {function!r}.") + try: + pickle.dumps(function) + except (pickle.PicklingError, AttributeError, TypeError) as error: + raise TypeError( + f"{name} must be importable by name in a spawned worker, such as a " + f"module-level function; got {function!r} ({error})." + ) from None + + +def _exit_cause(exitcode: int | None) -> str: + if exitcode is None: + return "the worker's connection to the parent closed" + if exitcode < 0: + try: + name = signal.Signals(-exitcode).name + except ValueError: + name = f"signal {-exitcode}" + return f"the worker was killed by {name}" + if exitcode == 0: + return "the worker exited without returning a result" + return f"the worker exited with code {exitcode}" + + +def _gibibytes(count: int) -> str: + return f"{count / 1024**3:.2f} GiB" + + +def _stop_processes(workers: list[_Worker]) -> None: + """Kill any workers still alive; run when a pool is collected or at exit.""" + for worker in list(workers): + try: + if worker.process.exitcode is None: + worker.process.kill() + worker.process.join(_SHUTDOWN_SECONDS) + except (OSError, ValueError, AssertionError): + pass + + +class WorkerPool: + """Spawned worker processes that run units and return results in order. + + Use it as a context manager, so its workers stop when the block ends:: + + with WorkerPool( + WorkerPoolSettings(workers=4, max_units_per_worker=2), + initializer=load_batches, + initargs=(h5_path,), + unit_function=score_request, + ) as pool: + for result in pool.map(requests): + ... + + ``initializer`` and ``unit_function`` must be importable by name in a + fresh interpreter (module-level functions). ``describe_unit(index, unit)`` + labels a unit in errors; it runs only in the parent. ``map`` may be called + again once the previous ``map`` has finished, and reuses the live workers. + A ``map`` that does not run to the end, because a unit failed or the + caller stopped iterating, closes the pool. + """ + + def __init__( + self, + settings: WorkerPoolSettings, + *, + unit_function: Callable[[object, object], object], + initializer: Callable[..., object] | None = None, + initargs: Sequence[object] = (), + describe_unit: Callable[[int, object], str] | None = None, + ) -> None: + if not isinstance(settings, WorkerPoolSettings): + raise TypeError("settings must be a WorkerPoolSettings.") + _require_importable("unit_function", unit_function) + if initializer is not None: + _require_importable("initializer", initializer) + if settings.memory_cap_bytes is not None and not _memory_reading_supported(): + raise ValueError( + f"memory_cap_bytes needs worker memory readings, which " + f"{sys.platform} does not support here." + ) + self._settings = settings + self._unit_function = unit_function + self._initializer = initializer + self._initargs = tuple(initargs) + self._describe_unit = describe_unit + self._context = multiprocessing.get_context("spawn") + # Every reap, start and kill of a worker process happens under this + # lock, so the memory thread never signals a process the parent has + # already reaped. + self._lock = threading.Lock() + self._workers: list[_Worker] = [] + self._cap_overruns: dict[int, int] = {} + self._closed = False + self._mapping = False + self._worker_starts = 0 + self._units_completed = 0 + self._failed_attempts: list[FailedAttempt] = [] + self._max_live_workers = 0 + self._peak_memory: int | None = None + self._monitor: threading.Thread | None = None + self._monitor_stop = threading.Event() + self._finalizer = weakref.finalize(self, _stop_processes, self._workers) + + # -- public ------------------------------------------------------------ + + def __enter__(self) -> WorkerPool: + return self + + def __exit__(self, *exc_info) -> None: + self.close() + + def report(self) -> WorkerPoolReport: + with self._lock: + return WorkerPoolReport( + worker_starts=self._worker_starts, + units_completed=self._units_completed, + failed_attempts=tuple(self._failed_attempts), + max_live_workers=self._max_live_workers, + peak_worker_memory_bytes=self._peak_memory, + ) + + def map(self, units: Iterable[object]) -> Iterator[object]: + """Run ``unit_function(state, unit)`` for each unit; yield results in order.""" + if self._closed: + raise WorkerPoolError("The worker pool is closed.") + if self._mapping: + raise WorkerPoolError("The worker pool is already running a map.") + self._mapping = True + finished = False + try: + yield from self._run(list(units)) + finished = True + finally: + self._mapping = False + if not finished: + self.close() + + def close(self) -> None: + """Stop every worker: idle ones are told to exit, busy ones are killed.""" + if self._closed: + return + self._closed = True + self._monitor_stop.set() + if self._monitor is not None: + self._monitor.join() + with self._lock: + workers = list(self._workers) + for worker in workers: + if ( + worker.ready + and worker.unit_index is None + and not worker.connection_lost + ): + if not worker.retiring: + self._send_stop(worker) + else: + with self._lock: + worker.process.kill() + deadline = time.monotonic() + _SHUTDOWN_SECONDS + for worker in workers: + with self._lock: + worker.process.join(max(0.0, deadline - time.monotonic())) + if worker.process.exitcode is None: + worker.process.kill() + worker.process.join(_SHUTDOWN_SECONDS) + self._forget(worker) + + # -- running units ------------------------------------------------------ + + def _label(self, units: Sequence[object], index: int) -> str: + if self._describe_unit is not None: + return str(self._describe_unit(index, units[index])) + return f"unit {index + 1}/{len(units)}" + + def _run(self, units: list[object]) -> Iterator[object]: + count = len(units) + if count == 0: + return + settings = self._settings + self._start_monitor() + run = _Run( + units=units, + attempts=[0] * count, + causes=[[] for _ in range(count)], + results={}, + retries=[], + undispatched=deque(range(count)), + start_failures=[], + ) + next_index = 0 + while next_index < count: + while next_index in run.results: + result = run.results.pop(next_index) + next_index += 1 + yield result + del result + if next_index >= count: + break + window_end = next_index + settings.units_ahead + waiting = len(run.retries) + sum( + 1 for index in run.undispatched if index < window_end + ) + self._start_workers(waiting) + for worker in list(self._workers): + if ( + not worker.ready + or worker.retiring + or worker.connection_lost + or worker.unit_index is not None + ): + continue + if run.retries: + index = heapq.heappop(run.retries) + elif run.undispatched and run.undispatched[0] < window_end: + index = run.undispatched.popleft() + else: + break + if not self._send_unit(worker, index, run): + heapq.heappush(run.retries, index) + self._wait_and_handle(run) + + def _unit_failed(self, run: _Run, index: int, pid: int | None, cause: str) -> None: + """Record a failed attempt; queue the unit again or stop the run.""" + label = self._label(run.units, index) + run.causes[index].append(cause) + with self._lock: + self._failed_attempts.append( + FailedAttempt(index, label, run.attempts[index], pid, cause) + ) + if run.attempts[index] >= self._settings.max_attempts: + detail = "; ".join( + f"attempt {number}: {text}" + for number, text in enumerate(run.causes[index], start=1) + ) + raise WorkerPoolUnitError( + f"{label} failed on all {run.attempts[index]} attempts: {detail}", + unit_index=index, + label=label, + causes=run.causes[index], + ) + heapq.heappush(run.retries, index) + + def _start_workers(self, waiting: int) -> None: + available = sum( + 1 + for worker in self._workers + if not worker.retiring + and not worker.connection_lost + and worker.unit_index is None + ) + while available < waiting and len(self._workers) < self._settings.workers: + self._start_worker() + available += 1 + + def _start_worker(self) -> None: + parent_end, child_end = self._context.Pipe(duplex=True) + process = self._context.Process( + target=_worker_main, + args=(child_end, self._initializer, self._initargs, self._unit_function), + name=f"worker-pool-{self._worker_starts + 1}", + daemon=True, + ) + try: + with self._lock, _environment_for_start(self._settings.worker_environment): + process.start() + self._workers.append(_Worker(process=process, connection=parent_end)) + self._worker_starts += 1 + self._max_live_workers = max(self._max_live_workers, len(self._workers)) + except Exception as error: + parent_end.close() + raise WorkerPoolError(f"A worker could not be started: {error}") from error + finally: + child_end.close() + + def _send_unit(self, worker: _Worker, index: int, run: _Run) -> bool: + """Send a unit to an idle worker; False if the worker has gone.""" + try: + payload = ForkingPickler.dumps((index, run.units[index])) + except Exception as error: + label = self._label(run.units, index) + cause = f"the unit could not be sent to a worker: {_summary(error)}" + raise WorkerPoolUnitError( + f"{label} failed: {cause}", + unit_index=index, + label=label, + causes=[cause], + ) from error + try: + worker.connection.send_bytes(payload) + except OSError: + worker.connection_lost = True + return False + run.attempts[index] += 1 + worker.unit_index = index + return True + + def _send_stop(self, worker: _Worker) -> None: + worker.retiring = True + try: + worker.connection.send(None) + except OSError: + worker.connection_lost = True + + def _wait_and_handle(self, run: _Run) -> None: + by_connection = { + worker.connection: worker + for worker in self._workers + if not worker.connection_lost + } + by_sentinel = {worker.process.sentinel: worker for worker in self._workers} + ready = wait_for_any([*by_connection, *by_sentinel], timeout=_WAIT_SECONDS) + touched: list[_Worker] = [] + for item in ready: + worker = by_connection.get(item) or by_sentinel.get(item) + if worker is not None and worker not in touched: + touched.append(worker) + for worker in touched: + self._drain(worker, run) + for worker in list(self._workers): + with self._lock: + exitcode = worker.process.exitcode + if exitcode is None: + continue + # Messages sent just before the worker exited come first. + self._drain(worker, run) + self._worker_exited(worker, exitcode, run) + + def _drain(self, worker: _Worker, run: _Run) -> None: + while not worker.connection_lost: + try: + if not worker.connection.poll(): + return + message = worker.connection.recv() + except (EOFError, OSError): + worker.connection_lost = True + return + self._handle(worker, message, run) + + def _handle(self, worker: _Worker, message: tuple, run: _Run) -> None: + kind = message[0] + if kind == "ready": + worker.ready = True + run.start_failures.clear() + elif kind == "start_error": + _, summary, text = message + raise WorkerPoolError( + f"A worker failed while starting: {summary}" + ) from _RemoteTracebackError(text) + elif kind == "result": + _, index, result = message + if index != worker.unit_index: + raise WorkerPoolError( + f"Worker {worker.pid} returned unit {index} while running " + f"unit {worker.unit_index}." + ) + run.results[index] = result + worker.unit_index = None + worker.units_run += 1 + with self._lock: + self._units_completed += 1 + limit = self._settings.max_units_per_worker + if limit is not None and worker.units_run >= limit: + self._send_stop(worker) + elif kind == "error": + _, index, summary, text = message + label = self._label(run.units, index) + run.causes[index].append(summary) + with self._lock: + self._failed_attempts.append( + FailedAttempt( + index, label, run.attempts[index], worker.pid, summary + ) + ) + raise WorkerPoolUnitError( + f"{label} failed in worker {worker.pid}: {summary}", + unit_index=index, + label=label, + causes=run.causes[index], + ) from _RemoteTracebackError(text) + elif kind == "memory_error": + _, index, summary, _text = message + worker.unit_index = None + worker.retiring = True + self._unit_failed(run, index, worker.pid, summary) + else: # pragma: no cover - the worker sends only the kinds above + raise WorkerPoolError(f"Worker {worker.pid} sent {kind!r}.") + + def _worker_exited(self, worker: _Worker, exitcode: int, run: _Run) -> None: + pid = worker.pid + with self._lock: + overrun = self._cap_overruns.pop(pid, None) + if overrun is not None: + cause = ( + f"the worker went over its memory cap of " + f"{_gibibytes(self._settings.memory_cap_bytes)} " + f"({_gibibytes(overrun)} read)" + ) + else: + cause = _exit_cause(exitcode) + index = worker.unit_index + was_starting = not worker.ready and not worker.retiring + self._forget(worker) + if index is not None: + self._unit_failed(run, index, pid, cause) + elif was_starting: + run.start_failures.append(cause) + if len(run.start_failures) >= self._settings.max_attempts: + raise WorkerPoolError( + f"Workers failed {len(run.start_failures)} times in a row " + f"while starting: {'; '.join(run.start_failures)}" + ) + + def _forget(self, worker: _Worker) -> None: + with self._lock: + if worker in self._workers: + self._workers.remove(worker) + try: + worker.process.join(0) + if worker.process.exitcode is not None: + worker.process.close() + except ValueError: + pass + try: + worker.connection.close() + except OSError: + pass + + # -- the memory thread -------------------------------------------------- + + def _start_monitor(self) -> None: + if self._monitor is not None or not _memory_reading_supported(): + return + self._monitor = threading.Thread( + target=self._watch_memory, name="worker-pool-memory", daemon=True + ) + self._monitor.start() + + def _watch_memory(self) -> None: + cap = self._settings.memory_cap_bytes + while not self._monitor_stop.wait(self._settings.memory_poll_seconds): + with self._lock: + targets = [(worker, worker.process.pid) for worker in self._workers] + for worker, pid in targets: + if pid is None: + continue + observed = process_memory_bytes(pid) + if observed is None: + continue + with self._lock: + # A worker still listed has not been reaped or closed, so + # its pid is still its own. + if ( + worker not in self._workers + or worker.process.exitcode is not None + ): + continue + if self._peak_memory is None or observed > self._peak_memory: + self._peak_memory = observed + if cap is not None and observed > cap: + self._cap_overruns.setdefault(pid, observed) + worker.process.kill() diff --git a/test_support/microcosm_build/worker_pool_identity.py b/test_support/microcosm_build/worker_pool_identity.py new file mode 100644 index 0000000000..6e7faba92b --- /dev/null +++ b/test_support/microcosm_build/worker_pool_identity.py @@ -0,0 +1,204 @@ +"""Check that a pooled computation gives byte-identical results at any worker count. + +A caller wraps its pooled computation in ``run(workers) -> result``, where the +result is whatever the caller joins from the pool (arrays, totals, payloads), +and calls :func:`assert_identical_across_worker_counts`. The helper runs it at +each worker count and compares canonical bytes, not values: + +* arrays by dtype, shape and raw bytes, so ``0.0`` and ``-0.0``, NaNs with + different bits, and ``int32`` and ``int64`` all count as different; +* floats by their IEEE 754 bits; +* mappings with their keys in order, since a payload written to JSON keeps + that order; +* tuples, lists, dataclasses and pandas objects by type and contents. + +A difference is reported by its place in the result, such as +``result['totals'][3]``. +""" + +from __future__ import annotations + +import dataclasses +import struct +from collections.abc import Callable, Mapping, Sequence + +import numpy as np + +__all__ = ["assert_identical_across_worker_counts", "canonical_result_bytes"] + + +def _framed(tag: bytes, payload: bytes) -> bytes: + return tag + struct.pack(">Q", len(payload)) + payload + + +def _type_name(value: object) -> bytes: + kind = type(value) + return f"{kind.__module__}.{kind.__qualname__}".encode() + + +def _pandas_bytes(value: object) -> bytes | None: + try: + import pandas as pd + except ImportError: # pragma: no cover - pandas is a workspace dependency + return None + if isinstance(value, pd.DataFrame): + parts = [ + canonical_result_bytes(list(value.columns)), + canonical_result_bytes(value.index), + ] + for column in value.columns: + parts.append(canonical_result_bytes(value[column])) + return _framed(b"P", _type_name(value) + b"".join(parts)) + if isinstance(value, pd.Series): + return _framed( + b"P", + _type_name(value) + + canonical_result_bytes(value.name) + + canonical_result_bytes(str(value.dtype)) + + canonical_result_bytes(value.index) + + canonical_result_bytes(np.asarray(value.to_numpy())), + ) + if isinstance(value, pd.Index): + return _framed( + b"P", + _type_name(value) + + canonical_result_bytes(str(value.dtype)) + + canonical_result_bytes(np.asarray(value.to_numpy())), + ) + return None + + +def canonical_result_bytes(value: object) -> bytes: + """Bytes that are equal exactly when two results are bit-for-bit the same. + + Raises: + TypeError: For a value of a type it has no encoding for. + """ + if value is None: + return b"N" + if isinstance(value, bool | np.bool_): + return b"B1" if value else b"B0" + if isinstance(value, np.ndarray): + header = f"{value.dtype.str}{value.shape}".encode() + if value.dtype.hasobject: + items = b"".join(canonical_result_bytes(item) for item in value.ravel()) + return _framed(b"O", _framed(b"h", header) + items) + return _framed( + b"A", _framed(b"h", header) + np.ascontiguousarray(value).tobytes() + ) + if isinstance(value, np.generic): + return _framed(b"S", value.dtype.str.encode() + b":" + value.tobytes()) + if isinstance(value, int): + return _framed(b"I", str(value).encode()) + if isinstance(value, float): + return _framed(b"F", struct.pack(">d", value)) + if isinstance(value, complex): + return _framed(b"C", struct.pack(">dd", value.real, value.imag)) + if isinstance(value, str): + return _framed(b"U", value.encode("utf-8", "surrogatepass")) + if isinstance(value, bytes | bytearray | memoryview): + return _framed(b"Y", bytes(value)) + pandas_bytes = _pandas_bytes(value) + if pandas_bytes is not None: + return pandas_bytes + if isinstance(value, Mapping): + items = b"".join( + canonical_result_bytes(key) + canonical_result_bytes(item) + for key, item in value.items() + ) + return _framed(b"M", _framed(b"t", _type_name(value)) + items) + if isinstance(value, tuple | list): + items = b"".join(canonical_result_bytes(item) for item in value) + return _framed(b"L", _framed(b"t", _type_name(value)) + items) + if isinstance(value, set | frozenset): + items = b"".join(sorted(canonical_result_bytes(item) for item in value)) + return _framed(b"E", _framed(b"t", _type_name(value)) + items) + if dataclasses.is_dataclass(value) and not isinstance(value, type): + items = b"".join( + canonical_result_bytes(field.name) + + canonical_result_bytes(getattr(value, field.name)) + for field in dataclasses.fields(value) + ) + return _framed(b"D", _framed(b"t", _type_name(value)) + items) + raise TypeError( + "canonical_result_bytes has no encoding for values of type " + f"{type(value).__module__}.{type(value).__qualname__}." + ) + + +def _first_difference(left: object, right: object, place: str) -> str: + """The place in two results where their canonical bytes first differ.""" + if type(left) is not type(right): + return f"{place} (types {type(left).__name__} and {type(right).__name__})" + if isinstance(left, Mapping): + if list(left) != list(right): + return f"{place} (its keys or their order)" + for key in left: + if canonical_result_bytes(left[key]) != canonical_result_bytes(right[key]): + return _first_difference(left[key], right[key], f"{place}[{key!r}]") + return place + if isinstance(left, tuple | list): + if len(left) != len(right): + return f"{place} (lengths {len(left)} and {len(right)})" + for position, (left_item, right_item) in enumerate( + zip(left, right, strict=True) + ): + if canonical_result_bytes(left_item) != canonical_result_bytes(right_item): + return _first_difference(left_item, right_item, f"{place}[{position}]") + return place + if dataclasses.is_dataclass(left) and not isinstance(left, type): + for field in dataclasses.fields(left): + left_item, right_item = ( + getattr(left, field.name), + getattr(right, field.name), + ) + if canonical_result_bytes(left_item) != canonical_result_bytes(right_item): + return _first_difference(left_item, right_item, f"{place}.{field.name}") + return place + if ( + isinstance(left, np.ndarray) + and left.dtype == right.dtype + and left.shape == right.shape + and not left.dtype.hasobject + ): + left_bytes = np.ascontiguousarray(left).reshape(-1).view(np.uint8) + right_bytes = np.ascontiguousarray(right).reshape(-1).view(np.uint8) + differing = np.flatnonzero(left_bytes != right_bytes) + if differing.size: + flat = int(differing[0]) // max(left.dtype.itemsize, 1) + position = np.unravel_index(flat, left.shape) if left.shape else () + return f"{place}[{', '.join(str(int(axis)) for axis in position)}]" + return place + + +def assert_identical_across_worker_counts( + run: Callable[[int], object], *, worker_counts: Sequence[int] = (1, 3) +) -> object: + """Run ``run(workers)`` at each worker count; require byte-identical results. + + Returns the result of the first worker count, so a test can check it + further. + + Raises: + AssertionError: Naming the worker count and the first place where its + result differs from the first worker count's. + """ + counts = tuple(worker_counts) + if len(counts) < 2 or any( + isinstance(count, bool) or not isinstance(count, int) or count < 1 + for count in counts + ): + raise ValueError( + f"worker_counts needs at least two positive worker counts; got {counts}." + ) + reference = run(counts[0]) + reference_bytes = canonical_result_bytes(reference) + for workers in counts[1:]: + result = run(workers) + if canonical_result_bytes(result) != reference_bytes: + place = _first_difference(reference, result, "result") + raise AssertionError( + f"Results with workers={workers} differ from workers={counts[0]} " + f"at {place}." + ) + return reference diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index f672b84652..552b5d3c2a 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -281,7 +281,10 @@ population_by_age_from_sim, write_demographics, ) -from microcosm.build.us_runtime.engine_lifecycle import release_engine_simulation +from microcosm.build.us_runtime.engine_lifecycle import ( + EngineVariableModuleScope, + release_engine_simulation, +) from microcosm.build.us_runtime.exact_k_ladder import ( ExactKLadderCalibration, assert_exact_k_realized_count, @@ -5721,6 +5724,11 @@ def dataset_from_frame(batch_frame: Frame): # Each finished consumer's scoring record, for the manifests' block. # Records, not consumers: a finished consumer's arrays must be freed. self.consumer_records: dict[str, dict[str, object]] = {} + # The reform last handed to any consumer. Consumers run one after + # another, so at most one reform's system and rule modules are held; + # opening the next reform, finishing its consumer or closing the scorer + # releases it. + self._open_reform: _BatchedPostExportReform | None = None def open_consumer( self, @@ -5746,6 +5754,8 @@ def finish_consumer(self, scoring: _PostExportConsumer) -> dict[str, object]: raise ValueError(f"{scoring.name} was not opened on this scorer.") if scoring.name in self.consumer_records: raise ValueError(f"{scoring.name} already finished on this scorer.") + if self._open_reform is not None and self._open_reform._consumer is scoring: + self._finish_open_reform() record = scoring.record() self.consumer_records[scoring.name] = record return record @@ -5781,9 +5791,27 @@ def manifest_record(self) -> dict[str, object]: } def close(self) -> None: + self._finish_open_reform() self._batch_frames = None _collect_family_garbage() + def _open_reform_for( + self, consumer: _PostExportConsumer, reform + ) -> _BatchedPostExportReform: + """Hand ``consumer`` a reform, finishing the one handed out before. + + Each shipped consumer scores one reform completely before it opens the + next, and consumers run one after another. + """ + self._finish_open_reform() + self._open_reform = _BatchedPostExportReform(consumer, reform) + return self._open_reform + + def _finish_open_reform(self) -> None: + reform, self._open_reform = self._open_reform, None + if reform is not None: + reform.finish() + def _batches(self) -> tuple[Frame, ...]: if self._batch_frames is None: raise RuntimeError("The post-export scorer is closed.") @@ -5974,7 +6002,7 @@ def __init__( def simulate(self, reform): if reform is None: return _PlannedPostExportBaseline(self) - return _BatchedPostExportReform(self, reform) + return self._scorer._open_reform_for(self, reform) def record(self) -> dict[str, object]: scorer = self._scorer @@ -6038,6 +6066,14 @@ class _BatchedPostExportReform: The reform's tax-benefit system is built once, on the first key, and handed to every batch engine (microcosm#456). The engines get that system alone (see ``_HouseholdBatchedPostExportScorer._construct``). + + Building the system makes policyengine-core add every variable module of + it to ``sys.modules`` (about 6,000 entries) under names it never removes; + on the eight-household guard fixture they hold about 0.04 GiB per reform. + The build opens an ``EngineVariableModuleScope``, which stays open until + the scorer hands out its next reform, the consumer finishes or the scorer + closes (:meth:`finish`), and then removes those modules. A finished reform + refuses further keys. """ def __init__(self, consumer: _PostExportConsumer, reform) -> None: @@ -6045,19 +6081,46 @@ def __init__(self, consumer: _PostExportConsumer, reform) -> None: self._reform = reform self._system = None self._results: dict[PostExportKey, _PostExportValues] = {} + self._rule_modules: EngineVariableModuleScope | None = None + self._finished = False def calculate(self, variable, period=None, map_to=None) -> _PostExportValues: key = _post_export_key(variable, period, map_to) + if self._finished: + raise RuntimeError( + f"{self._consumer.name} asked a finished reform for {key}. A " + "post-export consumer scores each reform completely before it " + "opens the next one, which finishes and releases the earlier." + ) if key not in self._results: if self._system is None: scorer = self._consumer._scorer - self._system = scorer._microsimulation_cls.default_tax_benefit_system( - reform=self._reform - ) + rule_modules = EngineVariableModuleScope().open() + try: + self._system = ( + scorer._microsimulation_cls.default_tax_benefit_system( + reform=self._reform + ) + ) + except BaseException: + rule_modules.close() + raise + self._rule_modules = rule_modules self._consumer.reform_systems += 1 self._results[key] = self._consumer._reform_values(self._system, key) return self._results[key] + def finish(self) -> None: + """Drop the reform's system and remove the modules its build added.""" + if self._finished: + return + self._finished = True + self._system = None + self._results = {} + rule_modules, self._rule_modules = self._rule_modules, None + if rule_modules is not None: + rule_modules.close() + def _reform_household_income_tax( *, diff --git a/tools/score_us_release_head_to_head.py b/tools/score_us_release_head_to_head.py index eda715e2d7..b60f34ee77 100644 --- a/tools/score_us_release_head_to_head.py +++ b/tools/score_us_release_head_to_head.py @@ -17,7 +17,8 @@ through the same population repair, target materialization, constraint matrix, scoring, loss attribution, contract checks, and rendering path. Scoring defaults to sequential execution; optional spawned workers score -independent slices. Every process refuses a peak at or above 20 GiB RSS. +independent slices on the shared worker pool (microcosm.build.worker_pool). +Every process refuses a peak at or above 20 GiB RSS. Memory design, from measurements on the live incumbent (57,240 households, 166,321 persons): the unbatched full-frame base microsimulation alone peaks @@ -56,13 +57,10 @@ import hashlib import json import math -import multiprocessing import resource import sys import time -from collections import deque from collections.abc import Iterable, Iterator, Mapping, Sequence -from concurrent.futures import ProcessPoolExecutor from dataclasses import dataclass, field from pathlib import Path @@ -106,6 +104,7 @@ support_channel_column, support_clone_index_column, ) +from microcosm.build.worker_pool import WorkerPool, WorkerPoolSettings from microcosm.calibrate import TargetRegistry, score_targets from microcosm.calibrate.solve import relative_error_loss from microcosm.frame import US_SCHEMA, Frame @@ -313,9 +312,6 @@ class _SliceWorkerState: slice_batches: tuple[np.ndarray, ...] -_SLICE_WORKER_STATE: _SliceWorkerState | None = None - - def _positive_workers(value: str) -> int: workers = int(value) if workers < 1: @@ -330,65 +326,6 @@ def _positive_worker_max_slices(value: str) -> int: return maximum -# CPython could deadlock when ProcessPoolExecutor replaced a worker that had -# reached max_tasks_per_child: the pool was left with no worker and a pending -# task, so future.result() waited forever. Fixed in 3.13.15, 3.14.7 and -# 3.15.0b4 (see the max_tasks_per_child notes in the concurrent.futures -# documentation); every later minor ships the fix. -_RELEASE_LEVEL_RANK = {"alpha": 0, "beta": 1, "candidate": 2, "final": 3} -_RELEASE_LEVEL_SUFFIX = {"alpha": "a", "beta": "b", "candidate": "rc"} -_WORKER_RECYCLING_FIXED_IN = { - (3, 13): (3, 13, 15, "final", 0), - (3, 14): (3, 14, 7, "final", 0), - (3, 15): (3, 15, 0, "beta", 4), -} - - -def _comparable_version(version: Sequence[object]) -> tuple[int, int, int, int, int]: - """Order a ``sys.version_info``-shaped value, prereleases before finals.""" - - parts = tuple(version) - major, minor, micro = (int(part) for part in parts[:3]) - level = str(parts[3]) if len(parts) > 3 else "final" - serial = int(parts[4]) if len(parts) > 4 else 0 - return (major, minor, micro, _RELEASE_LEVEL_RANK[level], serial) - - -def _version_text(version: Sequence[object]) -> str: - parts = tuple(version) - text = ".".join(str(part) for part in parts[:3]) - level = str(parts[3]) if len(parts) > 3 else "final" - if level == "final": - return text - serial = parts[4] if len(parts) > 4 else 0 - return f"{text}{_RELEASE_LEVEL_SUFFIX[level]}{serial}" - - -def _assert_worker_recycling_supported( - version_info: Sequence[object] | None = None, -) -> None: - """Refuse worker recycling on an interpreter that can deadlock doing it.""" - - version = tuple(sys.version_info if version_info is None else version_info) - minor = (int(version[0]), int(version[1])) - fixed = _WORKER_RECYCLING_FIXED_IN.get(minor) - if fixed is None: - # Later minors ship the fix; earlier ones are below requires-python - # and never received it. - if minor > max(_WORKER_RECYCLING_FIXED_IN): - return - fixed_text = "3.13.15, 3.14.7 or 3.15.0b4" - elif _comparable_version(version) >= _comparable_version(fixed): - return - else: - fixed_text = _version_text(fixed) - raise RuntimeError( - f"--worker-max-slices needs Python {fixed_text} or later: on " - f"{_version_text(version)} replacing a recycled worker can deadlock " - "the pool. Run without --worker-max-slices, or use a fixed interpreter." - ) - - def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser( description=( @@ -455,8 +392,9 @@ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: type=_positive_worker_max_slices, default=None, help=( - "Replace each spawned worker after K household slices, including " - "across registry chunks; defaults to no recycling." + "Replace each spawned worker with a fresh one after K household " + "slices, including across registry chunks; defaults to no " + "replacement." ), ) parser.add_argument( @@ -1098,22 +1036,22 @@ def _initialize_slice_worker( artifact_name: str, chunk_size: int, maximum_microsim_batch_size: int | None, -) -> None: +) -> _SliceWorkerState: """Receive the parent's exact repaired frame and compiled specs once. - Spawn pickles initializer arguments once per process. Passing the already - normalized, authenticated, repaired frame avoids reopening the artifact or - repeating any loader/repair decisions in a worker. Tasks contain only two - indices; neither the full frame nor the registry is sent per slice. + Spawn pickles initializer arguments once per worker process. Passing the + already normalized, authenticated, repaired frame avoids reopening the + artifact or repeating any loader/repair decisions in a worker. Tasks contain + only two indices; neither the full frame nor the registry is sent per slice. + The returned state reaches every slice the worker scores. """ - global _SLICE_WORKER_STATE slice_batches = tuple( release._household_position_batches( base_frame.n("household"), maximum_microsim_batch_size ) ) - _SLICE_WORKER_STATE = _SliceWorkerState( + state = _SliceWorkerState( base_frame=base_frame, specs=specs, loss_weights=loss_weights, @@ -1123,14 +1061,12 @@ def _initialize_slice_worker( slice_batches=slice_batches, ) _assert_rss_below_limit(f"after initializing {artifact_name} slice worker") + return state -def _score_slice_worker(task: tuple[int, int]) -> ScoredSlice: +def _score_slice_worker(state: _SliceWorkerState, task: tuple[int, int]) -> ScoredSlice: """Run every sequential per-slice contract in an isolated process.""" - state = _SLICE_WORKER_STATE - if state is None: # pragma: no cover - executor always initializes workers - raise RuntimeError("Slice worker was not initialized.") chunk_index, slice_index = task chunk_count = max(1, math.ceil(len(state.specs) / state.chunk_size)) slice_label = ( @@ -1155,6 +1091,9 @@ def _score_slice_worker(task: tuple[int, int]) -> ScoredSlice: gc.collect() _assert_rss_below_limit(f"after scoring {label}") return scored_slice + except MemoryError: + # The shared pool runs the slice again in a fresh worker. + raise except Exception as error: raise RuntimeError(f"{label} worker failed: {error}") from error @@ -1252,7 +1191,13 @@ def _score_chunks_parallel( workers: int, worker_max_slices: int | None = None, ) -> Iterator[ScoredChunk]: - """Stream bounded (chunk, slice) tasks through one spawn pool per artifact.""" + """Stream (chunk, slice) tasks through one shared worker pool per artifact. + + The pool returns slice results in task order, so each chunk reduces its + slices in the sequential order whatever order the workers finish in. A + slice whose worker dies or runs out of memory runs once more in a fresh + worker before the run stops. + """ slice_count = len( tuple( @@ -1268,16 +1213,25 @@ def _score_chunks_parallel( release._assert_medicaid_claiming_tax_units_local(base_frame) chunk_size = MATERIALIZE_SCORE_CHUNK_SPECS chunk_count = max(1, math.ceil(len(specs) / chunk_size)) - tasks = iter( + # Tasks span chunk boundaries so short chunks still use the pool. + tasks = [ (chunk_index, slice_index) for chunk_index in range(chunk_count) for slice_index in range(slice_count) - ) + ] + + def describe_task(index: int, task: tuple[int, int]) -> str: + chunk_index, slice_index = task + return ( + f"{artifact_name} chunk {chunk_index + 1}/{chunk_count} " + f"slice {slice_index + 1}/{slice_count}" + ) + _assert_rss_below_limit(f"before starting {artifact_name} slice workers") - with ProcessPoolExecutor( - max_workers=workers, - mp_context=multiprocessing.get_context("spawn"), - max_tasks_per_child=worker_max_slices, + # At most 2 * workers slices run or wait with a result, which bounds the + # results held here even if an early slice stalls. + with WorkerPool( + WorkerPoolSettings(workers=workers, max_units_per_worker=worker_max_slices), initializer=_initialize_slice_worker, initargs=( base_frame, @@ -1287,42 +1241,18 @@ def _score_chunks_parallel( chunk_size, maximum_microsim_batch_size, ), - ) as executor: - pending = deque() - - def submit_next() -> None: - task = next(tasks, None) - if task is not None: - try: - future = executor.submit(_score_slice_worker, task) - except Exception as error: - chunk_index, slice_index = task - raise RuntimeError( - f"{artifact_name} chunk {chunk_index + 1}/{chunk_count} " - f"slice {slice_index + 1}/{slice_count} worker submission " - f"failed: {error}" - ) from error - pending.append((task, future)) + unit_function=_score_slice_worker, + describe_unit=describe_task, + ) as pool: + results = pool.map(tasks) def chunk_results() -> Iterator[ScoredSlice]: for _ in range(slice_count): - (chunk_index, slice_index), future = pending.popleft() - try: - result = future.result() - except Exception as error: - raise RuntimeError( - f"{artifact_name} chunk {chunk_index + 1}/{chunk_count} " - f"slice {slice_index + 1}/{slice_count} worker failed: {error}" - ) from error - submit_next() + result = next(results) _assert_rss_below_limit(f"after receiving {artifact_name} slice result") yield result try: - # Bound futures and buffered results even if an early slice stalls. - # Tasks span chunk boundaries so short chunks still use the pool. - for _ in range(2 * workers): - submit_next() for chunk_index in range(chunk_count): yield _reduce_scored_slices( chunk_results(), @@ -1332,8 +1262,7 @@ def chunk_results() -> Iterator[ScoredSlice]: maximum_microsim_batch_size=maximum_microsim_batch_size, ) finally: - for _, future in pending: - future.cancel() + results.close() def _spec_keys(specs: Sequence) -> tuple[tuple[str, object], ...]: @@ -1895,8 +1824,6 @@ def score_loaded_artifact( raise ValueError("workers must be at least 1.") if worker_max_slices is not None and worker_max_slices < 1: raise ValueError("worker_max_slices must be at least 1.") - if worker_max_slices is not None: - _assert_worker_recycling_supported() cd_provenance = _validate_cd_provenance(artifact, yardstick) terminal_battery = _terminal_battery_payload(artifact) base_frame, mass_repair = release._with_base_population_mass_repair(artifact.frame) @@ -2217,8 +2144,6 @@ def score_head_to_head( raise ValueError("workers must be at least 1.") if worker_max_slices is not None and worker_max_slices < 1: raise ValueError("worker_max_slices must be at least 1.") - if worker_max_slices is not None: - _assert_worker_recycling_supported() crosswalk = congressional_district_vintage_crosswalk or ( release.default_congressional_district_vintage_crosswalk_path() ) From 6b406b493e1a8d3547d686fbac92e9920ec45ae1 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:44:30 +0400 Subject: [PATCH 04/16] Add failing tests for the first review round's findings Pool: the memory cap while a worker starts, resuming a closed pool's map, a worker that will not exit after being stopped, an unclosed pool's workers, busy workers whose parent is killed, a map whose results were all taken, units and results that cannot be unpickled, memory one unit leaves behind, environment values that cannot be encoded, exit statuses collected elsewhere, and functions defined where workers cannot import them. Scorer: its own 20 GiB check stays fatal in a worker, a failed worker start names the artifact, and failed attempts are reported on stderr. Identity helper: structured dtypes, masked arrays, scalar and integer subclasses, bytes types and pandas categories and index names. Rule-module scopes may close out of order, and closing one scorer keeps another's open reform modules. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_worker_pool.py | 245 ++++++++++++++++++ .../us/test_us_post_export_scoring.py | 36 +++ .../us/test_us_release_head_to_head_scorer.py | 63 ++++- .../us/test_us_release_slice_memory.py | 22 ++ .../us_release_head_to_head_scorer.py | 11 + .../worker_pool_orphan_parent.py | 23 ++ .../microcosm_build/worker_pool_units.py | 51 ++++ 7 files changed, 449 insertions(+), 2 deletions(-) create mode 100644 test_support/microcosm_build/worker_pool_orphan_parent.py diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py index 9dd2131c44..67722c489e 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -2,14 +2,21 @@ from __future__ import annotations +import gc import multiprocessing import os import signal +import subprocess +import sys +import time from collections import Counter +from pathlib import Path +from types import ModuleType import numpy as np import pytest +import microcosm.build.worker_pool as worker_pool_module from microcosm.build.worker_pool import ( WorkerPool, WorkerPoolError, @@ -22,6 +29,7 @@ assert_identical_across_worker_counts, canonical_result_bytes, ) +from test_support.paths import paths_for MIB = 1024 * 1024 TEST_SECONDS_LIMIT = 120 @@ -334,6 +342,210 @@ def test_process_memory_bytes_sees_this_process_grow() -> None: del held +def test_the_memory_cap_is_enforced_while_another_worker_starts(monkeypatch) -> None: + """Starting a worker can block for as long as the worker takes to import. + + The memory thread must still be able to stop a worker over its cap, so a + start must not hold the lock that thread needs. + """ + pool = WorkerPool(WorkerPoolSettings(workers=1), unit_function=units.echo) + starts_under_lock = [] + real_process = pool._context.Process + + class RecordingProcess(real_process): + def start(self): + starts_under_lock.append(pool._shared.lock.locked()) + return super().start() + + monkeypatch.setattr(pool._context, "Process", RecordingProcess) + with pool: + list(pool.map([0])) + assert starts_under_lock == [False] + + +def test_resuming_a_map_after_the_pool_closed_raises_and_starts_nothing() -> None: + pool = WorkerPool( + WorkerPoolSettings(workers=2), unit_function=units.sleep_then_return + ) + results = pool.map([(index, 0.3) for index in range(6)]) + assert next(results) == 0 + pool.close() + starts = pool.report().worker_starts + + with pytest.raises(WorkerPoolError, match="closed"): + next(results) + assert pool.report().worker_starts == starts + assert multiprocessing.active_children() == [] + + +def test_a_worker_that_will_not_exit_after_being_stopped_is_killed(monkeypatch) -> None: + monkeypatch.setattr(worker_pool_module, "_STOP_SECONDS", 1.0) + started = time.monotonic() + with WorkerPool( + WorkerPoolSettings(workers=1, max_units_per_worker=1), + initializer=units.start_lingering_thread, + unit_function=units.echo, + ) as pool: + results = list(pool.map(range(2))) + + assert results == [0, 1] + assert time.monotonic() - started < 60 + + +def _unclosed_run() -> list: + pool = WorkerPool(WorkerPoolSettings(workers=2), unit_function=units.echo) + return list(pool.map(range(2))) + + +def test_a_pool_dropped_without_closing_stops_its_workers() -> None: + assert len(_unclosed_run()) == 2 + gc.collect() + deadline = time.monotonic() + 30 + while multiprocessing.active_children() and time.monotonic() < deadline: + time.sleep(0.1) + assert multiprocessing.active_children() == [] + + +def _process_running(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + status = Path(f"/proc/{pid}/stat") + if status.exists(): + # An exited process its new parent has not reaped yet is a zombie. + return status.read_text().rsplit(")", 1)[1].split()[0] != "Z" + return True + + +def test_busy_workers_exit_when_their_parent_is_killed(tmp_path) -> None: + repository = paths_for("microcosm-build").repository + environment = {**os.environ, "PYTHONPATH": str(repository)} + parent = subprocess.Popen( + [ + sys.executable, + "-m", + "test_support.microcosm_build.worker_pool_orphan_parent", + str(tmp_path), + ], + cwd=repository, + env=environment, + ) + try: + deadline = time.monotonic() + 90 + while len(list(tmp_path.glob("worker-*"))) < 2: + assert parent.poll() is None, "the parent process exited early" + assert time.monotonic() < deadline, "the workers did not start" + time.sleep(0.2) + worker_pids = [ + int(path.name.split("-")[1]) for path in tmp_path.glob("worker-*") + ] + finally: + parent.kill() + parent.wait() + + deadline = time.monotonic() + 20 + while ( + any(_process_running(pid) for pid in worker_pids) + and time.monotonic() < deadline + ): + time.sleep(0.2) + still_running = [pid for pid in worker_pids if _process_running(pid)] + for pid in still_running: + os.kill(pid, signal.SIGKILL) + assert still_running == [] + + +def test_taking_every_result_finishes_the_map_without_exhausting_it() -> None: + with WorkerPool(WorkerPoolSettings(workers=2), unit_function=units.echo) as pool: + results = pool.map(range(3)) + assert [next(results) for _ in range(3)] == [0, 1, 2] + results.close() + assert list(pool.map(range(2))) == [0, 1] + + +def test_a_unit_the_worker_cannot_unpickle_stops_the_run_with_its_cause() -> None: + with WorkerPool( + WorkerPoolSettings(workers=1, max_attempts=3), + unit_function=units.echo, + ) as pool: + with pytest.raises( + WorkerPoolUnitError, match=r"unit 1/1 .*ValueError: this object cannot" + ) as failure: + list(pool.map([units.RefusesToUnpickle()])) + assert pool.report().worker_starts == 1 + assert len(failure.value.causes) == 1 + + +def test_a_result_the_parent_cannot_unpickle_stops_the_run_with_its_label() -> None: + with WorkerPool( + WorkerPoolSettings(workers=1), + unit_function=units.return_object_the_parent_cannot_unpickle, + ) as pool: + with pytest.raises( + WorkerPoolUnitError, match=r"unit 1/1 .*could not be read in the parent" + ): + list(pool.map([0])) + + +def test_memory_a_unit_leaves_behind_is_not_charged_to_the_next_unit() -> None: + # The memory thread's first reading comes long after this test ends, so + # only the reading taken when unit 0 returns can see the 600 MiB. + settings = WorkerPoolSettings( + workers=1, + memory_cap_bytes=400 * MIB, + memory_poll_seconds=300.0, + max_attempts=1, + ) + with WorkerPool(settings, unit_function=units.keep_memory_after_returning) as pool: + assert list(pool.map([(0, 600), (1, 0)])) == [0, 1] + report = pool.report() + + assert report.failed_attempts == () + assert report.workers_stopped_over_cap == 1 + + +def test_a_worker_environment_value_that_cannot_be_encoded_is_refused() -> None: + with pytest.raises(ValueError, match="worker_environment"): + WorkerPoolSettings( + workers=1, + worker_environment={ + "MICROCOSM_TEST_OK": "1", + "MICROCOSM_TEST_BAD": "\ud800", + }, + ) + + +def test_a_dead_worker_is_noticed_when_something_else_collects_children() -> None: + previous = signal.signal(signal.SIGCHLD, signal.SIG_IGN) + try: + with WorkerPool( + WorkerPoolSettings(workers=1, max_attempts=2), + unit_function=units.always_die, + ) as pool: + with pytest.raises(WorkerPoolUnitError, match="unit 1/1 failed on all 2"): + list(pool.map([0])) + finally: + signal.signal(signal.SIGCHLD, previous) + + +def test_a_function_defined_where_workers_cannot_import_it_is_refused( + monkeypatch, +) -> None: + script_main = ModuleType("__main__") # As under ``python -c`` or a REPL. + + def typed_at_the_prompt(state, unit): + return unit + + typed_at_the_prompt.__module__ = "__main__" + typed_at_the_prompt.__qualname__ = "typed_at_the_prompt" + script_main.typed_at_the_prompt = typed_at_the_prompt + monkeypatch.setitem(sys.modules, "__main__", script_main) + + with pytest.raises(TypeError, match="importable"): + WorkerPool(WorkerPoolSettings(workers=1), unit_function=typed_at_the_prompt) + + # --------------------------------------------------------------------------- # The 1-vs-N byte-identity helper # --------------------------------------------------------------------------- @@ -429,3 +641,36 @@ def test_canonical_bytes_tell_apart_what_equality_hides() -> None: assert canonical_result_bytes((1, 2)) != canonical_result_bytes([1, 2]) with pytest.raises(TypeError, match="object"): canonical_result_bytes(object()) + + +def test_canonical_bytes_keep_field_types_array_kinds_and_pandas_metadata() -> None: + import enum + + import pandas as pd + + little_endian = np.array([(1.0,)], dtype=[("a", "f8")]) + ) + assert canonical_result_bytes(little_endian) != canonical_result_bytes( + little_endian.view([("b", " None: + first_log, second_log = _EngineLog(), _EngineLog() + first = _scorer( + builder, + _nested_frame(), + first_log, + 3, + tmp_path / "first", + variables_dir=stand_in_rule_modules, + ) + second = _scorer( + builder, + _nested_frame(), + second_log, + 3, + tmp_path / "second", + variables_dir=stand_in_rule_modules, + ) + first.open_consumer("fixture", ()).simulate(_FakeReform("first")).calculate( + "income_tax", builder.PERIOD + ) + second_consumer = second.open_consumer("fixture", ()) + second_reform = second_consumer.simulate(_FakeReform("second")) + second_reform.calculate("income_tax", builder.PERIOD) + + first.close() + + assert _rule_module_name(first_log.systems[0]) not in sys.modules + assert _rule_module_name(second_log.systems[0]) in sys.modules + second_reform.calculate("income_tax", builder.PERIOD + 1) + second.finish_consumer(second_consumer) + assert _stand_in_rule_modules_left(stand_in_rule_modules) == [] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_head_to_head_scorer.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_head_to_head_scorer.py index 7e4cfbaada..ce0dac1cd3 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_head_to_head_scorer.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_head_to_head_scorer.py @@ -3,13 +3,18 @@ # ruff: noqa: F403, F405 import json import multiprocessing +import re import signal import time from hypothesis import HealthCheck, example, given, settings from hypothesis import strategies as st -from microcosm.build.worker_pool import WorkerPool, WorkerPoolUnitError +from microcosm.build.worker_pool import ( + WorkerPool, + WorkerPoolError, + WorkerPoolUnitError, +) from test_support.microcosm_build.us_release_head_to_head_scorer import * @@ -187,7 +192,54 @@ def test_spawned_worker_failure_includes_chunk_and_slice_label(monkeypatch) -> N ) -def test_abrupt_worker_death_is_labelled_and_leaves_no_children(monkeypatch) -> None: +def test_a_workers_own_memory_limit_stops_the_run_without_scoring_the_slice_again( + monkeypatch, +) -> None: + """The scorer's 20 GiB check stays fatal in a worker, as in one process.""" + module = _load_head_to_head_module() + _parallel_fixture(module, monkeypatch) + monkeypatch.setattr( + module, "_initialize_slice_worker", _initialize_low_limit_fixture_slice_worker + ) + with pytest.raises( + WorkerPoolUnitError, + match=r"incumbent chunk 1/2 slice 1/2 .*scoring limit", + ) as failure: + module.score_head_to_head( + incumbent=Path("/fixture/incumbent.h5"), + candidate=None, + ledger_facts=Path("/fixture/facts.jsonl"), + congressional_district_vintage_crosswalk=Path("/fixture/crosswalk.parquet"), + maximum_microsim_batch_size=2, + workers=1, + worker_max_slices=100, + ) + assert len(failure.value.causes) == 1 + + +def test_a_worker_start_failure_names_the_artifact(monkeypatch) -> None: + module = _load_head_to_head_module() + _parallel_fixture(module, monkeypatch) + monkeypatch.setattr( + module, "_initialize_slice_worker", _initialize_refusing_fixture_slice_worker + ) + with pytest.raises( + WorkerPoolError, + match=r"incumbent slice workers failed: .*fixture worker start refused", + ): + module.score_head_to_head( + incumbent=Path("/fixture/incumbent.h5"), + candidate=None, + ledger_facts=Path("/fixture/facts.jsonl"), + congressional_district_vintage_crosswalk=Path("/fixture/crosswalk.parquet"), + maximum_microsim_batch_size=2, + workers=2, + ) + + +def test_abrupt_worker_death_is_labelled_and_leaves_no_children( + monkeypatch, capsys +) -> None: from test_support.microcosm_build.us_release_head_to_head_worker_death import ( OneHouseholdFrame, exit_slice_worker, @@ -227,6 +279,13 @@ def timeout_handler(signum, frame) -> None: assert len(failure.value.causes) == 2 assert all("exited with code 97" in cause for cause in failure.value.causes) assert multiprocessing.active_children() == [] + # Each failed attempt is reported on stderr, as the memory receipts are. + stderr = capsys.readouterr().err + assert re.search( + r"fixture chunk [12]/2 slice 1/1: attempt 1 ended without a result " + r"\(the worker exited with code 97\)", + stderr, + ) finally: signal.setitimer(signal.ITIMER_REAL, 0) for process in multiprocessing.active_children(): diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py index dcffc78123..5dcb78123e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py @@ -258,3 +258,25 @@ def test_an_unclosed_scope_removes_nothing_when_it_is_collected(tmp_path) -> Non finally: sys.modules.pop(abandoned_name, None) sys.modules.pop(later_name, None) + + +def test_closing_an_earlier_scope_keeps_a_later_open_scopes_modules(tmp_path) -> None: + """Scopes may close out of order without removing a module still in use.""" + variables_dir = tmp_path / "variables" + earlier_name = "7500001_-123_income_tax" + later_name = "7500002_-123_income_tax" + try: + earlier = EngineVariableModuleScope(variables_dir).open() + _register_variable_module(earlier_name, variables_dir) + later = EngineVariableModuleScope(variables_dir).open() + _register_variable_module(later_name, variables_dir) + + earlier.close() + assert earlier_name not in sys.modules + assert later_name in sys.modules + + later.close() + assert later_name not in sys.modules + finally: + sys.modules.pop(earlier_name, None) + sys.modules.pop(later_name, None) diff --git a/test_support/microcosm_build/us_release_head_to_head_scorer.py b/test_support/microcosm_build/us_release_head_to_head_scorer.py index 5469c292dc..f9f641da56 100644 --- a/test_support/microcosm_build/us_release_head_to_head_scorer.py +++ b/test_support/microcosm_build/us_release_head_to_head_scorer.py @@ -273,6 +273,17 @@ def _initialize_failing_fixture_slice_worker(*args): return state +def _initialize_low_limit_fixture_slice_worker(*args): + """A fixture worker whose own memory check fires after its first slice.""" + state = _initialize_fixture_slice_worker(*args) + _load_head_to_head_module().MAX_RSS_BYTES = 1 + return state + + +def _initialize_refusing_fixture_slice_worker(*args): + raise ValueError("fixture worker start refused") + + def _three_household_fixture_artifact(module, *, sha256: str, measure_values): """Extend the existing frame with a shorter household-slice tail.""" artifact = _fixture_artifact( diff --git a/test_support/microcosm_build/worker_pool_orphan_parent.py b/test_support/microcosm_build/worker_pool_orphan_parent.py new file mode 100644 index 0000000000..50f00cf094 --- /dev/null +++ b/test_support/microcosm_build/worker_pool_orphan_parent.py @@ -0,0 +1,23 @@ +"""A parent process whose pool workers are busy when the test kills it. + +Run as ``python -m test_support.microcosm_build.worker_pool_orphan_parent DIR``: +each worker writes ``DIR/worker-`` and then sleeps for a minute. +""" + +from __future__ import annotations + +import sys + +from microcosm.build.worker_pool import WorkerPool, WorkerPoolSettings +from test_support.microcosm_build import worker_pool_units as units + + +def main(directory: str) -> None: + with WorkerPool( + WorkerPoolSettings(workers=2), unit_function=units.write_pid_then_sleep + ) as pool: + list(pool.map([(directory, 60.0), (directory, 60.0)])) + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/test_support/microcosm_build/worker_pool_units.py b/test_support/microcosm_build/worker_pool_units.py index 63423edd8d..746342692c 100644 --- a/test_support/microcosm_build/worker_pool_units.py +++ b/test_support/microcosm_build/worker_pool_units.py @@ -27,6 +27,11 @@ def initialize_with_payload(payload): return {"payload": payload, "initializer_calls": _INITIALIZER_CALLS} +def echo(state, unit): + """Return the unit; needs no initializer state.""" + return unit + + def describe_worker(state, unit): return { "unit": unit, @@ -130,3 +135,49 @@ def score_household_batch(state, positions): "per_household": per_household, "weighted_total": np.sum(per_household * weights, dtype=np.float64), } + + +def start_lingering_thread(*args): + """An initializer whose worker keeps a non-daemon thread after it returns. + + multiprocessing waits for such a thread before the process exits, so a + worker told to stop stays alive until the pool kills it. + """ + import threading + + threading.Thread(target=time.sleep, args=(120,), daemon=False).start() + + +def _refuse_to_load(): + raise ValueError("this object cannot be rebuilt after pickling") + + +class RefusesToUnpickle: + """Pickles fine, but raises when it is unpickled.""" + + def __reduce__(self): + return (_refuse_to_load, ()) + + +def return_object_the_parent_cannot_unpickle(state, unit): + return RefusesToUnpickle() + + +_KEPT: list = [] + + +def keep_memory_after_returning(state, unit): + """Return at once, but keep ``mebibytes`` alive in this worker.""" + value, mebibytes = unit + if mebibytes: + _KEPT.append(np.ones(mebibytes * 1024 * 1024 // 8)) + else: + time.sleep(0.5) + return value + + +def write_pid_then_sleep(state, unit): + directory, seconds = unit + (Path(directory) / f"worker-{os.getpid()}").write_text("running") + time.sleep(seconds) + return os.getpid() From 5fea759df943974cd2da691d1708bf805aa0c791 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:07:57 +0400 Subject: [PATCH 05/16] Fix the first review round's findings Pool: a worker start no longer holds the lock the memory thread needs; a map resumed after close raises; a worker that has not exited 10 s after being told to stop is killed; the memory thread and the finalizer share state with the pool, not the pool itself, so an unclosed pool is collected and kills its workers; workers exit when their parent dies; the last result finishes the map; units and results that cannot be unpickled stop the run with their label; a worker over its cap when it returns a result is replaced before its next unit; environment values are checked for encoding and set inside the restore block; dispatch no longer counts every unsent unit on each pass; exits are seen through each worker's exit pipe, so an exit status collected elsewhere is noticed; workers are killed through a pidfd on Linux; functions in a __main__ that spawn cannot import are refused. Scorer: its own 20 GiB check stays fatal in a worker, a failed worker start names the artifact, and failed attempts are reported on stderr. Module scopes may close out of order; the identity helper keeps dtypes with their fields, array and scalar types, masks and pandas metadata. The h2h memory evidence README describes worker replacement on the shared pool. Co-Authored-By: Claude Opus 5.5 --- docs/evidence/us-h2h-memory/README.md | 10 +- .../build/us_runtime/engine_lifecycle.py | 54 +- .../src/microcosm/build/worker_pool.py | 572 ++++++++++++------ .../engine_free/shared/test_worker_pool.py | 17 +- .../microcosm_build/worker_pool_identity.py | 87 ++- tools/score_us_release_head_to_head.py | 42 +- 6 files changed, 561 insertions(+), 221 deletions(-) diff --git a/docs/evidence/us-h2h-memory/README.md b/docs/evidence/us-h2h-memory/README.md index 8b476cb38c..6dd765a34b 100644 --- a/docs/evidence/us-h2h-memory/README.md +++ b/docs/evidence/us-h2h-memory/README.md @@ -50,9 +50,13 @@ imports, unrelated paths, and the shared default system when imported lazily. It restores pre-existing entries if Core reused a discarded system's id. The returned slice contains no live engine objects. -`--worker-max-slices K` additionally passes `max_tasks_per_child=K` to the spawn -executor. The default remains no recycling. An explicit K also uses the pool -with `--workers 1`. Task submission and ordered reduction remain unchanged. +`--worker-max-slices K` additionally replaces each spawned worker after K +slices. The scorer first did this with `ProcessPoolExecutor`'s +`max_tasks_per_child=K`; it now runs its slices on the shared worker pool +(`microcosm.build.worker_pool`), which replaces workers itself and so works on +every supported Python. The default remains no replacement. An explicit K also +uses the pool with `--workers 1`. Task order and ordered reduction remain +unchanged. ## Measurement method diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py b/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py index 0197b84c04..669757f972 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py @@ -30,6 +30,8 @@ from __future__ import annotations import sys +import threading +import weakref from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path @@ -72,6 +74,12 @@ def _registrations(directory: Path | None) -> dict[str, ModuleType]: return found +# Scopes opened and not yet closed, oldest first, as weak references: a scope +# dropped without closing stops counting once it is collected. +_OPEN_SCOPES: list[weakref.ref[EngineVariableModuleScope]] = [] +_OPEN_SCOPES_LOCK = threading.Lock() + + class EngineVariableModuleScope: """Remove Core's variable-module registrations made between open and close. @@ -83,6 +91,11 @@ class EngineVariableModuleScope: later scope registered and still uses. A scope left unclosed here does nothing when collected; its modules simply stay registered, as they would without it. ``close`` does nothing the second time. + + Scopes may close in any order. A scope that closes while a scope opened + after it is still open removes only what was registered before that later + scope opened; what came after may belong to the later scope, which removes + it when it closes. """ def __init__(self, variables_dir: str | Path | None = None) -> None: @@ -98,16 +111,44 @@ def open(self) -> EngineVariableModuleScope: directory = ( None if initial_directory is None else Path(initial_directory).absolute() ) - self._previous = _registrations(directory) + with _OPEN_SCOPES_LOCK: + self._previous = _registrations(directory) + _OPEN_SCOPES.append(weakref.ref(self)) return self + def _first_later_open_scope_snapshot(self) -> dict[str, ModuleType] | None: + """The snapshot of the oldest scope opened after this one and still open.""" + later = False + snapshot = None + live = [] + for reference in _OPEN_SCOPES: + scope = reference() + if scope is None: + continue + live.append(reference) + if scope is self: + later = True + elif later and snapshot is None and scope._previous is not None: + snapshot = scope._previous + _OPEN_SCOPES[:] = [reference for reference in live if reference() is not self] + return snapshot + def close(self) -> None: """Remove the registrations made since ``open``, except the shared system's.""" - previous, self._previous = self._previous, None - if self._closed or previous is None: + with _OPEN_SCOPES_LOCK: + previous, self._previous = self._previous, None + if self._closed or previous is None: + self._closed = True + return self._closed = True - return - self._closed = True + later_snapshot = self._first_later_open_scope_snapshot() + self._remove_since(previous, later_snapshot) + + def _remove_since( + self, + previous: dict[str, ModuleType], + later_snapshot: dict[str, ModuleType] | None, + ) -> None: final_directory = self._variables_dir or _loaded_variables_dir() if final_directory is None: return @@ -123,6 +164,9 @@ def close(self) -> None: for name in _registrations(Path(final_directory).absolute()): if name in previous: sys.modules[name] = previous[name] + elif later_snapshot is not None and name not in later_snapshot: + # Registered after a still-open later scope opened. + continue elif shared_system is None or not name.startswith(shared_prefix): sys.modules.pop(name, None) diff --git a/packages/microcosm-build/src/microcosm/build/worker_pool.py b/packages/microcosm-build/src/microcosm/build/worker_pool.py index bfcd847975..7b669104fc 100644 --- a/packages/microcosm-build/src/microcosm/build/worker_pool.py +++ b/packages/microcosm-build/src/microcosm/build/worker_pool.py @@ -17,38 +17,59 @@ in each worker, and whatever it returns is passed to every unit that worker runs as ``unit_function(state, unit)``. Spawn pickles ``initargs`` once per worker start, so a frame passed there crosses once per worker, not once per - unit. A unit itself should be small (indices, a request descriptor). -* **Worker replacement.** With ``max_units_per_worker``, a worker is stopped - after that many units and a fresh one takes its place, so memory that an - engine leaves behind does not build up. The pool starts the replacement only - after the old worker has exited, so no more than ``workers`` processes are - ever alive at once. The pool manages its own processes, so worker + unit; while a worker starts, the parent briefly holds that pickled copy too. + A unit itself should be small (indices, a request descriptor). +* **Worker replacement.** With ``max_units_per_worker``, a worker is told to + stop after that many units and a fresh one takes its place, so memory that + an engine leaves behind does not build up. The replacement starts only after + the old worker has exited, so no more than ``workers`` processes are ever + alive at once; a worker that has not exited ``_STOP_SECONDS`` after being + told to stop is killed. The pool manages its own processes, so worker replacement has none of the interpreter restrictions of ``ProcessPoolExecutor(max_tasks_per_child=...)``. * **A memory cap per worker.** With ``memory_cap_bytes``, a thread in the - parent reads each worker's memory every ``memory_poll_seconds`` and stops a - worker that goes over the cap. The reading is the process's footprint: its - resident memory plus pages the operating system has compressed (macOS) or - swapped out (Linux), from :func:`process_memory_bytes`. + parent reads each worker's memory every ``memory_poll_seconds`` and kills a + worker that goes over the cap. The parent also reads a worker's memory when + it returns a result, and replaces a worker that is over the cap then, before + giving it another unit, so memory one unit leaves behind is not charged to + the next. The reading is the process's footprint: its resident memory plus + pages the operating system has compressed (macOS) or swapped out (Linux), + from :func:`process_memory_bytes`. * **Running a failed unit again.** A unit whose worker exits before returning its result (a crash, the operating system killing it, the memory cap) or whose unit function raises ``MemoryError`` runs again in a fresh worker, up to ``max_attempts`` attempts in all. Any other exception from the unit - function stops the run at once: the same inputs would raise it again. + function, and a unit or result that cannot be pickled or unpickled, stops + the run at once: the same inputs would fail again. * **Results in unit order.** :meth:`WorkerPool.map` yields results in the order of its units, whatever order the workers finish in. At most ``max_units_ahead`` units, counted from the oldest result not yet handed back, are running or waiting with a finished result, which bounds the - results the parent holds. + results the parent holds. Workers are given new units only while the caller + is asking ``map`` for its next result. * **A worker environment.** ``worker_environment`` sets environment variables in each worker as it starts, before the worker imports anything, so a caller can, for example, give workers different numeric thread counts from the parent's. The pool chooses no values; without it, workers inherit the - parent's environment. + parent's environment. The values are held in the parent's own environment + while each worker starts, so another thread of the parent that reads the + environment, or starts a subprocess, at that moment sees them too. +* **No orphaned workers.** Each worker exits as soon as its parent process + dies, even in the middle of a unit; a pool that is garbage-collected or left + open at interpreter exit kills its workers. The pool decides nothing about sizing: the caller sets the number of workers and the memory cap. A unit function must not start ``multiprocessing`` child -processes, because the workers are daemonic. +processes, because the workers are daemonic. A worker start imports this +module, and so the ``microcosm.build`` package and what it imports. + +On Linux a worker is killed through a process file descriptor (``pidfd``), so +a kill can never reach another process that has been given the same process +ID. On macOS the pool kills by process ID: it checks first that the worker has +not exited, and the parent reaps workers only under the lock the memory thread +holds, but other code in the parent that reaps child processes (another +``multiprocessing.Process.start``, ``multiprocessing.active_children()``) +leaves a window of microseconds in which the ID could be reused. """ from __future__ import annotations @@ -65,10 +86,9 @@ import time import traceback import weakref -from collections import deque from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from contextlib import contextmanager -from dataclasses import dataclass +from dataclasses import dataclass, field from multiprocessing.connection import wait as wait_for_any from multiprocessing.reduction import ForkingPickler @@ -85,9 +105,13 @@ #: The longest the parent waits for a worker message before it checks the #: workers again. _WAIT_SECONDS = 0.5 -#: How long :meth:`WorkerPool.close` waits for a stopped worker to exit before -#: killing it. +#: How long a worker told to stop may take to exit before it is killed. +_STOP_SECONDS = 10.0 +#: How long :meth:`WorkerPool.close` waits for its workers to exit before it +#: kills them. _SHUTDOWN_SECONDS = 10.0 +#: The exit code of a worker that stopped because its parent died. +_PARENT_GONE_EXIT_CODE = 75 # Environment changes for a worker start are made in this process's own # environment, so two pools starting workers at once must take turns. @@ -99,6 +123,19 @@ def _require_positive_integer(name: str, value: object) -> None: raise ValueError(f"{name} must be a positive integer; got {value!r}.") +def _environment_entry_is_valid(key: object, value: object) -> bool: + if not isinstance(key, str) or not isinstance(value, str): + return False + if not key or "=" in key or "\0" in key or "\0" in value: + return False + try: + os.fsencode(key) + os.fsencode(value) + except UnicodeEncodeError: + return False + return True + + @dataclass(frozen=True) class WorkerPoolSettings: """How many workers to run and the limits each one runs under. @@ -111,6 +148,8 @@ class WorkerPoolSettings: keeps each worker for the whole run. max_attempts: Attempts in all for a unit whose worker fails (see the module docstring); the run stops when a unit fails this many times. + Also the number of worker starts in a row that may fail before the + run stops. max_units_ahead: Units, counted from the oldest result not yet handed back, that may be running or waiting with a finished result. ``None`` means twice ``workers``. @@ -147,17 +186,11 @@ def __post_init__(self) -> None: if self.worker_environment is not None: environment = dict(self.worker_environment) for key, value in environment.items(): - if ( - not isinstance(key, str) - or not key - or "=" in key - or "\0" in key - or not isinstance(value, str) - or "\0" in value - ): + if not _environment_entry_is_valid(key, value): raise ValueError( "worker_environment must map variable names to string " - f"values; got {key!r}: {value!r}." + "values the operating system can encode; got " + f"{key!r}: {value!r}." ) object.__setattr__(self, "worker_environment", environment) @@ -192,6 +225,8 @@ class WorkerPoolReport: max_live_workers: The most worker processes alive at once. peak_worker_memory_bytes: The highest memory footprint read from any worker, or ``None`` before the first reading. + workers_stopped_over_cap: Workers replaced because they were over the + memory cap after returning a result, without a unit being charged. """ worker_starts: int @@ -199,6 +234,7 @@ class WorkerPoolReport: failed_attempts: tuple[FailedAttempt, ...] max_live_workers: int peak_worker_memory_bytes: int | None + workers_stopped_over_cap: int class WorkerPoolError(RuntimeError): @@ -338,8 +374,28 @@ def _send_quietly(connection, message) -> bool: return True +def _exit_when_parent_dies() -> None: + """End this worker as soon as its parent process dies. + + A spawned worker holds the read end of a pipe whose write end only its + parent holds, so the pipe reads as closed exactly when the parent has + gone. Without this, a busy worker would run its unit to the end after its + parent was killed. + """ + parent = multiprocessing.parent_process() + if parent is None: # pragma: no cover - a pool worker always has a parent + return + + def watch() -> None: + wait_for_any([parent.sentinel]) + os._exit(_PARENT_GONE_EXIT_CODE) + + threading.Thread(target=watch, name="worker-pool-parent", daemon=True).start() + + def _worker_main(connection, initializer, initargs, unit_function) -> None: """Run in each worker: start up once, then run units until told to stop.""" + _exit_when_parent_dies() try: state = None if initializer is None else initializer(*initargs) except Exception as error: @@ -352,6 +408,13 @@ def _worker_main(connection, initializer, initargs, unit_function) -> None: message = connection.recv() except (EOFError, OSError): return + except Exception as error: + # The unit could not be unpickled here; the parent knows which. + if not _send_quietly( + connection, ("receive_error", _summary(error), _formatted(error)) + ): + return + continue if message is None: return index, unit = message @@ -392,15 +455,34 @@ def _worker_main(connection, initializer, initargs, unit_function) -> None: class _Worker: process: multiprocessing.process.BaseProcess connection: object + pid: int + pidfd: int | None = None ready: bool = False unit_index: int | None = None units_run: int = 0 retiring: bool = False + stop_deadline: float | None = None connection_lost: bool = False + stopped_over_cap: bool = False + exited: bool = False - @property - def pid(self) -> int | None: - return self.process.pid + +@dataclass(eq=False) +class _PoolState: + """What the pool, its memory thread and its finalizer share. + + The memory thread and the finalizer hold this, not the pool, so a pool + nobody refers to any more can be garbage-collected and its finalizer can + stop the workers. Every change to ``workers``, every kill and every reap + happens under ``lock``. + """ + + lock: threading.Lock = field(default_factory=threading.Lock) + workers: list[_Worker] = field(default_factory=list) + cap_overruns: dict[int, int] = field(default_factory=dict) + stop: threading.Event = field(default_factory=threading.Event) + peak_memory: int | None = None + workers_stopped_over_cap: int = 0 @dataclass(eq=False) @@ -412,10 +494,62 @@ class _Run: causes: list[list[str]] results: dict[int, object] retries: list[int] - undispatched: deque[int] start_failures: list[str] +def _has_exited(worker: _Worker) -> bool: + """True once the worker's process has exited, whoever reaped it.""" + return bool(wait_for_any([worker.process.sentinel], timeout=0)) + + +def _kill(worker: _Worker) -> None: + """Kill a worker that has not exited; call with the state's lock held.""" + if worker.exited or _has_exited(worker): + return + try: + if worker.pidfd is not None: + signal.pidfd_send_signal(worker.pidfd, signal.SIGKILL) + else: + os.kill(worker.pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def _shut_down(state: _PoolState) -> None: + """Kill every worker; run when a pool is collected or at interpreter exit.""" + state.stop.set() + with state.lock: + workers = list(state.workers) + for worker in workers: + _kill(worker) + for worker in workers: + try: + worker.process.join(_SHUTDOWN_SECONDS) + except (OSError, ValueError, AssertionError): + pass + + +def _watch_memory(state: _PoolState, cap: int | None, interval: float) -> None: + """The memory thread: read each worker's footprint, kill one over the cap.""" + while not state.stop.wait(interval): + with state.lock: + targets = [worker for worker in state.workers if not worker.exited] + for worker in targets: + observed = process_memory_bytes(worker.pid) + if observed is None: + continue + with state.lock: + # A worker still listed has not been reaped by the pool, so its + # process ID is still its own. + if worker not in state.workers or worker.exited or _has_exited(worker): + continue + if state.peak_memory is None or observed > state.peak_memory: + state.peak_memory = observed + if cap is not None and observed > cap: + state.cap_overruns.setdefault(worker.pid, observed) + _kill(worker) + + @contextmanager def _environment_for_start(environment: Mapping[str, str] | None) -> Iterator[None]: """Hold ``environment`` in this process's environment while a worker starts. @@ -430,8 +564,9 @@ def _environment_for_start(environment: Mapping[str, str] | None) -> Iterator[No return with _ENVIRONMENT_LOCK: previous = {name: os.environ.get(name) for name in environment} - os.environ.update(environment) try: + for name, value in environment.items(): + os.environ[name] = value yield finally: for name, value in previous.items(): @@ -444,18 +579,33 @@ def _environment_for_start(environment: Mapping[str, str] | None) -> Iterator[No def _require_importable(name: str, function: Callable) -> None: if not callable(function): raise TypeError(f"{name} must be callable; got {function!r}.") - try: - pickle.dumps(function) - except (pickle.PicklingError, AttributeError, TypeError) as error: + problem = None + if getattr(function, "__module__", None) == "__main__": + main = sys.modules.get("__main__") + spec = getattr(main, "__spec__", None) + if ( + getattr(main, "__file__", None) is None + and getattr(spec, "name", None) is None + ): + # Spawn re-imports the parent's main module from its file or its + # module name; a ``python -c`` command or a REPL has neither. + problem = "its module is a __main__ that spawned workers cannot import" + if problem is None: + try: + pickle.dumps(function) + except (pickle.PicklingError, AttributeError, TypeError) as error: + problem = str(error) + if problem is not None: raise TypeError( f"{name} must be importable by name in a spawned worker, such as a " - f"module-level function; got {function!r} ({error})." - ) from None + f"module-level function in a module file; got {function!r} " + f"({problem})." + ) def _exit_cause(exitcode: int | None) -> str: if exitcode is None: - return "the worker's connection to the parent closed" + return "the worker exited; its exit status was collected elsewhere" if exitcode < 0: try: name = signal.Signals(-exitcode).name @@ -471,17 +621,6 @@ def _gibibytes(count: int) -> str: return f"{count / 1024**3:.2f} GiB" -def _stop_processes(workers: list[_Worker]) -> None: - """Kill any workers still alive; run when a pool is collected or at exit.""" - for worker in list(workers): - try: - if worker.process.exitcode is None: - worker.process.kill() - worker.process.join(_SHUTDOWN_SECONDS) - except (OSError, ValueError, AssertionError): - pass - - class WorkerPool: """Spawned worker processes that run units and return results in order. @@ -497,11 +636,12 @@ class WorkerPool: ... ``initializer`` and ``unit_function`` must be importable by name in a - fresh interpreter (module-level functions). ``describe_unit(index, unit)`` - labels a unit in errors; it runs only in the parent. ``map`` may be called - again once the previous ``map`` has finished, and reuses the live workers. - A ``map`` that does not run to the end, because a unit failed or the - caller stopped iterating, closes the pool. + fresh interpreter (module-level functions in a module file). + ``describe_unit(index, unit)`` labels a unit in errors; it runs only in the + parent. ``map`` may be called again once the previous ``map`` has handed + back its last result, and reuses the live workers. A ``map`` stopped + before its last result, because a unit failed or the caller stopped + iterating, closes the pool. """ def __init__( @@ -529,22 +669,15 @@ def __init__( self._initargs = tuple(initargs) self._describe_unit = describe_unit self._context = multiprocessing.get_context("spawn") - # Every reap, start and kill of a worker process happens under this - # lock, so the memory thread never signals a process the parent has - # already reaped. - self._lock = threading.Lock() - self._workers: list[_Worker] = [] - self._cap_overruns: dict[int, int] = {} + self._shared = _PoolState() self._closed = False self._mapping = False self._worker_starts = 0 self._units_completed = 0 self._failed_attempts: list[FailedAttempt] = [] self._max_live_workers = 0 - self._peak_memory: int | None = None self._monitor: threading.Thread | None = None - self._monitor_stop = threading.Event() - self._finalizer = weakref.finalize(self, _stop_processes, self._workers) + self._finalizer = weakref.finalize(self, _shut_down, self._shared) # -- public ------------------------------------------------------------ @@ -555,13 +688,14 @@ def __exit__(self, *exc_info) -> None: self.close() def report(self) -> WorkerPoolReport: - with self._lock: + with self._shared.lock: return WorkerPoolReport( worker_starts=self._worker_starts, units_completed=self._units_completed, failed_attempts=tuple(self._failed_attempts), max_live_workers=self._max_live_workers, - peak_worker_memory_bytes=self._peak_memory, + peak_worker_memory_bytes=self._shared.peak_memory, + workers_stopped_over_cap=self._shared.workers_stopped_over_cap, ) def map(self, units: Iterable[object]) -> Iterator[object]: @@ -570,14 +704,21 @@ def map(self, units: Iterable[object]) -> Iterator[object]: raise WorkerPoolError("The worker pool is closed.") if self._mapping: raise WorkerPoolError("The worker pool is already running a map.") + units = list(units) self._mapping = True - finished = False + delivered_all = False try: - yield from self._run(list(units)) - finished = True + for index, result in self._run(units): + if index == len(units) - 1: + # Every result is out: the map is over even if the caller + # never asks for more, so the pool stays usable. + delivered_all = True + self._mapping = False + yield result + delivered_all = True finally: self._mapping = False - if not finished: + if not delivered_all: self.close() def close(self) -> None: @@ -585,30 +726,32 @@ def close(self) -> None: if self._closed: return self._closed = True - self._monitor_stop.set() + shared = self._shared + shared.stop.set() if self._monitor is not None: self._monitor.join() - with self._lock: - workers = list(self._workers) + with shared.lock: + workers = list(shared.workers) for worker in workers: if ( worker.ready and worker.unit_index is None + and not worker.retiring and not worker.connection_lost ): - if not worker.retiring: - self._send_stop(worker) - else: - with self._lock: - worker.process.kill() + self._send_stop(worker) + elif not worker.retiring: + with shared.lock: + _kill(worker) deadline = time.monotonic() + _SHUTDOWN_SECONDS for worker in workers: - with self._lock: - worker.process.join(max(0.0, deadline - time.monotonic())) - if worker.process.exitcode is None: - worker.process.kill() - worker.process.join(_SHUTDOWN_SECONDS) + remaining = max(0.0, deadline - time.monotonic()) + wait_for_any([worker.process.sentinel], timeout=remaining) + with shared.lock: + _kill(worker) + wait_for_any([worker.process.sentinel], timeout=_SHUTDOWN_SECONDS) self._forget(worker) + self._finalizer.detach() # -- running units ------------------------------------------------------ @@ -617,7 +760,7 @@ def _label(self, units: Sequence[object], index: int) -> str: return str(self._describe_unit(index, units[index])) return f"unit {index + 1}/{len(units)}" - def _run(self, units: list[object]) -> Iterator[object]: + def _run(self, units: list[object]) -> Iterator[tuple[int, object]]: count = len(units) if count == 0: return @@ -629,24 +772,24 @@ def _run(self, units: list[object]) -> Iterator[object]: causes=[[] for _ in range(count)], results={}, retries=[], - undispatched=deque(range(count)), start_failures=[], ) - next_index = 0 + next_new = 0 # The first unit not yet sent to any worker. + next_index = 0 # The next result to hand back. while next_index < count: - while next_index in run.results: + if self._closed: + raise WorkerPoolError("The worker pool is closed.") + if next_index in run.results: result = run.results.pop(next_index) next_index += 1 - yield result + yield next_index - 1, result del result - if next_index >= count: - break - window_end = next_index + settings.units_ahead - waiting = len(run.retries) + sum( - 1 for index in run.undispatched if index < window_end - ) + continue + window_end = min(count, next_index + settings.units_ahead) + waiting = len(run.retries) + max(0, window_end - next_new) + self._kill_workers_past_their_stop_deadline() self._start_workers(waiting) - for worker in list(self._workers): + for worker in list(self._shared.workers): if ( not worker.ready or worker.retiring @@ -656,8 +799,9 @@ def _run(self, units: list[object]) -> Iterator[object]: continue if run.retries: index = heapq.heappop(run.retries) - elif run.undispatched and run.undispatched[0] < window_end: - index = run.undispatched.popleft() + elif next_new < window_end: + index = next_new + next_new += 1 else: break if not self._send_unit(worker, index, run): @@ -668,7 +812,7 @@ def _unit_failed(self, run: _Run, index: int, pid: int | None, cause: str) -> No """Record a failed attempt; queue the unit again or stop the run.""" label = self._label(run.units, index) run.causes[index].append(cause) - with self._lock: + with self._shared.lock: self._failed_attempts.append( FailedAttempt(index, label, run.attempts[index], pid, cause) ) @@ -685,15 +829,37 @@ def _unit_failed(self, run: _Run, index: int, pid: int | None, cause: str) -> No ) heapq.heappush(run.retries, index) + def _stop_the_run( + self, run: _Run, index: int, pid: int | None, summary: str, text: str | None + ) -> None: + """Stop at once on a failure the same inputs would repeat.""" + label = self._label(run.units, index) + run.causes[index].append(summary) + with self._shared.lock: + self._failed_attempts.append( + FailedAttempt(index, label, run.attempts[index], pid, summary) + ) + error = WorkerPoolUnitError( + f"{label} failed in worker {pid}: {summary}", + unit_index=index, + label=label, + causes=run.causes[index], + ) + if text is None: + raise error + raise error from _RemoteTracebackError(text) + def _start_workers(self, waiting: int) -> None: available = sum( 1 - for worker in self._workers + for worker in self._shared.workers if not worker.retiring and not worker.connection_lost and worker.unit_index is None ) - while available < waiting and len(self._workers) < self._settings.workers: + while ( + available < waiting and len(self._shared.workers) < self._settings.workers + ): self._start_worker() available += 1 @@ -705,17 +871,32 @@ def _start_worker(self) -> None: name=f"worker-pool-{self._worker_starts + 1}", daemon=True, ) + # Not under the state's lock: with spawn, ``start`` blocks until the + # worker has read its start-up data, which can take as long as the + # worker's imports, and the memory thread needs the lock meanwhile. try: - with self._lock, _environment_for_start(self._settings.worker_environment): + with _environment_for_start(self._settings.worker_environment): process.start() - self._workers.append(_Worker(process=process, connection=parent_end)) - self._worker_starts += 1 - self._max_live_workers = max(self._max_live_workers, len(self._workers)) except Exception as error: parent_end.close() raise WorkerPoolError(f"A worker could not be started: {error}") from error finally: child_end.close() + pidfd = None + if hasattr(os, "pidfd_open"): + try: + pidfd = os.pidfd_open(process.pid) + except OSError: + pidfd = None + worker = _Worker( + process=process, connection=parent_end, pid=process.pid, pidfd=pidfd + ) + with self._shared.lock: + self._shared.workers.append(worker) + self._worker_starts += 1 + self._max_live_workers = max( + self._max_live_workers, len(self._shared.workers) + ) def _send_unit(self, worker: _Worker, index: int, run: _Run) -> bool: """Send a unit to an idle worker; False if the worker has gone.""" @@ -741,34 +922,48 @@ def _send_unit(self, worker: _Worker, index: int, run: _Run) -> bool: def _send_stop(self, worker: _Worker) -> None: worker.retiring = True + worker.stop_deadline = time.monotonic() + _STOP_SECONDS try: worker.connection.send(None) except OSError: worker.connection_lost = True + def _kill_workers_past_their_stop_deadline(self) -> None: + now = time.monotonic() + with self._shared.lock: + for worker in self._shared.workers: + if worker.stop_deadline is not None and now >= worker.stop_deadline: + _kill(worker) + def _wait_and_handle(self, run: _Run) -> None: - by_connection = { - worker.connection: worker - for worker in self._workers - if not worker.connection_lost - } - by_sentinel = {worker.process.sentinel: worker for worker in self._workers} - ready = wait_for_any([*by_connection, *by_sentinel], timeout=_WAIT_SECONDS) - touched: list[_Worker] = [] - for item in ready: - worker = by_connection.get(item) or by_sentinel.get(item) - if worker is not None and worker not in touched: - touched.append(worker) - for worker in touched: - self._drain(worker, run) - for worker in list(self._workers): - with self._lock: - exitcode = worker.process.exitcode - if exitcode is None: - continue - # Messages sent just before the worker exited come first. - self._drain(worker, run) - self._worker_exited(worker, exitcode, run) + workers = list(self._shared.workers) + timeout = _WAIT_SECONDS + now = time.monotonic() + for worker in workers: + if worker.stop_deadline is not None: + timeout = min(timeout, max(0.0, worker.stop_deadline - now)) + connections = [ + worker.connection for worker in workers if not worker.connection_lost + ] + sentinels = [worker.process.sentinel for worker in workers] + ready = wait_for_any([*connections, *sentinels], timeout=timeout) + ready_connections = [item for item in ready if not isinstance(item, int)] + ready_sentinels = {item for item in ready if isinstance(item, int)} + for worker in workers: + if any(item is worker.connection for item in ready_connections): + self._drain(worker, run) + for worker in workers: + if worker.process.sentinel in ready_sentinels: + # Messages sent just before the worker exited come first. + self._drain(worker, run) + self._worker_exited(worker, self._reap(worker), run) + + def _reap(self, worker: _Worker) -> int | None: + """The exit code of a worker whose process has exited, once reaped.""" + with self._shared.lock: + worker.process.join(0.1) + worker.exited = True + return worker.process.exitcode def _drain(self, worker: _Worker, run: _Run) -> None: while not worker.connection_lost: @@ -779,6 +974,21 @@ def _drain(self, worker: _Worker, run: _Run) -> None: except (EOFError, OSError): worker.connection_lost = True return + except Exception as error: + worker.connection_lost = True + if worker.unit_index is None: + raise WorkerPoolError( + f"A message from worker {worker.pid} could not be read: " + f"{_summary(error)}" + ) from error + self._stop_the_run( + run, + worker.unit_index, + worker.pid, + "it returned a result that could not be read in the parent: " + f"{_summary(error)}", + _formatted(error), + ) self._handle(worker, message, run) def _handle(self, worker: _Worker, message: tuple, run: _Run) -> None: @@ -801,39 +1011,60 @@ def _handle(self, worker: _Worker, message: tuple, run: _Run) -> None: run.results[index] = result worker.unit_index = None worker.units_run += 1 - with self._lock: + with self._shared.lock: self._units_completed += 1 + self._replace_if_over_cap(worker) limit = self._settings.max_units_per_worker - if limit is not None and worker.units_run >= limit: + if not worker.retiring and limit is not None and worker.units_run >= limit: self._send_stop(worker) + elif kind == "receive_error": + _, summary, text = message + if worker.unit_index is None: + raise WorkerPoolError( + f"Worker {worker.pid} could not read a message: {summary}" + ) from _RemoteTracebackError(text) + self._stop_the_run( + run, + worker.unit_index, + worker.pid, + f"the worker could not unpickle the unit: {summary}", + text, + ) elif kind == "error": _, index, summary, text = message - label = self._label(run.units, index) - run.causes[index].append(summary) - with self._lock: - self._failed_attempts.append( - FailedAttempt( - index, label, run.attempts[index], worker.pid, summary - ) - ) - raise WorkerPoolUnitError( - f"{label} failed in worker {worker.pid}: {summary}", - unit_index=index, - label=label, - causes=run.causes[index], - ) from _RemoteTracebackError(text) + self._stop_the_run(run, index, worker.pid, summary, text) elif kind == "memory_error": _, index, summary, _text = message worker.unit_index = None worker.retiring = True + worker.stop_deadline = time.monotonic() + _STOP_SECONDS self._unit_failed(run, index, worker.pid, summary) else: # pragma: no cover - the worker sends only the kinds above raise WorkerPoolError(f"Worker {worker.pid} sent {kind!r}.") - def _worker_exited(self, worker: _Worker, exitcode: int, run: _Run) -> None: + def _replace_if_over_cap(self, worker: _Worker) -> None: + """Retire a worker over the cap now, before it is given another unit.""" + cap = self._settings.memory_cap_bytes + if cap is None: + return + observed = process_memory_bytes(worker.pid) + if observed is None or observed <= cap: + return + shared = self._shared + with shared.lock: + if shared.peak_memory is None or observed > shared.peak_memory: + shared.peak_memory = observed + if not worker.stopped_over_cap: + worker.stopped_over_cap = True + shared.workers_stopped_over_cap += 1 + worker.retiring = True + worker.stop_deadline = time.monotonic() + _kill(worker) + + def _worker_exited(self, worker: _Worker, exitcode: int | None, run: _Run) -> None: pid = worker.pid - with self._lock: - overrun = self._cap_overruns.pop(pid, None) + with self._shared.lock: + overrun = self._shared.cap_overruns.pop(pid, None) if overrun is not None: cause = ( f"the worker went over its memory cap of " @@ -856,13 +1087,26 @@ def _worker_exited(self, worker: _Worker, exitcode: int, run: _Run) -> None: ) def _forget(self, worker: _Worker) -> None: - with self._lock: - if worker in self._workers: - self._workers.remove(worker) + with self._shared.lock: + if worker in self._shared.workers: + self._shared.workers.remove(worker) + worker.exited = True + self._shared.cap_overruns.pop(worker.pid, None) + if worker.pidfd is not None: + os.close(worker.pidfd) + worker.pidfd = None try: worker.process.join(0) if worker.process.exitcode is not None: worker.process.close() + elif _has_exited(worker): + # Something else collected its exit status (for example a + # SIGCHLD handler set to SIG_IGN), so multiprocessing can + # never learn it and would list the process as running + # for ever. + children = getattr(multiprocessing.process, "_children", None) + if isinstance(children, set): + children.discard(worker.process) except ValueError: pass try: @@ -876,31 +1120,13 @@ def _start_monitor(self) -> None: if self._monitor is not None or not _memory_reading_supported(): return self._monitor = threading.Thread( - target=self._watch_memory, name="worker-pool-memory", daemon=True + target=_watch_memory, + args=( + self._shared, + self._settings.memory_cap_bytes, + self._settings.memory_poll_seconds, + ), + name="worker-pool-memory", + daemon=True, ) self._monitor.start() - - def _watch_memory(self) -> None: - cap = self._settings.memory_cap_bytes - while not self._monitor_stop.wait(self._settings.memory_poll_seconds): - with self._lock: - targets = [(worker, worker.process.pid) for worker in self._workers] - for worker, pid in targets: - if pid is None: - continue - observed = process_memory_bytes(pid) - if observed is None: - continue - with self._lock: - # A worker still listed has not been reaped or closed, so - # its pid is still its own. - if ( - worker not in self._workers - or worker.process.exitcode is not None - ): - continue - if self._peak_memory is None or observed > self._peak_memory: - self._peak_memory = observed - if cap is not None and observed > cap: - self._cap_overruns.setdefault(pid, observed) - worker.process.kill() diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py index 67722c489e..b629879293 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -2,6 +2,7 @@ from __future__ import annotations +import contextlib import gc import multiprocessing import os @@ -350,14 +351,18 @@ def test_the_memory_cap_is_enforced_while_another_worker_starts(monkeypatch) -> """ pool = WorkerPool(WorkerPoolSettings(workers=1), unit_function=units.echo) starts_under_lock = [] - real_process = pool._context.Process + real_environment_for_start = worker_pool_module._environment_for_start - class RecordingProcess(real_process): - def start(self): - starts_under_lock.append(pool._shared.lock.locked()) - return super().start() + @contextlib.contextmanager + def recording_environment_for_start(environment): + # Entered around ``process.start()`` in the pool's worker start. + starts_under_lock.append(pool._shared.lock.locked()) + with real_environment_for_start(environment): + yield - monkeypatch.setattr(pool._context, "Process", RecordingProcess) + monkeypatch.setattr( + worker_pool_module, "_environment_for_start", recording_environment_for_start + ) with pool: list(pool.map([0])) assert starts_under_lock == [False] diff --git a/test_support/microcosm_build/worker_pool_identity.py b/test_support/microcosm_build/worker_pool_identity.py index 6e7faba92b..cdbd2886b1 100644 --- a/test_support/microcosm_build/worker_pool_identity.py +++ b/test_support/microcosm_build/worker_pool_identity.py @@ -5,12 +5,14 @@ and calls :func:`assert_identical_across_worker_counts`. The helper runs it at each worker count and compares canonical bytes, not values: -* arrays by dtype, shape and raw bytes, so ``0.0`` and ``-0.0``, NaNs with - different bits, and ``int32`` and ``int64`` all count as different; -* floats by their IEEE 754 bits; +* arrays by type, dtype (with its byte order and any fields), shape and raw + bytes, so ``0.0`` and ``-0.0``, NaNs with different bits, and ``int32`` and + ``int64`` all count as different; masked arrays by their mask too; +* every other value with its type, and floats by their IEEE 754 bits; * mappings with their keys in order, since a payload written to JSON keeps that order; -* tuples, lists, dataclasses and pandas objects by type and contents. +* tuples, lists, dataclasses and pandas objects by type and contents, pandas + objects with their dtypes (a categorical's categories) and index names. A difference is reported by its place in the result, such as ``result['totals'][3]``. @@ -36,6 +38,16 @@ def _type_name(value: object) -> bytes: return f"{kind.__module__}.{kind.__qualname__}".encode() +def _dtype_bytes(dtype: np.dtype) -> bytes: + """A dtype with its byte order and, for structured dtypes, its fields. + + ``dtype.str`` alone is ``|V8`` for every 8-byte structured dtype, so it + would lose field names, field types and their byte order. + """ + fields = dtype.descr if dtype.fields is not None or dtype.subdtype else None + return repr((dtype.str, fields)).encode() + + def _pandas_bytes(value: object) -> bytes | None: try: import pandas as pd @@ -43,26 +55,28 @@ def _pandas_bytes(value: object) -> bytes | None: return None if isinstance(value, pd.DataFrame): parts = [ - canonical_result_bytes(list(value.columns)), + canonical_result_bytes(value.columns), canonical_result_bytes(value.index), ] - for column in value.columns: - parts.append(canonical_result_bytes(value[column])) - return _framed(b"P", _type_name(value) + b"".join(parts)) + for position in range(value.shape[1]): + parts.append(canonical_result_bytes(value.iloc[:, position])) + return _framed(b"P", _framed(b"t", _type_name(value)) + b"".join(parts)) if isinstance(value, pd.Series): return _framed( b"P", - _type_name(value) + _framed(b"t", _type_name(value)) + canonical_result_bytes(value.name) - + canonical_result_bytes(str(value.dtype)) + # The dtype's repr carries a categorical's categories and order. + + canonical_result_bytes(repr(value.dtype)) + canonical_result_bytes(value.index) + canonical_result_bytes(np.asarray(value.to_numpy())), ) if isinstance(value, pd.Index): return _framed( b"P", - _type_name(value) - + canonical_result_bytes(str(value.dtype)) + _framed(b"t", _type_name(value)) + + canonical_result_bytes(list(value.names)) + + canonical_result_bytes(repr(value.dtype)) + canonical_result_bytes(np.asarray(value.to_numpy())), ) return None @@ -71,33 +85,50 @@ def _pandas_bytes(value: object) -> bytes | None: def canonical_result_bytes(value: object) -> bytes: """Bytes that are equal exactly when two results are bit-for-bit the same. + Every value carries its type, so ``True`` and ``np.True_``, an ``IntEnum`` + member and its ``int``, and ``bytes`` and ``bytearray`` differ. + Raises: TypeError: For a value of a type it has no encoding for. """ if value is None: return b"N" - if isinstance(value, bool | np.bool_): + if type(value) is bool: return b"B1" if value else b"B0" if isinstance(value, np.ndarray): - header = f"{value.dtype.str}{value.shape}".encode() + kind = _framed(b"t", _type_name(value)) + if isinstance(value, np.ma.MaskedArray): + return _framed( + b"K", + kind + + canonical_result_bytes(np.asarray(value.data)) + + canonical_result_bytes(np.ma.getmaskarray(value)) + + canonical_result_bytes(np.asarray(value.fill_value)), + ) + header = kind + _framed(b"d", _dtype_bytes(value.dtype)) + header += _framed(b"s", repr(value.shape).encode()) if value.dtype.hasobject: items = b"".join(canonical_result_bytes(item) for item in value.ravel()) - return _framed(b"O", _framed(b"h", header) + items) + return _framed(b"O", header + items) + return _framed(b"A", header + np.ascontiguousarray(value).tobytes()) + if isinstance(value, np.generic): return _framed( - b"A", _framed(b"h", header) + np.ascontiguousarray(value).tobytes() + b"S", _dtype_bytes(value.dtype) + b":" + np.asarray(value).tobytes() ) - if isinstance(value, np.generic): - return _framed(b"S", value.dtype.str.encode() + b":" + value.tobytes()) + kind = _framed(b"t", _type_name(value)) if isinstance(value, int): - return _framed(b"I", str(value).encode()) + return _framed(b"I", kind + str(int(value)).encode()) if isinstance(value, float): - return _framed(b"F", struct.pack(">d", value)) + return _framed(b"F", kind + struct.pack(">d", value)) if isinstance(value, complex): - return _framed(b"C", struct.pack(">dd", value.real, value.imag)) + return _framed(b"C", kind + struct.pack(">dd", value.real, value.imag)) if isinstance(value, str): - return _framed(b"U", value.encode("utf-8", "surrogatepass")) - if isinstance(value, bytes | bytearray | memoryview): - return _framed(b"Y", bytes(value)) + return _framed(b"U", kind + str.encode(value, "utf-8", "surrogatepass")) + if isinstance(value, memoryview): + layout = repr((value.format, value.shape)).encode() + return _framed(b"Y", kind + _framed(b"m", layout) + value.tobytes()) + if isinstance(value, bytes | bytearray): + return _framed(b"Y", kind + bytes(value)) pandas_bytes = _pandas_bytes(value) if pandas_bytes is not None: return pandas_bytes @@ -106,20 +137,20 @@ def canonical_result_bytes(value: object) -> bytes: canonical_result_bytes(key) + canonical_result_bytes(item) for key, item in value.items() ) - return _framed(b"M", _framed(b"t", _type_name(value)) + items) + return _framed(b"M", kind + items) if isinstance(value, tuple | list): items = b"".join(canonical_result_bytes(item) for item in value) - return _framed(b"L", _framed(b"t", _type_name(value)) + items) + return _framed(b"L", kind + items) if isinstance(value, set | frozenset): items = b"".join(sorted(canonical_result_bytes(item) for item in value)) - return _framed(b"E", _framed(b"t", _type_name(value)) + items) + return _framed(b"E", kind + items) if dataclasses.is_dataclass(value) and not isinstance(value, type): items = b"".join( canonical_result_bytes(field.name) + canonical_result_bytes(getattr(value, field.name)) for field in dataclasses.fields(value) ) - return _framed(b"D", _framed(b"t", _type_name(value)) + items) + return _framed(b"D", kind + items) raise TypeError( "canonical_result_bytes has no encoding for values of type " f"{type(value).__module__}.{type(value).__qualname__}." diff --git a/tools/score_us_release_head_to_head.py b/tools/score_us_release_head_to_head.py index b60f34ee77..2eabc7117d 100644 --- a/tools/score_us_release_head_to_head.py +++ b/tools/score_us_release_head_to_head.py @@ -104,7 +104,13 @@ support_channel_column, support_clone_index_column, ) -from microcosm.build.worker_pool import WorkerPool, WorkerPoolSettings +from microcosm.build.worker_pool import ( + WorkerPool, + WorkerPoolError, + WorkerPoolReport, + WorkerPoolSettings, + WorkerPoolUnitError, +) from microcosm.calibrate import TargetRegistry, score_targets from microcosm.calibrate.solve import relative_error_loss from microcosm.frame import US_SCHEMA, Frame @@ -1091,10 +1097,10 @@ def _score_slice_worker(state: _SliceWorkerState, task: tuple[int, int]) -> Scor gc.collect() _assert_rss_below_limit(f"after scoring {label}") return scored_slice - except MemoryError: - # The shared pool runs the slice again in a fresh worker. - raise except Exception as error: + # A RuntimeError, not the MemoryError the 20 GiB check raises, so the + # check stays fatal as in one process: the shared pool runs a slice + # again only when its worker dies. raise RuntimeError(f"{label} worker failed: {error}") from error @@ -1181,6 +1187,22 @@ def _reduce_scored_slices( ) +def _print_failed_attempts(report: WorkerPoolReport) -> None: + """Report each slice attempt that ended without a result on stderr. + + Operational receipts only, like the memory receipts; the JSON and Markdown + outputs stay byte-deterministic. + """ + for attempt in report.failed_attempts: + print( + f"[h2h {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}] " + f"{attempt.label}: attempt {attempt.attempt} ended without a result " + f"({attempt.cause})", + file=sys.stderr, + flush=True, + ) + + def _score_chunks_parallel( base_frame: Frame, specs: Sequence, @@ -1195,8 +1217,8 @@ def _score_chunks_parallel( The pool returns slice results in task order, so each chunk reduces its slices in the sequential order whatever order the workers finish in. A - slice whose worker dies or runs out of memory runs once more in a fresh - worker before the run stops. + slice whose worker dies runs once more in a fresh worker before the run + stops; each failed attempt is reported on stderr. """ slice_count = len( @@ -1261,8 +1283,16 @@ def chunk_results() -> Iterator[ScoredSlice]: chunk_label=f"chunk {chunk_index + 1}/{chunk_count}", maximum_microsim_batch_size=maximum_microsim_batch_size, ) + except WorkerPoolUnitError: + raise + except WorkerPoolError as error: + # A failure no slice carries, such as a worker failing to start. + raise WorkerPoolError( + f"{artifact_name} slice workers failed: {error}" + ) from error finally: results.close() + _print_failed_attempts(pool.report()) def _spec_keys(specs: Sequence) -> tuple[tuple[str, object], ...]: From 344b62d9a1c3b78c0bad67a1c238ffe64ae83712 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:45:02 +0400 Subject: [PATCH 06/16] Add failing tests for the second review round's pool findings A finished map's generator must not end a running map's turn; the pool must close cleanly from inside its memory thread while that thread holds the lock; a memory reading taken before a worker's current unit must not kill it; workers must use pipes; an idle worker must get its next unit while the caller holds a result; a handed-back result must not be kept while map waits; a stopped worker must be killed at its deadline between maps; a refused kill must not raise; the memory poll interval must be one a thread can wait for. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_worker_pool.py | 187 +++++++++++++++++- .../microcosm_build/worker_pool_units.py | 14 ++ 2 files changed, 199 insertions(+), 2 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py index b629879293..8f3ee780c0 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -7,12 +7,15 @@ import multiprocessing import os import signal +import stat import subprocess import sys +import threading import time +import weakref from collections import Counter from pathlib import Path -from types import ModuleType +from types import ModuleType, SimpleNamespace import numpy as np import pytest @@ -312,6 +315,8 @@ def test_closing_an_unfinished_map_stops_every_worker() -> None: {"memory_cap_bytes": 0}, {"max_units_ahead": 0}, {"memory_poll_seconds": 0.0}, + # Longer than a thread can wait for, which would end the memory thread. + {"memory_poll_seconds": 1e10}, ], ) def test_settings_refuse_values_that_cannot_run(setting) -> None: @@ -343,6 +348,22 @@ def test_process_memory_bytes_sees_this_process_grow() -> None: del held +def _held_by_another_thread(lock) -> bool: + """Whether a thread other than a fresh one holds ``lock`` (an RLock).""" + acquired = [] + + def try_to_acquire() -> None: + got = lock.acquire(timeout=0.05) + acquired.append(got) + if got: + lock.release() + + thread = threading.Thread(target=try_to_acquire) + thread.start() + thread.join() + return not acquired[0] + + def test_the_memory_cap_is_enforced_while_another_worker_starts(monkeypatch) -> None: """Starting a worker can block for as long as the worker takes to import. @@ -356,7 +377,7 @@ def test_the_memory_cap_is_enforced_while_another_worker_starts(monkeypatch) -> @contextlib.contextmanager def recording_environment_for_start(environment): # Entered around ``process.start()`` in the pool's worker start. - starts_under_lock.append(pool._shared.lock.locked()) + starts_under_lock.append(_held_by_another_thread(pool._shared.lock)) with real_environment_for_start(environment): yield @@ -551,6 +572,168 @@ def typed_at_the_prompt(state, unit): WorkerPool(WorkerPoolSettings(workers=1), unit_function=typed_at_the_prompt) +def test_a_finished_maps_generator_cannot_release_a_running_maps_turn() -> None: + with WorkerPool( + WorkerPoolSettings(workers=2), unit_function=units.sleep_then_return + ) as pool: + first = pool.map([(0, 0.0)]) + assert next(first) == 0 # Its last result: the map is over. + second = pool.map([(10, 0.0), (11, 2.0)]) + assert next(second) == 10 + first.close() # Must not end the second map's turn. + with pytest.raises(WorkerPoolError, match="already running"): + next(pool.map([(20, 0.0)])) + assert list(second) == [11] + + +def test_closing_from_inside_the_memory_thread_stops_every_worker(monkeypatch) -> None: + """A garbage collection can run in any thread, including the memory thread + while it holds the pool's lock, and close an abandoned map there.""" + pool = WorkerPool( + WorkerPoolSettings(workers=2, memory_poll_seconds=0.05), + unit_function=units.sleep_then_return, + ) + armed = threading.Event() + outcome: dict[str, str] = {} + real_has_exited = worker_pool_module._has_exited + + def has_exited(worker): + # Called by the memory thread with the pool's lock held. + if ( + armed.is_set() + and threading.current_thread().name == "worker-pool-memory" + and "close" not in outcome + ): + outcome["close"] = "started" + try: + pool.close() + outcome["close"] = "finished" + except BaseException as error: + outcome["close"] = repr(error) + return real_has_exited(worker) + + monkeypatch.setattr(worker_pool_module, "_has_exited", has_exited) + results = pool.map([(0, 0.0), (1, 30.0)]) + assert next(results) == 0 + armed.set() + deadline = time.monotonic() + 30 + while outcome.get("close") in (None, "started") and time.monotonic() < deadline: + time.sleep(0.05) + + assert outcome.get("close") == "finished" + assert multiprocessing.active_children() == [] + with pytest.raises(WorkerPoolError, match="closed"): + next(results) + + +def test_a_stale_memory_reading_does_not_kill_a_worker_on_a_later_unit( + monkeypatch, tmp_path +) -> None: + marker = tmp_path / "unit-0-started" + real_reading = worker_pool_module.process_memory_bytes + stale = threading.Event() + + def reading(pid): + if ( + threading.current_thread().name == "worker-pool-memory" + and marker.exists() + and not stale.is_set() + ): + # Read during unit 0, acted on after unit 1 has started. + stale.set() + time.sleep(1.5) + return 10 * 1024**3 + return real_reading(pid) + + monkeypatch.setattr(worker_pool_module, "process_memory_bytes", reading) + settings = WorkerPoolSettings( + workers=1, + memory_cap_bytes=400 * MIB, + memory_poll_seconds=0.05, + max_attempts=1, + ) + with WorkerPool(settings, unit_function=units.mark_then_sleep) as pool: + assert list(pool.map([(0, str(marker), 0.3), (1, "", 3.0)])) == [0, 1] + assert pool.report().failed_attempts == () + + +def test_workers_exchange_messages_over_pipes() -> None: + """Socket pairs carry large results several times slower on macOS.""" + with WorkerPool(WorkerPoolSettings(workers=1), unit_function=units.echo) as pool: + assert list(pool.map([0])) == [0] + (worker,) = pool._shared.workers + for end in (worker.to_worker, worker.from_worker): + assert stat.S_ISFIFO(os.fstat(end.fileno()).st_mode) + + +def test_an_idle_worker_gets_its_next_unit_while_the_caller_holds_a_result() -> None: + with WorkerPool( + WorkerPoolSettings(workers=1), unit_function=units.record_run_times + ) as pool: + results = pool.map([(0, 0.0), (1, 0.0)]) + next(results) + time.sleep(1.0) # The caller works on result 0. + resumed = time.monotonic() + (_, unit_one_started, _) = next(results) + + assert unit_one_started < resumed + + +def test_a_result_already_handed_back_is_not_kept_while_map_waits() -> None: + with WorkerPool( + WorkerPoolSettings(workers=1), unit_function=units.array_after_sleep + ) as pool: + results = pool.map([0.0, 2.0]) + first = next(results) + reference = weakref.ref(first) + del first + observed: dict[str, bool] = {} + timer = threading.Timer( + 1.0, lambda: observed.setdefault("alive", reference() is not None) + ) + timer.start() + next(results) + timer.join() + + assert observed == {"alive": False} + + +def test_a_stopped_worker_is_killed_at_its_deadline_between_maps(monkeypatch) -> None: + monkeypatch.setattr(worker_pool_module, "_STOP_SECONDS", 1.0) + with WorkerPool( + WorkerPoolSettings(workers=1, max_units_per_worker=1, memory_poll_seconds=0.1), + initializer=units.start_lingering_thread, + unit_function=units.echo, + ) as pool: + assert list(pool.map([0])) == [0] + (worker,) = pool._shared.workers # Told to stop; kept alive by a thread. + deadline = time.monotonic() + 20 + while ( + not worker_pool_module._has_exited(worker) and time.monotonic() < deadline + ): + time.sleep(0.1) + assert worker_pool_module._has_exited(worker) + + +def test_a_kill_the_operating_system_refuses_does_not_raise(monkeypatch) -> None: + def refuse(pid, signal_number): + raise PermissionError(1, "Operation not permitted") + + monkeypatch.setattr(worker_pool_module.os, "kill", refuse) + read_end, write_end = os.pipe() + try: + worker = SimpleNamespace( + exited=False, + pidfd=None, + pid=999_999, + process=SimpleNamespace(sentinel=read_end), + ) + worker_pool_module._kill(worker) + finally: + os.close(read_end) + os.close(write_end) + + # --------------------------------------------------------------------------- # The 1-vs-N byte-identity helper # --------------------------------------------------------------------------- diff --git a/test_support/microcosm_build/worker_pool_units.py b/test_support/microcosm_build/worker_pool_units.py index 746342692c..77eb41ab2e 100644 --- a/test_support/microcosm_build/worker_pool_units.py +++ b/test_support/microcosm_build/worker_pool_units.py @@ -181,3 +181,17 @@ def write_pid_then_sleep(state, unit): (Path(directory) / f"worker-{os.getpid()}").write_text("running") time.sleep(seconds) return os.getpid() + + +def mark_then_sleep(state, unit): + """Write ``marker`` (if given) when the unit starts, then sleep.""" + value, marker, seconds = unit + if marker: + Path(marker).write_text(str(os.getpid())) + time.sleep(seconds) + return value + + +def array_after_sleep(state, seconds): + time.sleep(seconds) + return np.ones(1_000) From 7cc6718256230d41c066d711abd67db704efacbe Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:48:00 +0400 Subject: [PATCH 07/16] Fix the second review round's pool findings Each map holds a token for its turn, so a finished map's generator closed late cannot end a later map's turn; the shared lock is reentrant and close() skips joining the memory thread from inside it, so a garbage collection there can close the pool; the memory thread records how many units a worker had been sent when it read the worker's memory and kills only if no new unit was sent since; it also kills stopped workers at their deadline between maps; workers use two one-way pipes instead of a socket pair; the main loop takes in finished work and hands out units before yielding a result it holds; map drops each result after yielding it; the poll interval must be one a thread can wait for; a result-time cap kill no longer makes the wait spin; kills the operating system refuses are given up on, not raised; shutdown closes pidfds and reaps under the lock. The docstring states the interpreter-lock limit of the parent-death exit and where process IDs can still be reused on macOS. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/worker_pool.py | 255 ++++++++++++------ 1 file changed, 179 insertions(+), 76 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/worker_pool.py b/packages/microcosm-build/src/microcosm/build/worker_pool.py index 7b669104fc..f15a398d4b 100644 --- a/packages/microcosm-build/src/microcosm/build/worker_pool.py +++ b/packages/microcosm-build/src/microcosm/build/worker_pool.py @@ -55,21 +55,29 @@ while each worker starts, so another thread of the parent that reads the environment, or starts a subprocess, at that moment sees them too. * **No orphaned workers.** Each worker exits as soon as its parent process - dies, even in the middle of a unit; a pool that is garbage-collected or left - open at interpreter exit kills its workers. + dies, even in the middle of a unit, once the unit lets other threads run: + Python and NumPy code does so often, but a long call into C code that holds + the interpreter lock delays the exit until it returns. A pool that is + garbage-collected or left open at interpreter exit kills its workers, and a + worker told to stop is killed at its deadline even between maps. The pool decides nothing about sizing: the caller sets the number of workers and the memory cap. A unit function must not start ``multiprocessing`` child processes, because the workers are daemonic. A worker start imports this module, and so the ``microcosm.build`` package and what it imports. +Messages travel over two one-way pipes per worker; socket pairs carry large +results several times slower on macOS. + On Linux a worker is killed through a process file descriptor (``pidfd``), so a kill can never reach another process that has been given the same process -ID. On macOS the pool kills by process ID: it checks first that the worker has -not exited, and the parent reaps workers only under the lock the memory thread -holds, but other code in the parent that reaps child processes (another -``multiprocessing.Process.start``, ``multiprocessing.active_children()``) -leaves a window of microseconds in which the ID could be reused. +ID. On macOS the pool kills by process ID, after checking under its lock that +the worker has not exited; the pool reaps its workers under the same lock. +But ``multiprocessing.Process.start`` reaps every exited child of the parent, +outside that lock, whenever it starts a process (including the pool's own +worker starts), and so does ``multiprocessing.active_children()``; that leaves +a window of microseconds in which a worker's process ID could be reused before +a kill lands. """ from __future__ import annotations @@ -179,9 +187,11 @@ def __post_init__(self) -> None: or not isinstance(seconds, int | float) or not math.isfinite(seconds) or seconds <= 0 + or seconds > threading.TIMEOUT_MAX ): raise ValueError( - f"memory_poll_seconds must be a positive number; got {seconds!r}." + "memory_poll_seconds must be a positive number of seconds a " + f"thread can wait for; got {seconds!r}." ) if self.worker_environment is not None: environment = dict(self.worker_environment) @@ -393,8 +403,11 @@ def watch() -> None: threading.Thread(target=watch, name="worker-pool-parent", daemon=True).start() -def _worker_main(connection, initializer, initargs, unit_function) -> None: - """Run in each worker: start up once, then run units until told to stop.""" +def _worker_main(receive, connection, initializer, initargs, unit_function) -> None: + """Run in each worker: start up once, then run units until told to stop. + + ``receive`` reads units from the parent; ``connection`` sends messages to it. + """ _exit_when_parent_dies() try: state = None if initializer is None else initializer(*initargs) @@ -405,7 +418,7 @@ def _worker_main(connection, initializer, initargs, unit_function) -> None: return while True: try: - message = connection.recv() + message = receive.recv() except (EOFError, OSError): return except Exception as error: @@ -454,16 +467,21 @@ def _worker_main(connection, initializer, initargs, unit_function) -> None: @dataclass(eq=False) class _Worker: process: multiprocessing.process.BaseProcess - connection: object + to_worker: object + from_worker: object pid: int pidfd: int | None = None ready: bool = False unit_index: int | None = None + #: Units sent to this worker so far: a memory reading taken before a later + #: unit was sent cannot be charged to that unit. + units_sent: int = 0 units_run: int = 0 retiring: bool = False stop_deadline: float | None = None connection_lost: bool = False stopped_over_cap: bool = False + killed: bool = False exited: bool = False @@ -474,10 +492,12 @@ class _PoolState: The memory thread and the finalizer hold this, not the pool, so a pool nobody refers to any more can be garbage-collected and its finalizer can stop the workers. Every change to ``workers``, every kill and every reap - happens under ``lock``. + the pool makes happens under ``lock``. It is reentrant because a garbage + collection can run a finalizer, or close an abandoned map, in whichever + thread is running, including the memory thread while it holds the lock. """ - lock: threading.Lock = field(default_factory=threading.Lock) + lock: threading.RLock = field(default_factory=threading.RLock) workers: list[_Worker] = field(default_factory=list) cap_overruns: dict[int, int] = field(default_factory=dict) stop: threading.Event = field(default_factory=threading.Event) @@ -499,22 +519,48 @@ class _Run: def _has_exited(worker: _Worker) -> bool: """True once the worker's process has exited, whoever reaped it.""" - return bool(wait_for_any([worker.process.sentinel], timeout=0)) + if worker.exited: + return True + try: + return bool(wait_for_any([worker.process.sentinel], timeout=0)) + except ValueError: + # The pool has closed the process object: it was reaped and forgotten. + return True def _kill(worker: _Worker) -> None: - """Kill a worker that has not exited; call with the state's lock held.""" + """Kill a worker that has not exited; call with the state's lock held. + + A kill the operating system refuses is given up on, not raised: this runs + in the memory thread and during shutdown, which must carry on. + """ if worker.exited or _has_exited(worker): return - try: - if worker.pidfd is not None: + if worker.pidfd is not None: + try: signal.pidfd_send_signal(worker.pidfd, signal.SIGKILL) - else: - os.kill(worker.pid, signal.SIGKILL) - except ProcessLookupError: + worker.killed = True + return + except ProcessLookupError: + return + except OSError: + pass # Fall back to the process ID below. + try: + os.kill(worker.pid, signal.SIGKILL) + worker.killed = True + except OSError: pass +def _close_pidfd(worker: _Worker) -> None: + if worker.pidfd is not None: + try: + os.close(worker.pidfd) + except OSError: + pass + worker.pidfd = None + + def _shut_down(state: _PoolState) -> None: """Kill every worker; run when a pool is collected or at interpreter exit.""" state.stop.set() @@ -522,19 +568,33 @@ def _shut_down(state: _PoolState) -> None: workers = list(state.workers) for worker in workers: _kill(worker) - for worker in workers: - try: - worker.process.join(_SHUTDOWN_SECONDS) - except (OSError, ValueError, AssertionError): - pass + for worker in workers: + try: + worker.process.join(_SHUTDOWN_SECONDS) + except (OSError, ValueError, AssertionError): + pass + worker.exited = True + _close_pidfd(worker) def _watch_memory(state: _PoolState, cap: int | None, interval: float) -> None: - """The memory thread: read each worker's footprint, kill one over the cap.""" + """The memory thread: read each worker's footprint and kill one over the cap. + + It also kills a worker told to stop that is still alive at its deadline, + whether or not a map is running. + """ while not state.stop.wait(interval): + now = time.monotonic() with state.lock: - targets = [worker for worker in state.workers if not worker.exited] - for worker in targets: + targets = [ + (worker, worker.units_sent) + for worker in state.workers + if not worker.exited + ] + for worker, _ in targets: + if worker.stop_deadline is not None and now >= worker.stop_deadline: + _kill(worker) + for worker, units_sent in targets: observed = process_memory_bytes(worker.pid) if observed is None: continue @@ -545,6 +605,9 @@ def _watch_memory(state: _PoolState, cap: int | None, interval: float) -> None: continue if state.peak_memory is None or observed > state.peak_memory: state.peak_memory = observed + if worker.units_sent != units_sent: + # Read before the worker was given its current unit. + continue if cap is not None and observed > cap: state.cap_overruns.setdefault(worker.pid, observed) _kill(worker) @@ -671,7 +734,8 @@ def __init__( self._context = multiprocessing.get_context("spawn") self._shared = _PoolState() self._closed = False - self._mapping = False + # The token of the map whose results are still to come, if any. + self._map_owner: object | None = None self._worker_starts = 0 self._units_completed = 0 self._failed_attempts: list[FailedAttempt] = [] @@ -702,10 +766,11 @@ def map(self, units: Iterable[object]) -> Iterator[object]: """Run ``unit_function(state, unit)`` for each unit; yield results in order.""" if self._closed: raise WorkerPoolError("The worker pool is closed.") - if self._mapping: + if self._map_owner is not None: raise WorkerPoolError("The worker pool is already running a map.") + token = object() + self._map_owner = token units = list(units) - self._mapping = True delivered_all = False try: for index, result in self._run(units): @@ -713,14 +778,21 @@ def map(self, units: Iterable[object]) -> Iterator[object]: # Every result is out: the map is over even if the caller # never asks for more, so the pool stays usable. delivered_all = True - self._mapping = False + self._release_map_turn(token) yield result + del result delivered_all = True finally: - self._mapping = False + # A finished map's generator may be closed after a later map + # began; only the map that holds the turn may give it up. + self._release_map_turn(token) if not delivered_all: self.close() + def _release_map_turn(self, token: object) -> None: + if self._map_owner is token: + self._map_owner = None + def close(self) -> None: """Stop every worker: idle ones are told to exit, busy ones are killed.""" if self._closed: @@ -728,7 +800,12 @@ def close(self) -> None: self._closed = True shared = self._shared shared.stop.set() - if self._monitor is not None: + # A garbage collection in the memory thread can close the pool there, + # and a thread cannot join itself. + if ( + self._monitor is not None + and self._monitor is not threading.current_thread() + ): self._monitor.join() with shared.lock: workers = list(shared.workers) @@ -745,11 +822,14 @@ def close(self) -> None: _kill(worker) deadline = time.monotonic() + _SHUTDOWN_SECONDS for worker in workers: - remaining = max(0.0, deadline - time.monotonic()) - wait_for_any([worker.process.sentinel], timeout=remaining) - with shared.lock: - _kill(worker) - wait_for_any([worker.process.sentinel], timeout=_SHUTDOWN_SECONDS) + try: + remaining = max(0.0, deadline - time.monotonic()) + wait_for_any([worker.process.sentinel], timeout=remaining) + with shared.lock: + _kill(worker) + wait_for_any([worker.process.sentinel], timeout=_SHUTDOWN_SECONDS) + except (OSError, ValueError): + pass self._forget(worker) self._finalizer.detach() @@ -779,12 +859,9 @@ def _run(self, units: list[object]) -> Iterator[tuple[int, object]]: while next_index < count: if self._closed: raise WorkerPoolError("The worker pool is closed.") - if next_index in run.results: - result = run.results.pop(next_index) - next_index += 1 - yield next_index - 1, result - del result - continue + # Take in finished results and exits without waiting, so idle + # workers get new units even while the caller holds a result. + self._wait_and_handle(run, block=False) window_end = min(count, next_index + settings.units_ahead) waiting = len(run.retries) + max(0, window_end - next_new) self._kill_workers_past_their_stop_deadline() @@ -806,7 +883,13 @@ def _run(self, units: list[object]) -> Iterator[tuple[int, object]]: break if not self._send_unit(worker, index, run): heapq.heappush(run.retries, index) - self._wait_and_handle(run) + if next_index in run.results: + result = run.results.pop(next_index) + next_index += 1 + yield next_index - 1, result + del result + continue + self._wait_and_handle(run, block=True) def _unit_failed(self, run: _Run, index: int, pid: int | None, cause: str) -> None: """Record a failed attempt; queue the unit again or stop the run.""" @@ -864,10 +947,20 @@ def _start_workers(self, waiting: int) -> None: available += 1 def _start_worker(self) -> None: - parent_end, child_end = self._context.Pipe(duplex=True) + # Two one-way pipes: socket pairs carry large results several times + # slower on macOS. + units_out, units_in = self._context.Pipe(duplex=False) + messages_out, messages_in = self._context.Pipe(duplex=False) + child_ends = (units_out, messages_in) process = self._context.Process( target=_worker_main, - args=(child_end, self._initializer, self._initargs, self._unit_function), + args=( + units_out, + messages_in, + self._initializer, + self._initargs, + self._unit_function, + ), name=f"worker-pool-{self._worker_starts + 1}", daemon=True, ) @@ -878,10 +971,12 @@ def _start_worker(self) -> None: with _environment_for_start(self._settings.worker_environment): process.start() except Exception as error: - parent_end.close() + units_in.close() + messages_out.close() raise WorkerPoolError(f"A worker could not be started: {error}") from error finally: - child_end.close() + for end in child_ends: + end.close() pidfd = None if hasattr(os, "pidfd_open"): try: @@ -889,7 +984,11 @@ def _start_worker(self) -> None: except OSError: pidfd = None worker = _Worker( - process=process, connection=parent_end, pid=process.pid, pidfd=pidfd + process=process, + to_worker=units_in, + from_worker=messages_out, + pid=process.pid, + pidfd=pidfd, ) with self._shared.lock: self._shared.workers.append(worker) @@ -912,19 +1011,21 @@ def _send_unit(self, worker: _Worker, index: int, run: _Run) -> bool: causes=[cause], ) from error try: - worker.connection.send_bytes(payload) + worker.to_worker.send_bytes(payload) except OSError: worker.connection_lost = True return False run.attempts[index] += 1 - worker.unit_index = index + with self._shared.lock: + worker.unit_index = index + worker.units_sent += 1 return True def _send_stop(self, worker: _Worker) -> None: worker.retiring = True worker.stop_deadline = time.monotonic() + _STOP_SECONDS try: - worker.connection.send(None) + worker.to_worker.send(None) except OSError: worker.connection_lost = True @@ -935,22 +1036,25 @@ def _kill_workers_past_their_stop_deadline(self) -> None: if worker.stop_deadline is not None and now >= worker.stop_deadline: _kill(worker) - def _wait_and_handle(self, run: _Run) -> None: + def _wait_and_handle(self, run: _Run, *, block: bool) -> None: + """Handle worker messages and exits; with ``block``, wait for one first.""" workers = list(self._shared.workers) - timeout = _WAIT_SECONDS - now = time.monotonic() - for worker in workers: - if worker.stop_deadline is not None: - timeout = min(timeout, max(0.0, worker.stop_deadline - now)) - connections = [ - worker.connection for worker in workers if not worker.connection_lost + timeout = 0.0 + if block: + timeout = _WAIT_SECONDS + now = time.monotonic() + for worker in workers: + if worker.stop_deadline is not None and not worker.killed: + timeout = min(timeout, max(0.0, worker.stop_deadline - now)) + receivers = [ + worker.from_worker for worker in workers if not worker.connection_lost ] sentinels = [worker.process.sentinel for worker in workers] - ready = wait_for_any([*connections, *sentinels], timeout=timeout) - ready_connections = [item for item in ready if not isinstance(item, int)] + ready = wait_for_any([*receivers, *sentinels], timeout=timeout) + ready_receivers = [item for item in ready if not isinstance(item, int)] ready_sentinels = {item for item in ready if isinstance(item, int)} for worker in workers: - if any(item is worker.connection for item in ready_connections): + if any(item is worker.from_worker for item in ready_receivers): self._drain(worker, run) for worker in workers: if worker.process.sentinel in ready_sentinels: @@ -968,9 +1072,9 @@ def _reap(self, worker: _Worker) -> int | None: def _drain(self, worker: _Worker, run: _Run) -> None: while not worker.connection_lost: try: - if not worker.connection.poll(): + if not worker.from_worker.poll(): return - message = worker.connection.recv() + message = worker.from_worker.recv() except (EOFError, OSError): worker.connection_lost = True return @@ -1058,7 +1162,7 @@ def _replace_if_over_cap(self, worker: _Worker) -> None: worker.stopped_over_cap = True shared.workers_stopped_over_cap += 1 worker.retiring = True - worker.stop_deadline = time.monotonic() + worker.stop_deadline = time.monotonic() + _STOP_SECONDS _kill(worker) def _worker_exited(self, worker: _Worker, exitcode: int | None, run: _Run) -> None: @@ -1092,9 +1196,7 @@ def _forget(self, worker: _Worker) -> None: self._shared.workers.remove(worker) worker.exited = True self._shared.cap_overruns.pop(worker.pid, None) - if worker.pidfd is not None: - os.close(worker.pidfd) - worker.pidfd = None + _close_pidfd(worker) try: worker.process.join(0) if worker.process.exitcode is not None: @@ -1109,10 +1211,11 @@ def _forget(self, worker: _Worker) -> None: children.discard(worker.process) except ValueError: pass - try: - worker.connection.close() - except OSError: - pass + for end in (worker.to_worker, worker.from_worker): + try: + end.close() + except OSError: + pass # -- the memory thread -------------------------------------------------- From 75fa563af2689ffc6c11ab6b92093bd9ed292e62 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:59:46 +0400 Subject: [PATCH 08/16] Add failing tests for the second review round's helper and scope findings The identity helper must encode equal structured arrays with object fields equally, keep categories beyond what a dtype's repr shows, MultiIndex level dtypes, nullable missing values, attrs and DatetimeIndex frequencies, and name NaN keys, frame cells and 0-d arrays. A module scope freed by a garbage collection while another scope holds the lock in the same thread must not hang. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_worker_pool.py | 68 +++++++++++++++++++ .../us/test_us_release_slice_memory.py | 41 +++++++++++ 2 files changed, 109 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py index 8f3ee780c0..601339c141 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -862,3 +862,71 @@ class Size(enum.IntEnum): assert canonical_result_bytes( pd.Series([1.0], index=pd.Index([0], name="household")) ) != canonical_result_bytes(pd.Series([1.0], index=pd.Index([0], name="person"))) + + +def test_canonical_bytes_are_equal_for_equal_structured_arrays_with_object_fields() -> ( + None +): + import pickle + + record_type = [("name", object), ("value", " None: + import pandas as pd + + categories = [f"category-{number:03d}" for number in range(150)] + reordered = categories[:60] + categories[60:90][::-1] + categories[90:] + assert canonical_result_bytes( + pd.Series(["category-000"], dtype=pd.CategoricalDtype(categories, ordered=True)) + ) != canonical_result_bytes( + pd.Series(["category-000"], dtype=pd.CategoricalDtype(reordered, ordered=True)) + ) + int32_levels = pd.MultiIndex.from_arrays([np.array([1, 2], dtype=np.int32)]) + int64_levels = pd.MultiIndex.from_arrays([np.array([1, 2], dtype=np.int64)]) + assert canonical_result_bytes(int32_levels) != canonical_result_bytes(int64_levels) + not_a_number = pd.Series(np.array([0.0]) / np.array([0.0])).astype("Float64") + missing = pd.Series([None], dtype="Float64") + assert canonical_result_bytes(not_a_number) != canonical_result_bytes(missing) + plain, labelled = pd.DataFrame({"a": [1.0]}), pd.DataFrame({"a": [1.0]}) + labelled.attrs["source"] = "fixture" + assert canonical_result_bytes(plain) != canonical_result_bytes(labelled) + assert canonical_result_bytes( + pd.date_range("2024-01-01", periods=3, freq="D") + ) != canonical_result_bytes( + pd.DatetimeIndex(["2024-01-01", "2024-01-02", "2024-01-03"]) + ) + + +def test_the_identity_helper_names_nan_keys_frame_cells_and_scalar_arrays() -> None: + import pandas as pd + + def runs(left, right): + return lambda workers: left if workers == 1 else right + + with pytest.raises(AssertionError, match=r"at result\[nan\]\.$"): + assert_identical_across_worker_counts( + runs({float("nan"): 1.0}, {float("nan"): 2.0}), worker_counts=(1, 2) + ) + with pytest.raises(AssertionError, match=r"at result\['b'\]\.iloc\[1\]\.$"): + assert_identical_across_worker_counts( + runs( + pd.DataFrame({"a": [1.0, 2.0], "b": [3.0, 4.0]}), + pd.DataFrame({"a": [1.0, 2.0], "b": [3.0, 5.0]}), + ), + worker_counts=(1, 2), + ) + with pytest.raises(AssertionError, match=r"at result\['total'\]\.$"): + assert_identical_across_worker_counts( + runs({"total": np.array(1.0)}, {"total": np.array(2.0)}), + worker_counts=(1, 2), + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py index 5dcb78123e..09f1656455 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py @@ -280,3 +280,44 @@ def test_closing_an_earlier_scope_keeps_a_later_open_scopes_modules(tmp_path) -> finally: sys.modules.pop(earlier_name, None) sys.modules.pop(later_name, None) + + +def test_a_scope_collected_while_another_holds_the_lock_does_not_hang( + monkeypatch, tmp_path +) -> None: + """A suspended ``with`` scope in a reference cycle can be freed by a garbage + collection that runs while another scope, in the same thread, holds the + scopes' lock; its cleanup must not wait for that lock for ever.""" + import threading + + import microcosm.build.us_runtime.engine_lifecycle as lifecycle + + variables_dir = tmp_path / "variables" + + class Holder: + pass + + holder = Holder() + context = temporary_engine_variable_modules(variables_dir) + context.__enter__() + holder.context = context + holder.itself = holder + del holder, context + + real_registrations = lifecycle._registrations + + def collecting_registrations(directory): + gc.collect() # Frees the suspended scope while ``open`` holds the lock. + return real_registrations(directory) + + monkeypatch.setattr(lifecycle, "_registrations", collecting_registrations) + finished = threading.Event() + + def open_and_close() -> None: + EngineVariableModuleScope(variables_dir).open().close() + finished.set() + + thread = threading.Thread(target=open_and_close, daemon=True) + thread.start() + thread.join(10) + assert finished.is_set() From d82daa9e5fd4cc717159a39931f2fa1f17510349 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:02:38 +0400 Subject: [PATCH 09/16] Fix the second review round's helper and scope findings canonical_result_bytes encodes structured arrays and records field by field (never raw bytes with padding or object addresses), categoricals by their categories, order and codes, MultiIndex levels with their codes, extension arrays with their missing entries apart from NaN, attrs and DatetimeIndex frequencies; _first_difference compares mapping keys by their bytes, descends into DataFrame columns and Series positions, and names a 0-d array by its place. The module scopes' lock is reentrant and closing iterates a copy of the open scopes, so a scope a garbage collection frees mid-open cannot hang. The NaN-against-missing test builds its NaN with an explicit mask: pandas 3 turns NaN into a missing value when converting. Co-Authored-By: Claude Opus 5.5 --- .../build/us_runtime/engine_lifecycle.py | 26 ++- .../engine_free/shared/test_worker_pool.py | 6 +- .../microcosm_build/worker_pool_identity.py | 187 +++++++++++++++--- 3 files changed, 184 insertions(+), 35 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py b/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py index 669757f972..8fb4ce086b 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py @@ -77,7 +77,10 @@ def _registrations(directory: Path | None) -> dict[str, ModuleType]: # Scopes opened and not yet closed, oldest first, as weak references: a scope # dropped without closing stops counting once it is collected. _OPEN_SCOPES: list[weakref.ref[EngineVariableModuleScope]] = [] -_OPEN_SCOPES_LOCK = threading.Lock() +# Reentrant: a garbage collection that frees a suspended +# ``temporary_engine_variable_modules`` scope runs its ``close`` in whichever +# thread is running, possibly one that holds this lock inside ``open``. +_OPEN_SCOPES_LOCK = threading.RLock() class EngineVariableModuleScope: @@ -120,17 +123,24 @@ def _first_later_open_scope_snapshot(self) -> dict[str, ModuleType] | None: """The snapshot of the oldest scope opened after this one and still open.""" later = False snapshot = None - live = [] - for reference in _OPEN_SCOPES: + # A copy: a close that a garbage collection runs from in here may change + # the list. + for reference in tuple(_OPEN_SCOPES): scope = reference() - if scope is None: - continue - live.append(reference) if scope is self: later = True - elif later and snapshot is None and scope._previous is not None: + elif ( + later + and snapshot is None + and scope is not None + and scope._previous is not None + ): snapshot = scope._previous - _OPEN_SCOPES[:] = [reference for reference in live if reference() is not self] + _OPEN_SCOPES[:] = [ + reference + for reference in _OPEN_SCOPES + if reference() is not None and reference() is not self + ] return snapshot def close(self) -> None: diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py index 601339c141..0d47fe627f 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -894,7 +894,11 @@ def test_canonical_bytes_keep_what_pandas_reprs_and_numpy_copies_lose() -> None: int32_levels = pd.MultiIndex.from_arrays([np.array([1, 2], dtype=np.int32)]) int64_levels = pd.MultiIndex.from_arrays([np.array([1, 2], dtype=np.int64)]) assert canonical_result_bytes(int32_levels) != canonical_result_bytes(int64_levels) - not_a_number = pd.Series(np.array([0.0]) / np.array([0.0])).astype("Float64") + # An explicit mask keeps the NaN a value: pandas 3 turns NaN into a + # missing value on conversion. + not_a_number = pd.Series( + pd.arrays.FloatingArray(np.array([np.nan]), np.array([False])) + ) missing = pd.Series([None], dtype="Float64") assert canonical_result_bytes(not_a_number) != canonical_result_bytes(missing) plain, labelled = pd.DataFrame({"a": [1.0]}), pd.DataFrame({"a": [1.0]}) diff --git a/test_support/microcosm_build/worker_pool_identity.py b/test_support/microcosm_build/worker_pool_identity.py index cdbd2886b1..e1a0fa3b51 100644 --- a/test_support/microcosm_build/worker_pool_identity.py +++ b/test_support/microcosm_build/worker_pool_identity.py @@ -48,36 +48,88 @@ def _dtype_bytes(dtype: np.dtype) -> bytes: return repr((dtype.str, fields)).encode() +def _pandas_values(value) -> object: + """The array behind a Series or Index: NumPy, or a pandas extension array.""" + if isinstance(value.dtype, np.dtype): + return value.to_numpy() + return value.array + + +def _extension_array_bytes(values) -> bytes: + """A pandas extension array, with its missing entries kept apart from NaN.""" + import pandas as pd + + kind = _framed(b"t", _type_name(values)) + _framed( + b"d", repr(values.dtype).encode() + ) + if isinstance(values, pd.Categorical): + # Explicit categories: a dtype's repr elides them beyond 100. + return _framed( + b"c", + kind + + canonical_result_bytes(values.categories) + + canonical_result_bytes(bool(values.ordered)) + + canonical_result_bytes(np.asarray(values.codes)), + ) + missing = canonical_result_bytes(np.asarray(values.isna(), dtype=bool)) + if hasattr(values, "asi8"): # Datetime, timedelta and period arrays. + return _framed( + b"x", kind + missing + canonical_result_bytes(np.asarray(values.asi8)) + ) + numpy_dtype = getattr(values.dtype, "numpy_dtype", None) + if numpy_dtype is not None: # Nullable integers, floats and booleans. + present = values.to_numpy(dtype=numpy_dtype, na_value=numpy_dtype.type(0)) + else: + present = values.to_numpy(dtype=object, na_value=None) + return _framed(b"x", kind + missing + canonical_result_bytes(np.asarray(present))) + + +def _values_bytes(values) -> bytes: + if isinstance(values, np.ndarray): + return canonical_result_bytes(values) + return _extension_array_bytes(values) + + def _pandas_bytes(value: object) -> bytes | None: try: import pandas as pd except ImportError: # pragma: no cover - pandas is a workspace dependency return None + kind = _framed(b"t", _type_name(value)) if isinstance(value, pd.DataFrame): parts = [ canonical_result_bytes(value.columns), canonical_result_bytes(value.index), + canonical_result_bytes(dict(value.attrs)), ] for position in range(value.shape[1]): parts.append(canonical_result_bytes(value.iloc[:, position])) - return _framed(b"P", _framed(b"t", _type_name(value)) + b"".join(parts)) + return _framed(b"P", kind + b"".join(parts)) if isinstance(value, pd.Series): return _framed( b"P", - _framed(b"t", _type_name(value)) + kind + canonical_result_bytes(value.name) - # The dtype's repr carries a categorical's categories and order. + canonical_result_bytes(repr(value.dtype)) + canonical_result_bytes(value.index) - + canonical_result_bytes(np.asarray(value.to_numpy())), + + canonical_result_bytes(dict(value.attrs)) + + _values_bytes(_pandas_values(value)), ) + if isinstance(value, pd.MultiIndex): + levels = b"".join( + canonical_result_bytes(level) + canonical_result_bytes(np.asarray(codes)) + for level, codes in zip(value.levels, value.codes, strict=True) + ) + return _framed(b"P", kind + canonical_result_bytes(list(value.names)) + levels) if isinstance(value, pd.Index): + frequency = getattr(value, "freq", None) return _framed( b"P", - _framed(b"t", _type_name(value)) + kind + canonical_result_bytes(list(value.names)) + canonical_result_bytes(repr(value.dtype)) - + canonical_result_bytes(np.asarray(value.to_numpy())), + + canonical_result_bytes(None if frequency is None else str(frequency)) + + _values_bytes(_pandas_values(value)), ) return None @@ -86,7 +138,9 @@ def canonical_result_bytes(value: object) -> bytes: """Bytes that are equal exactly when two results are bit-for-bit the same. Every value carries its type, so ``True`` and ``np.True_``, an ``IntEnum`` - member and its ``int``, and ``bytes`` and ``bytearray`` differ. + member and its ``int``, and ``bytes`` and ``bytearray`` differ. Structured + arrays and records are encoded field by field, never by raw bytes, which + would include padding and the addresses of object fields. Raises: TypeError: For a value of a type it has no encoding for. @@ -107,11 +161,24 @@ def canonical_result_bytes(value: object) -> bytes: ) header = kind + _framed(b"d", _dtype_bytes(value.dtype)) header += _framed(b"s", repr(value.shape).encode()) + if value.dtype.names is not None: + fields = b"".join( + canonical_result_bytes(name) + + canonical_result_bytes(np.ascontiguousarray(value[name])) + for name in value.dtype.names + ) + return _framed(b"R", header + fields) if value.dtype.hasobject: items = b"".join(canonical_result_bytes(item) for item in value.ravel()) return _framed(b"O", header + items) return _framed(b"A", header + np.ascontiguousarray(value).tobytes()) if isinstance(value, np.generic): + if value.dtype.names is not None: # A record of a structured array. + fields = b"".join( + canonical_result_bytes(name) + canonical_result_bytes(value[name]) + for name in value.dtype.names + ) + return _framed(b"V", _dtype_bytes(value.dtype) + fields) return _framed( b"S", _dtype_bytes(value.dtype) + b":" + np.asarray(value).tobytes() ) @@ -157,16 +224,95 @@ def canonical_result_bytes(value: object) -> bytes: ) +def _differ(left: object, right: object) -> bool: + return canonical_result_bytes(left) != canonical_result_bytes(right) + + +def _first_array_difference(left: np.ndarray, right: np.ndarray, place: str) -> str: + if left.dtype != right.dtype or left.shape != right.shape: + return f"{place} (dtype or shape)" + if left.shape == (): + return place + if left.dtype.names is None and not left.dtype.hasobject: + left_items = np.ascontiguousarray(left).reshape(-1).view(np.uint8) + right_items = np.ascontiguousarray(right).reshape(-1).view(np.uint8) + differing = np.flatnonzero(left_items != right_items) + flat = ( + int(differing[0]) // max(left.dtype.itemsize, 1) if differing.size else None + ) + else: + flat = next( + ( + position + for position, (left_item, right_item) in enumerate( + zip(left.ravel(), right.ravel(), strict=True) + ) + if _differ(left_item, right_item) + ), + None, + ) + if flat is None: + return place + position = np.unravel_index(flat, left.shape) + return f"{place}[{', '.join(str(int(axis)) for axis in position)}]" + + +def _first_pandas_difference(left, right, place: str) -> str | None: + """The place two pandas objects first differ, or None if they aren't pandas.""" + try: + import pandas as pd + except ImportError: # pragma: no cover - pandas is a workspace dependency + return None + if isinstance(left, pd.DataFrame): + for name, part in (("columns", "columns"), ("index", "index")): + if _differ(getattr(left, part), getattr(right, part)): + return f"{place}.{name}" + if _differ(dict(left.attrs), dict(right.attrs)): + return f"{place}.attrs" + for position in range(left.shape[1]): + left_column, right_column = left.iloc[:, position], right.iloc[:, position] + if _differ(left_column, right_column): + label = f"{place}[{left.columns[position]!r}]" + return _first_difference(left_column, right_column, label) + return place + if isinstance(left, pd.Series): + for name in ("index", "name", "attrs"): + left_part, right_part = getattr(left, name), getattr(right, name) + if name == "attrs": + left_part, right_part = dict(left_part), dict(right_part) + if _differ(left_part, right_part): + return f"{place}.{name}" + if repr(left.dtype) != repr(right.dtype): + return f"{place}.dtype" + if isinstance(left.dtype, np.dtype): + located = _first_array_difference( + left.to_numpy(), right.to_numpy(), f"{place}.iloc" + ) + return place if located == f"{place}.iloc" else located + return place + if isinstance(left, pd.Index): + return place + return None + + def _first_difference(left: object, right: object, place: str) -> str: """The place in two results where their canonical bytes first differ.""" if type(left) is not type(right): return f"{place} (types {type(left).__name__} and {type(right).__name__})" + pandas_place = _first_pandas_difference(left, right, place) + if pandas_place is not None: + return pandas_place if isinstance(left, Mapping): - if list(left) != list(right): + # Keys compare by their bytes: a NaN key is never == itself. + if [canonical_result_bytes(key) for key in left] != [ + canonical_result_bytes(key) for key in right + ]: return f"{place} (its keys or their order)" - for key in left: - if canonical_result_bytes(left[key]) != canonical_result_bytes(right[key]): - return _first_difference(left[key], right[key], f"{place}[{key!r}]") + for (key, left_item), right_item in zip( + left.items(), right.values(), strict=True + ): + if _differ(left_item, right_item): + return _first_difference(left_item, right_item, f"{place}[{key!r}]") return place if isinstance(left, tuple | list): if len(left) != len(right): @@ -174,7 +320,7 @@ def _first_difference(left: object, right: object, place: str) -> str: for position, (left_item, right_item) in enumerate( zip(left, right, strict=True) ): - if canonical_result_bytes(left_item) != canonical_result_bytes(right_item): + if _differ(left_item, right_item): return _first_difference(left_item, right_item, f"{place}[{position}]") return place if dataclasses.is_dataclass(left) and not isinstance(left, type): @@ -183,22 +329,11 @@ def _first_difference(left: object, right: object, place: str) -> str: getattr(left, field.name), getattr(right, field.name), ) - if canonical_result_bytes(left_item) != canonical_result_bytes(right_item): + if _differ(left_item, right_item): return _first_difference(left_item, right_item, f"{place}.{field.name}") return place - if ( - isinstance(left, np.ndarray) - and left.dtype == right.dtype - and left.shape == right.shape - and not left.dtype.hasobject - ): - left_bytes = np.ascontiguousarray(left).reshape(-1).view(np.uint8) - right_bytes = np.ascontiguousarray(right).reshape(-1).view(np.uint8) - differing = np.flatnonzero(left_bytes != right_bytes) - if differing.size: - flat = int(differing[0]) // max(left.dtype.itemsize, 1) - position = np.unravel_index(flat, left.shape) if left.shape else () - return f"{place}[{', '.join(str(int(axis)) for axis in position)}]" + if isinstance(left, np.ndarray) and not isinstance(left, np.ma.MaskedArray): + return _first_array_difference(left, right, place) return place From cdc7a9a9114adb42265932216157012332b988f3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:28:42 +0400 Subject: [PATCH 10/16] Add failing tests for the third review round's pool findings A unit whose worker dies while receiving it is charged an attempt; a worker that dies while receiving its start-up data is a failed start, not the end of the run; a units iterable that raises leaves the pool usable; close() returns when its thread holds the pool's lock; handing back a result frees its place for an idle worker at once; busy workers exit when their parent is killed even while a child the parent forked holds copies of its pipe ends. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_worker_pool.py | 136 ++++++++++++++++-- .../worker_pool_orphan_parent.py | 27 +++- 2 files changed, 149 insertions(+), 14 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py index 0d47fe627f..3776eb8839 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -444,7 +444,10 @@ def _process_running(pid: int) -> bool: return True -def test_busy_workers_exit_when_their_parent_is_killed(tmp_path) -> None: +@pytest.mark.parametrize("fork_holder", [False, True], ids=["alone", "forked-child"]) +def test_busy_workers_exit_when_their_parent_is_killed(tmp_path, fork_holder) -> None: + """With ``forked-child``, a child the parent forked keeps copies of the + parent's pipe ends open, so the pipes alone cannot show the parent died.""" repository = paths_for("microcosm-build").repository environment = {**os.environ, "PYTHONPATH": str(repository)} parent = subprocess.Popen( @@ -453,13 +456,17 @@ def test_busy_workers_exit_when_their_parent_is_killed(tmp_path) -> None: "-m", "test_support.microcosm_build.worker_pool_orphan_parent", str(tmp_path), + *(["--fork-holder"] if fork_holder else []), ], cwd=repository, env=environment, ) + holder_file = tmp_path / "holder" try: deadline = time.monotonic() + 90 - while len(list(tmp_path.glob("worker-*"))) < 2: + while len(list(tmp_path.glob("worker-*"))) < 2 or ( + fork_holder and not holder_file.exists() + ): assert parent.poll() is None, "the parent process exited early" assert time.monotonic() < deadline, "the workers did not start" time.sleep(0.2) @@ -470,15 +477,21 @@ def test_busy_workers_exit_when_their_parent_is_killed(tmp_path) -> None: parent.kill() parent.wait() - deadline = time.monotonic() + 20 - while ( - any(_process_running(pid) for pid in worker_pids) - and time.monotonic() < deadline - ): - time.sleep(0.2) - still_running = [pid for pid in worker_pids if _process_running(pid)] - for pid in still_running: - os.kill(pid, signal.SIGKILL) + try: + deadline = time.monotonic() + 20 + while ( + any(_process_running(pid) for pid in worker_pids) + and time.monotonic() < deadline + ): + time.sleep(0.2) + still_running = [pid for pid in worker_pids if _process_running(pid)] + for pid in still_running: + os.kill(pid, signal.SIGKILL) + finally: + if holder_file.exists(): + holder = int(holder_file.read_text()) + if _process_running(holder): + os.kill(holder, signal.SIGKILL) assert still_running == [] @@ -734,6 +747,107 @@ def refuse(pid, signal_number): os.close(write_end) +def _fail_one_send(monkeypatch, pool, *, while_ready: bool) -> list[int]: + """Make the parent's next unit or start-up send find its worker dead. + + The send kills the worker and raises ``BrokenPipeError``, as a send does + when the worker dies (an out-of-memory kill, say) while reading it. + Returns the killed workers' process IDs. + """ + from multiprocessing.connection import Connection + + real_send_bytes = Connection.send_bytes + killed: list[int] = [] + + def send_bytes(connection, *args, **kwargs): + workers = pool._shared.workers + if not killed and workers and workers[-1].ready is while_ready: + killed.append(workers[-1].pid) + os.kill(workers[-1].pid, signal.SIGKILL) + raise BrokenPipeError(32, "Broken pipe") + return real_send_bytes(connection, *args, **kwargs) + + monkeypatch.setattr(Connection, "send_bytes", send_bytes) + return killed + + +def test_a_unit_whose_worker_dies_while_receiving_it_is_charged_an_attempt( + monkeypatch, +) -> None: + pool = WorkerPool( + WorkerPoolSettings(workers=1, max_attempts=2), unit_function=units.echo + ) + killed = _fail_one_send(monkeypatch, pool, while_ready=True) + with pool: + assert list(pool.map([0])) == [0] + report = pool.report() + + assert len(killed) == 1 + assert [ + (attempt.unit_index, attempt.worker_pid) for attempt in report.failed_attempts + ] == [(0, killed[0])] + + +def test_a_worker_that_dies_while_receiving_its_start_up_data_is_a_failed_start( + monkeypatch, +) -> None: + pool = WorkerPool( + WorkerPoolSettings(workers=1, max_attempts=2), + initializer=units.initialize_with_payload, + initargs=(np.ones(10),), + unit_function=units.describe_worker, + ) + killed = _fail_one_send(monkeypatch, pool, while_ready=False) + with pool: + (result,) = pool.map([0]) + report = pool.report() + + assert len(killed) == 1 + assert result["pid"] != killed[0] + assert report.worker_starts == 2 + + +def test_a_units_iterable_that_raises_leaves_the_pool_usable() -> None: + def units_that_fail(): + yield 0 + raise ValueError("fixture units iterable fails") + + with WorkerPool(WorkerPoolSettings(workers=1), unit_function=units.echo) as pool: + with pytest.raises(ValueError, match="fixture units iterable fails"): + next(pool.map(units_that_fail())) + assert list(pool.map([1])) == [1] + + +def test_closing_while_this_thread_holds_the_pools_lock_returns() -> None: + """A garbage collection inside ``report()``, which holds the lock, can close + an abandoned map; ``close`` must not then wait for the memory thread, + which is waiting for that lock.""" + pool = WorkerPool( + WorkerPoolSettings(workers=2, memory_poll_seconds=0.02), + unit_function=units.sleep_then_return, + ) + results = pool.map([(0, 0.0), (1, 30.0)]) + assert next(results) == 0 + with pool._shared.lock: + time.sleep(0.2) # The memory thread is now waiting for the lock. + pool.close() + assert multiprocessing.active_children() == [] + + +def test_handing_back_a_result_frees_its_place_for_an_idle_worker() -> None: + with WorkerPool( + WorkerPoolSettings(workers=1, max_units_ahead=1), + unit_function=units.record_run_times, + ) as pool: + results = pool.map([(0, 0.0), (1, 0.0)]) + next(results) + time.sleep(1.0) # The caller works on result 0. + resumed = time.monotonic() + (_, unit_one_started, _) = next(results) + + assert unit_one_started < resumed + + # --------------------------------------------------------------------------- # The 1-vs-N byte-identity helper # --------------------------------------------------------------------------- diff --git a/test_support/microcosm_build/worker_pool_orphan_parent.py b/test_support/microcosm_build/worker_pool_orphan_parent.py index 50f00cf094..122bb3fc8c 100644 --- a/test_support/microcosm_build/worker_pool_orphan_parent.py +++ b/test_support/microcosm_build/worker_pool_orphan_parent.py @@ -1,18 +1,39 @@ """A parent process whose pool workers are busy when the test kills it. Run as ``python -m test_support.microcosm_build.worker_pool_orphan_parent DIR``: -each worker writes ``DIR/worker-`` and then sleeps for a minute. +each worker writes ``DIR/worker-`` and then sleeps for a minute. With +``--fork-holder``, once both workers are running the parent forks a child that +keeps copies of the parent's pipe ends for a minute and writes its process ID +to ``DIR/holder``. """ from __future__ import annotations +import os import sys +import threading +import time +from pathlib import Path from microcosm.build.worker_pool import WorkerPool, WorkerPoolSettings from test_support.microcosm_build import worker_pool_units as units -def main(directory: str) -> None: +def _fork_a_holder(directory: Path) -> None: + while len(list(directory.glob("worker-*"))) < 2: + time.sleep(0.1) + holder = os.fork() + if holder == 0: + time.sleep(60) + os._exit(0) + (directory / "holder").write_text(str(holder)) + + +def main(directory: str, fork_holder: bool) -> None: + if fork_holder: + threading.Thread( + target=_fork_a_holder, args=(Path(directory),), daemon=True + ).start() with WorkerPool( WorkerPoolSettings(workers=2), unit_function=units.write_pid_then_sleep ) as pool: @@ -20,4 +41,4 @@ def main(directory: str) -> None: if __name__ == "__main__": - main(sys.argv[1]) + main(sys.argv[1], "--fork-holder" in sys.argv[2:]) From 2b4724dd7718fe729238871c61febcca348c2e37 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:33:27 +0400 Subject: [PATCH 11/16] Fix the third review round's pool findings Start-up data goes over each worker's own pipe after its process starts, so a worker that dies while reading it is an ordinary failed start (and is reaped), and workers started together import at once. A unit is assigned and its attempt counted under the lock before it is written, and never to a killed worker, so a worker dying mid-send is charged and a reading taken before the unit cannot kill for it. map() reads its units before taking its turn, takes the turn under the lock and releases it on any failure. close() no longer joins the memory thread, and report() builds its result outside the lock. A held result frees its window place before units are handed out. Workers also exit when their parent process ID changes, for a parent whose forked child holds copies of the parent-death pipe. Co-Authored-By: Claude Opus 5.5 --- .../src/microcosm/build/worker_pool.py | 160 ++++++++++++------ 1 file changed, 108 insertions(+), 52 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/worker_pool.py b/packages/microcosm-build/src/microcosm/build/worker_pool.py index f15a398d4b..24e9a0a59e 100644 --- a/packages/microcosm-build/src/microcosm/build/worker_pool.py +++ b/packages/microcosm-build/src/microcosm/build/worker_pool.py @@ -15,10 +15,13 @@ default rules (``us_runtime/engine_lifecycle.py``). * **Start-up data sent once per worker.** ``initializer(*initargs)`` runs once in each worker, and whatever it returns is passed to every unit that worker - runs as ``unit_function(state, unit)``. Spawn pickles ``initargs`` once per - worker start, so a frame passed there crosses once per worker, not once per - unit; while a worker starts, the parent briefly holds that pickled copy too. - A unit itself should be small (indices, a request descriptor). + runs as ``unit_function(state, unit)``. ``initargs`` are pickled and sent + over the worker's own pipe once per worker start, after its process has + started, so a frame passed there crosses once per worker, not once per unit; + while it is sent, the parent briefly holds the pickled copy too. Workers + started together import their modules at the same time. A worker that dies + while receiving its start-up data counts as a failed start. A unit itself + should be small (indices, a request descriptor). * **Worker replacement.** With ``max_units_per_worker``, a worker is told to stop after that many units and a fresh one takes its place, so memory that an engine leaves behind does not build up. The replacement starts only after @@ -55,7 +58,9 @@ while each worker starts, so another thread of the parent that reads the environment, or starts a subprocess, at that moment sees them too. * **No orphaned workers.** Each worker exits as soon as its parent process - dies, even in the middle of a unit, once the unit lets other threads run: + dies (it watches a pipe only the parent holds, and, within a second, its + parent process ID, in case a child the parent forked holds copies of the + pipe), even in the middle of a unit, once the unit lets other threads run: Python and NumPy code does so often, but a long call into C code that holds the interpreter lock delays the exit until it returns. A pool that is garbage-collected or left open at interpreter exit kills its workers, and a @@ -396,24 +401,40 @@ def _exit_when_parent_dies() -> None: if parent is None: # pragma: no cover - a pool worker always has a parent return + parent_pid = os.getppid() + def watch() -> None: - wait_for_any([parent.sentinel]) + # A child the parent forked keeps copies of the pipe's write end, so + # the pipe alone may never close; the parent process ID changes when + # the worker is handed to a new parent. + while not wait_for_any([parent.sentinel], timeout=1.0): + if os.getppid() != parent_pid: + break os._exit(_PARENT_GONE_EXIT_CODE) threading.Thread(target=watch, name="worker-pool-parent", daemon=True).start() -def _worker_main(receive, connection, initializer, initargs, unit_function) -> None: +def _worker_main(receive, connection, initializer, unit_function) -> None: """Run in each worker: start up once, then run units until told to stop. - ``receive`` reads units from the parent; ``connection`` sends messages to it. + ``receive`` reads the start-up data and then units from the parent; + ``connection`` sends messages to it. """ _exit_when_parent_dies() + try: + initargs = receive.recv() + except (EOFError, OSError): + return + except Exception as error: + _send_quietly(connection, ("start_error", _summary(error), _formatted(error))) + return try: state = None if initializer is None else initializer(*initargs) except Exception as error: _send_quietly(connection, ("start_error", _summary(error), _formatted(error))) return + del initargs if not _send_quietly(connection, ("ready", os.getpid())): return while True: @@ -753,26 +774,38 @@ def __exit__(self, *exc_info) -> None: def report(self) -> WorkerPoolReport: with self._shared.lock: - return WorkerPoolReport( - worker_starts=self._worker_starts, - units_completed=self._units_completed, - failed_attempts=tuple(self._failed_attempts), - max_live_workers=self._max_live_workers, - peak_worker_memory_bytes=self._shared.peak_memory, - workers_stopped_over_cap=self._shared.workers_stopped_over_cap, + values = ( + self._worker_starts, + self._units_completed, + list(self._failed_attempts), + self._max_live_workers, + self._shared.peak_memory, + self._shared.workers_stopped_over_cap, ) + starts, completed, failed, live, peak, stopped = values + return WorkerPoolReport( + worker_starts=starts, + units_completed=completed, + failed_attempts=tuple(failed), + max_live_workers=live, + peak_worker_memory_bytes=peak, + workers_stopped_over_cap=stopped, + ) def map(self, units: Iterable[object]) -> Iterator[object]: """Run ``unit_function(state, unit)`` for each unit; yield results in order.""" - if self._closed: - raise WorkerPoolError("The worker pool is closed.") - if self._map_owner is not None: - raise WorkerPoolError("The worker pool is already running a map.") token = object() - self._map_owner = token - units = list(units) + took_turn = False delivered_all = False try: + units = list(units) + with self._shared.lock: + if self._closed: + raise WorkerPoolError("The worker pool is closed.") + if self._map_owner is not None: + raise WorkerPoolError("The worker pool is already running a map.") + self._map_owner = token + took_turn = True for index, result in self._run(units): if index == len(units) - 1: # Every result is out: the map is over even if the caller @@ -786,7 +819,7 @@ def map(self, units: Iterable[object]) -> Iterator[object]: # A finished map's generator may be closed after a later map # began; only the map that holds the turn may give it up. self._release_map_turn(token) - if not delivered_all: + if took_turn and not delivered_all: self.close() def _release_map_turn(self, token: object) -> None: @@ -799,14 +832,10 @@ def close(self) -> None: return self._closed = True shared = self._shared + # The memory thread stops at its next poll. It is not joined: a garbage + # collection can close the pool from the memory thread itself, or from a + # thread holding the lock the memory thread is waiting for. shared.stop.set() - # A garbage collection in the memory thread can close the pool there, - # and a thread cannot join itself. - if ( - self._monitor is not None - and self._monitor is not threading.current_thread() - ): - self._monitor.join() with shared.lock: workers = list(shared.workers) for worker in workers: @@ -862,6 +891,12 @@ def _run(self, units: list[object]) -> Iterator[tuple[int, object]]: # Take in finished results and exits without waiting, so idle # workers get new units even while the caller holds a result. self._wait_and_handle(run, block=False) + held = None + if next_index in run.results: + # Take the result now, so its place in the window goes to a new + # unit before the caller gets it. + held = (next_index, run.results.pop(next_index)) + next_index += 1 window_end = min(count, next_index + settings.units_ahead) waiting = len(run.retries) + max(0, window_end - next_new) self._kill_workers_past_their_stop_deadline() @@ -871,6 +906,7 @@ def _run(self, units: list[object]) -> Iterator[tuple[int, object]]: not worker.ready or worker.retiring or worker.connection_lost + or worker.killed or worker.unit_index is not None ): continue @@ -883,11 +919,9 @@ def _run(self, units: list[object]) -> Iterator[tuple[int, object]]: break if not self._send_unit(worker, index, run): heapq.heappush(run.retries, index) - if next_index in run.results: - result = run.results.pop(next_index) - next_index += 1 - yield next_index - 1, result - del result + if held is not None: + yield held + held = None continue self._wait_and_handle(run, block=True) @@ -940,13 +974,34 @@ def _start_workers(self, waiting: int) -> None: and not worker.connection_lost and worker.unit_index is None ) + started = [] + payload = None while ( available < waiting and len(self._shared.workers) < self._settings.workers ): - self._start_worker() + if payload is None: + payload = self._start_up_payload() + started.append(self._start_worker()) available += 1 + # Every new process imports at once while the parent sends each its + # start-up data in turn. + for worker in started: + try: + worker.to_worker.send_bytes(payload) + except OSError: + # The worker died while reading it; its exit counts as a + # failed start. + worker.connection_lost = True + + def _start_up_payload(self): + try: + return ForkingPickler.dumps(self._initargs) + except Exception as error: + raise WorkerPoolError( + f"The workers' start-up data could not be pickled: {_summary(error)}" + ) from error - def _start_worker(self) -> None: + def _start_worker(self) -> _Worker: # Two one-way pipes: socket pairs carry large results several times # slower on macOS. units_out, units_in = self._context.Pipe(duplex=False) @@ -954,19 +1009,11 @@ def _start_worker(self) -> None: child_ends = (units_out, messages_in) process = self._context.Process( target=_worker_main, - args=( - units_out, - messages_in, - self._initializer, - self._initargs, - self._unit_function, - ), + args=(units_out, messages_in, self._initializer, self._unit_function), name=f"worker-pool-{self._worker_starts + 1}", daemon=True, ) - # Not under the state's lock: with spawn, ``start`` blocks until the - # worker has read its start-up data, which can take as long as the - # worker's imports, and the memory thread needs the lock meanwhile. + # Not under the state's lock, so the memory thread can act meanwhile. try: with _environment_for_start(self._settings.worker_environment): process.start() @@ -996,9 +1043,17 @@ def _start_worker(self) -> None: self._max_live_workers = max( self._max_live_workers, len(self._shared.workers) ) + return worker def _send_unit(self, worker: _Worker, index: int, run: _Run) -> bool: - """Send a unit to an idle worker; False if the worker has gone.""" + """Give a unit to an idle worker; False if the worker can no longer take it. + + The unit is assigned and its attempt counted, under the lock, before it + is written: the memory thread then either kills the worker before the + assignment (and the unit is not given to it) or sees the new unit and + does not act on an earlier reading. A worker that dies while the unit + is being written is charged through its exit, like any other death. + """ try: payload = ForkingPickler.dumps((index, run.units[index])) except Exception as error: @@ -1010,15 +1065,16 @@ def _send_unit(self, worker: _Worker, index: int, run: _Run) -> bool: label=label, causes=[cause], ) from error + with self._shared.lock: + if worker.killed or worker.connection_lost or _has_exited(worker): + return False + worker.unit_index = index + worker.units_sent += 1 + run.attempts[index] += 1 try: worker.to_worker.send_bytes(payload) except OSError: worker.connection_lost = True - return False - run.attempts[index] += 1 - with self._shared.lock: - worker.unit_index = index - worker.units_sent += 1 return True def _send_stop(self, worker: _Worker) -> None: From 936b0babb7d51127a46ded12732e7346842e73fa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:35:24 +0400 Subject: [PATCH 12/16] Add failing tests for the third review round's helper and scope findings The identity helper must keep a Series subclass's _metadata and an ndarray subclass's attributes (such as weights and enum classes), numpy record and scalar types, encode equal MultiIndexes equally however they were built, and refuse pandas values it cannot encode with its own TypeError. A closing module scope must not put back a module another scope removed, nor replace a module a later, still-open scope registered under the same name. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_worker_pool.py | 74 +++++++++++++++++++ .../us/test_us_release_slice_memory.py | 62 ++++++++++++++++ 2 files changed, 136 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py index 3776eb8839..7637cbc6be 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -18,6 +18,7 @@ from types import ModuleType, SimpleNamespace import numpy as np +import pandas as pd import pytest import microcosm.build.worker_pool as worker_pool_module @@ -1048,3 +1049,76 @@ def runs(left, right): runs({"total": np.array(1.0)}, {"total": np.array(2.0)}), worker_counts=(1, 2), ) + + +class _WeightedSeries(pd.Series): + """Like policyengine-core's MicroSeries: weights kept in ``_metadata``.""" + + _metadata = ["weights"] + + @property + def _constructor(self): + return _WeightedSeries + + +class _LabelledArray(np.ndarray): + """Like policyengine-core's EnumArray: an attribute beside the codes.""" + + def __new__(cls, codes, possible_values): + array = np.asarray(codes).view(cls) + array.possible_values = possible_values + return array + + +def test_canonical_bytes_keep_the_state_subclasses_carry() -> None: + import enum + + first = _WeightedSeries([1.0, 2.0, 3.0]) + first.weights = np.array([1.0, 1.0, 1.0]) + second = _WeightedSeries([1.0, 2.0, 3.0]) + second.weights = np.array([5.0, 0.0, 9.0]) + assert canonical_result_bytes(first) != canonical_result_bytes(second) + + class FilingStatus(enum.Enum): + SINGLE = "single" + JOINT = "joint" + + class Tenure(enum.Enum): + OWNER = "owner" + RENTER = "renter" + + assert canonical_result_bytes( + _LabelledArray([0, 1], FilingStatus) + ) != canonical_result_bytes(_LabelledArray([0, 1], Tenure)) + + +def test_canonical_bytes_keep_numpy_scalar_and_record_types() -> None: + record_type = [("a", " None: + sliced = pd.MultiIndex.from_tuples( + [(1, "a"), (2, "b"), (3, "c")], names=["unit", "code"] + )[:2] + built = pd.MultiIndex.from_tuples([(1, "a"), (2, "b")], names=["unit", "code"]) + assert canonical_result_bytes(sliced) == canonical_result_bytes(built) + + +def test_canonical_bytes_refuse_pandas_values_they_cannot_encode_with_type_error() -> ( + None +): + import pyarrow as pa + + timestamps = pd.Series(pd.array([1, 2], dtype=pd.ArrowDtype(pa.timestamp("ns")))) + with pytest.raises(TypeError, match="canonical_result_bytes"): + canonical_result_bytes(timestamps) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py index 09f1656455..e3905c3f99 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_slice_memory.py @@ -321,3 +321,65 @@ def open_and_close() -> None: thread.start() thread.join(10) assert finished.is_set() + + +def test_a_scope_closing_never_puts_back_a_module_another_scope_removed( + monkeypatch, tmp_path +) -> None: + """A garbage collection during one scope's close can free a suspended scope + whose cleanup removes a module; the first scope must not then put it back.""" + import microcosm.build.us_runtime.engine_lifecycle as lifecycle + + variables_dir = tmp_path / "variables" + name = "7520001_-123_income_tax" + + class Holder: + pass + + try: + holder = Holder() + context = temporary_engine_variable_modules(variables_dir) + context.__enter__() + holder.context = context + holder.itself = holder + _register_variable_module(name, variables_dir) + explicit = EngineVariableModuleScope(variables_dir).open() + del holder, context + + real_registrations = lifecycle._registrations + + def registrations_then_collect(directory): + found = real_registrations(directory) + gc.collect() # Frees the suspended scope, which removes the module. + return found + + monkeypatch.setattr(lifecycle, "_registrations", registrations_then_collect) + explicit.close() + assert name not in sys.modules + finally: + sys.modules.pop(name, None) + + +def test_an_earlier_scope_closing_keeps_a_later_open_scopes_reregistered_module( + tmp_path, +) -> None: + """Core names modules after id(system), so a new system can take a dead one's + name. An earlier scope's snapshot of the old module must not replace the + module a later, still-open scope registered under that name.""" + variables_dir = tmp_path / "variables" + name = "7530001_-123_income_tax" + try: + stale = _variable_module(name, variables_dir) + sys.modules[name] = stale + earlier = EngineVariableModuleScope(variables_dir).open() + later = EngineVariableModuleScope(variables_dir).open() + current = _variable_module(name, variables_dir) + sys.modules[name] = current + + earlier.close() + assert sys.modules[name] is current + + later.close() + assert sys.modules[name] is stale + finally: + sys.modules.pop(name, None) From 2316b6dda0ccf138648e4cc35a8e86b77ad9db30 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:37:33 +0400 Subject: [PATCH 13/16] Fix the third review round's helper, scope and changelog findings canonical_result_bytes encodes what a pandas subclass lists in _metadata and what an ndarray subclass keeps in its instance dictionary (MicroSeries weights, an EnumArray's enum class), classes and enum members by name, numpy scalar types and dtype character codes, a MultiIndex by each level's values, and refuses pandas values it cannot encode with its own TypeError. A closing module scope leaves entries from its snapshot to a later open scope, and puts one back only while it is still registered, so it never restores a module another scope removed or replaces one a later scope registered under a reused name. The docstring states which scope a registration belongs to. The scorer's changelog entry says only a worker death runs a slice again. Co-Authored-By: Claude Opus 5.5 --- .../us-head-to-head-shared-pool.changed.md | 2 +- .../build/us_runtime/engine_lifecycle.py | 21 ++++-- .../microcosm_build/worker_pool_identity.py | 68 ++++++++++++++++--- 3 files changed, 76 insertions(+), 15 deletions(-) diff --git a/changelog.d/us-head-to-head-shared-pool.changed.md b/changelog.d/us-head-to-head-shared-pool.changed.md index 31f76a9a0f..7a232599c7 100644 --- a/changelog.d/us-head-to-head-shared-pool.changed.md +++ b/changelog.d/us-head-to-head-shared-pool.changed.md @@ -1 +1 @@ -The US head-to-head scorer (`tools/score_us_release_head_to_head.py`) runs its `--workers` slices on the shared worker pool instead of `ProcessPoolExecutor`, so the repository has one worker-pool implementation. `--worker-max-slices` now works on every supported Python: the scorer no longer refuses it on interpreters where `ProcessPoolExecutor` could hang replacing a worker. A slice whose worker dies or runs out of memory runs once more in a fresh worker before the run stops with the slice's label. Scorecards are unchanged. +The US head-to-head scorer (`tools/score_us_release_head_to_head.py`) runs its `--workers` slices on the shared worker pool instead of `ProcessPoolExecutor`, so the repository has one worker-pool implementation. `--worker-max-slices` now works on every supported Python: the scorer no longer refuses it on interpreters where `ProcessPoolExecutor` could hang replacing a worker. A slice whose worker dies (for example, killed by the operating system for its memory) runs once more in a fresh worker before the run stops with the slice's label; the scorer's own 20 GiB memory check, and any other error raised while scoring a slice, still stop the run at once. Each failed attempt is printed on stderr. Scorecards are unchanged. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py b/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py index 8fb4ce086b..add3b1f1b2 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/engine_lifecycle.py @@ -95,10 +95,14 @@ class EngineVariableModuleScope: nothing when collected; its modules simply stay registered, as they would without it. ``close`` does nothing the second time. - Scopes may close in any order. A scope that closes while a scope opened - after it is still open removes only what was registered before that later - scope opened; what came after may belong to the later scope, which removes - it when it closes. + Scopes may close in any order. A registration belongs to the most recently + opened scope that is still open when it is made: a scope that closes + removes what was registered since it opened, except what was registered + after a later, still-open scope opened, which that scope removes when it + closes. An entry that existed when the scope opened is put back only if + the scope is the latest open one and the entry is still registered (Core + reused a dead system's id and overwrote it); otherwise the later scope, + whose snapshot holds it too, decides. """ def __init__(self, variables_dir: str | Path | None = None) -> None: @@ -173,7 +177,14 @@ def _remove_since( shared_prefix = f"{id(shared_system)}_" for name in _registrations(Path(final_directory).absolute()): if name in previous: - sys.modules[name] = previous[name] + if later_snapshot is not None: + # A later open scope's snapshot holds it too; it decides. + continue + current = sys.modules.get(name) + # Not if another scope removed it meanwhile (a garbage + # collection can close one in the middle of this loop). + if current is not None and current is not previous[name]: + sys.modules[name] = previous[name] elif later_snapshot is not None and name not in later_snapshot: # Registered after a still-open later scope opened. continue diff --git a/test_support/microcosm_build/worker_pool_identity.py b/test_support/microcosm_build/worker_pool_identity.py index e1a0fa3b51..24c9f77cbc 100644 --- a/test_support/microcosm_build/worker_pool_identity.py +++ b/test_support/microcosm_build/worker_pool_identity.py @@ -21,6 +21,7 @@ from __future__ import annotations import dataclasses +import enum import struct from collections.abc import Callable, Mapping, Sequence @@ -45,7 +46,9 @@ def _dtype_bytes(dtype: np.dtype) -> bytes: would lose field names, field types and their byte order. """ fields = dtype.descr if dtype.fields is not None or dtype.subdtype else None - return repr((dtype.str, fields)).encode() + # The character code tells apart types with the same layout, such as + # ``longlong`` and ``int64`` where they differ. + return repr((dtype.str, dtype.char, fields)).encode() def _pandas_values(value) -> object: @@ -57,6 +60,37 @@ def _pandas_values(value) -> object: def _extension_array_bytes(values) -> bytes: """A pandas extension array, with its missing entries kept apart from NaN.""" + try: + return _extension_array_bytes_or_raise(values) + except (TypeError, ValueError) as error: + raise TypeError( + "canonical_result_bytes has no encoding for pandas values of dtype " + f"{values.dtype!r}: {error}" + ) from error + + +def _subclass_state_bytes(value: object, base: type) -> bytes: + """What a subclass of ``base`` keeps beyond the base's own data. + + A pandas subclass lists it in ``_metadata`` (policyengine-core's + ``MicroSeries`` keeps its weights there); an ``ndarray`` subclass keeps it + in its instance dictionary (``EnumArray`` keeps its enum class there). + """ + if type(value) is base: + return b"" + if base is np.ndarray: + state = dict(sorted(getattr(value, "__dict__", {}).items())) + else: + own = set(getattr(base, "_metadata", ())) + state = { + name: getattr(value, name, None) + for name in sorted(getattr(type(value), "_metadata", ())) + if name not in own + } + return _framed(b"z", canonical_result_bytes(state)) + + +def _extension_array_bytes_or_raise(values) -> bytes: import pandas as pd kind = _framed(b"t", _type_name(values)) + _framed( @@ -101,6 +135,7 @@ def _pandas_bytes(value: object) -> bytes | None: canonical_result_bytes(value.columns), canonical_result_bytes(value.index), canonical_result_bytes(dict(value.attrs)), + _subclass_state_bytes(value, pd.DataFrame), ] for position in range(value.shape[1]): parts.append(canonical_result_bytes(value.iloc[:, position])) @@ -113,12 +148,15 @@ def _pandas_bytes(value: object) -> bytes | None: + canonical_result_bytes(repr(value.dtype)) + canonical_result_bytes(value.index) + canonical_result_bytes(dict(value.attrs)) + + _subclass_state_bytes(value, pd.Series) + _values_bytes(_pandas_values(value)), ) if isinstance(value, pd.MultiIndex): + # Each level's values in index order: its levels and codes would also + # carry values a slice no longer uses. levels = b"".join( - canonical_result_bytes(level) + canonical_result_bytes(np.asarray(codes)) - for level, codes in zip(value.levels, value.codes, strict=True) + canonical_result_bytes(value.get_level_values(position)) + for position in range(value.nlevels) ) return _framed(b"P", kind + canonical_result_bytes(list(value.names)) + levels) if isinstance(value, pd.Index): @@ -149,16 +187,29 @@ def canonical_result_bytes(value: object) -> bytes: return b"N" if type(value) is bool: return b"B1" if value else b"B0" + if isinstance(value, type): + return _framed(b"T", f"{value.__module__}.{value.__qualname__}".encode()) + if isinstance(value, enum.Enum): + return _framed( + b"G", + _framed(b"t", _type_name(value)) + + canonical_result_bytes(value.name) + + canonical_result_bytes(value.value), + ) if isinstance(value, np.ndarray): - kind = _framed(b"t", _type_name(value)) if isinstance(value, np.ma.MaskedArray): + # Its instance dictionary is internal state; the data, mask and + # fill value are what it holds. return _framed( b"K", - kind + _framed(b"t", _type_name(value)) + canonical_result_bytes(np.asarray(value.data)) + canonical_result_bytes(np.ma.getmaskarray(value)) + canonical_result_bytes(np.asarray(value.fill_value)), ) + kind = _framed(b"t", _type_name(value)) + _subclass_state_bytes( + value, np.ndarray + ) header = kind + _framed(b"d", _dtype_bytes(value.dtype)) header += _framed(b"s", repr(value.shape).encode()) if value.dtype.names is not None: @@ -173,15 +224,14 @@ def canonical_result_bytes(value: object) -> bytes: return _framed(b"O", header + items) return _framed(b"A", header + np.ascontiguousarray(value).tobytes()) if isinstance(value, np.generic): + scalar = _framed(b"t", _type_name(value)) + _dtype_bytes(value.dtype) if value.dtype.names is not None: # A record of a structured array. fields = b"".join( canonical_result_bytes(name) + canonical_result_bytes(value[name]) for name in value.dtype.names ) - return _framed(b"V", _dtype_bytes(value.dtype) + fields) - return _framed( - b"S", _dtype_bytes(value.dtype) + b":" + np.asarray(value).tobytes() - ) + return _framed(b"V", scalar + fields) + return _framed(b"S", scalar + b":" + np.asarray(value).tobytes()) kind = _framed(b"t", _type_name(value)) if isinstance(value, int): return _framed(b"I", kind + str(int(value)).encode()) From b780d8587f2552d5fd06a97cb5066611e66d14e6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:05:16 +0400 Subject: [PATCH 14/16] Set the pool tests' memory caps above an idle worker's footprint On the Linux CI runners a fresh worker holds about 0.5 GiB once it has imported microcosm.build (torch and pandas), so the fixed 512 MiB cap killed workers while they started and test_a_worker_over_its_memory_cap_is_stopped_ and_its_unit_run_again failed on both engine-free legs. A module fixture now measures an idle worker's peak, and each cap test sets its cap 256 MiB above it and allocates 768 MiB. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_worker_pool.py | 52 ++++++++++++++----- 1 file changed, 40 insertions(+), 12 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py index 7637cbc6be..4999edf15f 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -38,6 +38,8 @@ MIB = 1024 * 1024 TEST_SECONDS_LIMIT = 120 +#: Room above an idle worker's footprint before a test's memory cap. +CAP_MARGIN = 256 * MIB @pytest.fixture(autouse=True) @@ -61,6 +63,25 @@ def expire(signum, frame): assert leftover == [] +@pytest.fixture(scope="module") +def idle_worker_bytes() -> int: + """The most memory a worker here holds while it starts and waits. + + A worker imports ``microcosm.build``, and so torch and pandas: about + 0.2 GiB on macOS and about 0.5 GiB on the Linux CI runners, varying from + start to start. Memory caps in these tests sit ``CAP_MARGIN`` above this + figure, not at a fixed number a fresh worker might already pass. + """ + with WorkerPool( + WorkerPoolSettings(workers=1, memory_poll_seconds=0.02), + unit_function=units.sleep_then_return, + ) as pool: + list(pool.map([(0, 1.0)])) + peak = pool.report().peak_worker_memory_bytes + assert peak is not None + return peak + + def test_results_come_back_in_unit_order_whatever_order_they_finish() -> None: # Earlier units sleep longer, so they finish after later ones. work = [(index, 0.6 - 0.15 * index) for index in range(4)] @@ -189,15 +210,15 @@ def test_a_unit_that_keeps_killing_its_worker_stops_the_run_with_its_label() -> def test_a_worker_over_its_memory_cap_is_stopped_and_its_unit_run_again( - tmp_path, + tmp_path, idle_worker_bytes ) -> None: marker = tmp_path / "held" - cap = 512 * MIB + cap = idle_worker_bytes + CAP_MARGIN with WorkerPool( WorkerPoolSettings(workers=1, memory_cap_bytes=cap, memory_poll_seconds=0.05), unit_function=units.hold_memory_on_first_attempt, ) as pool: - results = list(pool.map([(7, str(marker), 1_024)])) + results = list(pool.map([(7, str(marker), 3 * CAP_MARGIN // MIB)])) report = pool.report() assert results[0][0] == 7 @@ -207,15 +228,19 @@ def test_a_worker_over_its_memory_cap_is_stopped_and_its_unit_run_again( assert report.peak_worker_memory_bytes > cap -def test_a_unit_that_needs_more_than_the_memory_cap_stops_the_run() -> None: +def test_a_unit_that_needs_more_than_the_memory_cap_stops_the_run( + idle_worker_bytes, +) -> None: with WorkerPool( WorkerPoolSettings( - workers=1, memory_cap_bytes=512 * MIB, memory_poll_seconds=0.05 + workers=1, + memory_cap_bytes=idle_worker_bytes + CAP_MARGIN, + memory_poll_seconds=0.05, ), unit_function=units.always_hold_memory, ) as pool: with pytest.raises(WorkerPoolUnitError, match="unit 1/1") as failure: - list(pool.map([1_024])) + list(pool.map([3 * CAP_MARGIN // MIB])) assert len(failure.value.causes) == 2 assert all("memory cap" in cause for cause in failure.value.causes) @@ -528,17 +553,20 @@ def test_a_result_the_parent_cannot_unpickle_stops_the_run_with_its_label() -> N list(pool.map([0])) -def test_memory_a_unit_leaves_behind_is_not_charged_to_the_next_unit() -> None: +def test_memory_a_unit_leaves_behind_is_not_charged_to_the_next_unit( + idle_worker_bytes, +) -> None: # The memory thread's first reading comes long after this test ends, so - # only the reading taken when unit 0 returns can see the 600 MiB. + # only the reading taken when unit 0 returns can see what it keeps. settings = WorkerPoolSettings( workers=1, - memory_cap_bytes=400 * MIB, + memory_cap_bytes=idle_worker_bytes + CAP_MARGIN, memory_poll_seconds=300.0, max_attempts=1, ) + kept = 3 * CAP_MARGIN // MIB with WorkerPool(settings, unit_function=units.keep_memory_after_returning) as pool: - assert list(pool.map([(0, 600), (1, 0)])) == [0, 1] + assert list(pool.map([(0, kept), (1, 0)])) == [0, 1] report = pool.report() assert report.failed_attempts == () @@ -641,7 +669,7 @@ def has_exited(worker): def test_a_stale_memory_reading_does_not_kill_a_worker_on_a_later_unit( - monkeypatch, tmp_path + monkeypatch, tmp_path, idle_worker_bytes ) -> None: marker = tmp_path / "unit-0-started" real_reading = worker_pool_module.process_memory_bytes @@ -662,7 +690,7 @@ def reading(pid): monkeypatch.setattr(worker_pool_module, "process_memory_bytes", reading) settings = WorkerPoolSettings( workers=1, - memory_cap_bytes=400 * MIB, + memory_cap_bytes=idle_worker_bytes + CAP_MARGIN, memory_poll_seconds=0.05, max_attempts=1, ) From 47bf7bb0bf02a3f6a608099f7fca609666126de0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:42:40 +0400 Subject: [PATCH 15/16] Read a fresh child process in the memory-reading test On the engine-free (3.13) runner the test process, an hour into the run and holding 3.2 GB, showed the same footprint before and after allocating 256 MiB: its C allocator can hand out a freed block that is already resident. The test now reads a fresh child process before and after it allocates, and checks the reading is None once the child has exited. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_worker_pool.py | 41 ++++++++++++++++--- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py index 4999edf15f..d19c65b4fc 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_worker_pool.py @@ -365,13 +365,44 @@ def test_functions_a_worker_cannot_import_are_refused_before_any_worker_starts() ) -def test_process_memory_bytes_sees_this_process_grow() -> None: - before = process_memory_bytes(os.getpid()) - held = np.ones(256 * MIB // 8) - after = process_memory_bytes(os.getpid()) +def test_process_memory_bytes_sees_a_process_grow_and_exit() -> None: + """Read a fresh child process, not this one. + + A test process that has run for an hour can hold a large freed block its C + allocator reuses, so a new array there may add no resident pages at all + (seen on the Linux CI runners: the same 3.2 GB before and after). + """ + script = ( + "import sys\n" + "import numpy as np\n" + "print('started', flush=True)\n" + "sys.stdin.readline()\n" + "held = np.ones(256 * 1024 * 1024 // 8)\n" + "print('holding', flush=True)\n" + "sys.stdin.readline()\n" + ) + child = subprocess.Popen( + [sys.executable, "-c", script], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + try: + assert child.stdout.readline().strip() == "started" + before = process_memory_bytes(child.pid) + child.stdin.write("\n") + child.stdin.flush() + assert child.stdout.readline().strip() == "holding" + after = process_memory_bytes(child.pid) + finally: + child.kill() + child.wait() + child.stdin.close() + child.stdout.close() + assert before is not None and before > 10 * MIB assert after - before >= 200 * MIB - del held + assert process_memory_bytes(child.pid) is None # Exited and reaped. def _held_by_another_thread(lock) -> bool: From 1828a1e96ef9464aee98400e9728e478fb6126f7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:45:16 +0400 Subject: [PATCH 16/16] Re-run CI: two jobs failed in setup when GitHub's API was unavailable engine-free (3.14) and engine-uk (3.14) stopped after 18 s, before any test ran, with "No server is currently available to service your request" while fetching a release. Jobs cannot be re-run while their workflow run is still in progress, so this empty commit starts a new run. Co-Authored-By: Claude Opus 5.5