From 554490018cc3f1ecf80cec93139dfdcf8c03e1c7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:56:47 +0400 Subject: [PATCH 01/26] Add failing tests for pooled post-export scoring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tracker task 1.4 · 7. The tests require the release tool's _PooledPostExportScorer to score the engine-free dry run's recorded requests in spawned pool workers and serve each consumer, run again in the parent, byte-identical outputs to the serial scorer at one and several workers (on the fake engine and on policyengine-us); the serial scorer's refusals to happen in the workers with the serial error's class name and text; the merged baseline pass to fall back as the serial scorer does; a changed batch file and a pool failure to stop scoring; and a request the dry run did not record to be refused. They also require POST_EXPORT_SCORING_METHOD raised to household_batched_written_h5_v2, the held-out reports to re-raise WorkerPoolError, and the export probe to register every stage's baseline plan, score in the pool, write each worker pass's timing and read one batch at a time in its household row map. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pool.py | 180 +++++ .../us/test_us_post_export_pooled_scoring.py | 691 ++++++++++++++++++ .../us/test_us_post_export_probe.py | 177 ++++- .../us/test_us_post_export_scoring.py | 11 +- .../engine_free/us/test_us_spine_blindness.py | 3 + .../us/test_us_post_export_scoring.py | 98 +++ .../microcosm_build/us_post_export_pool.py | 216 ++++++ .../microcosm_build/us_post_export_probe.py | 14 +- 8 files changed, 1381 insertions(+), 9 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py create mode 100644 test_support/microcosm_build/us_post_export_pool.py diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py new file mode 100644 index 0000000000..dd82f0ffac --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py @@ -0,0 +1,180 @@ +"""The units, results and worker entry points of pooled post-export scoring. + +``microcosm.build.us_runtime.post_export_pool`` holds what the release tool's +pooled scorer sends to pool workers and what they send back. These tests +check its own rules: what a pass and a unit accept, how a failure a worker +returns is raised again in the parent, and how a worker finds the release +tool. The scoring itself is tested in ``test_us_post_export_pooled_scoring.py``. +""" + +from __future__ import annotations + +import pickle +import sys + +import pytest + +from microcosm.build.us_runtime.post_export_requests import ParameterChangesReform + +KEY = ("income_tax", 2024, None) +LATER_KEY = ("income_tax", 2026, None) + + +@pytest.fixture +def pool_module(): + import microcosm.build.us_runtime.post_export_pool as module + + return module + + +def _unit(pool_module, **overrides): + fields = { + "consumer": "reform_validation", + "reformed_simulation": 2, + "reform": ParameterChangesReform({"gov.irs.fixture": {"2024-01-01": 1}}), + "passes": (pool_module.PostExportPass("reform_validation reform x", (KEY,)),), + "batch_start": 0, + "batch_stop": 4, + "n_batches": 4, + **overrides, + } + return pool_module.PostExportUnit(**fields) + + +def test_a_pass_holds_unique_keys_in_ascending_period_order(pool_module) -> None: + scoring_pass = pool_module.PostExportPass("label", [KEY, LATER_KEY]) + assert scoring_pass.keys == (KEY, LATER_KEY) + with pytest.raises(ValueError, match="ascending period order"): + pool_module.PostExportPass("label", (LATER_KEY, KEY)) + with pytest.raises(ValueError, match="repeats a key"): + pool_module.PostExportPass("label", (KEY, KEY)) + with pytest.raises(ValueError, match="has no keys"): + pool_module.PostExportPass("label", ()) + with pytest.raises(ValueError, match="needs a label"): + pool_module.PostExportPass("", (KEY,)) + for bad in ( + ("income_tax", "2024", None), + ("income_tax", True, None), + ("", 1, None), + ): + with pytest.raises(ValueError, match="post-export key"): + pool_module.PostExportPass("label", (bad,)) + + +def test_a_unit_names_its_batches_and_its_reform(pool_module) -> None: + unit = _unit(pool_module) + assert pickle.loads(pickle.dumps(unit)) == unit + with pytest.raises(TypeError): + hash(unit) + assert unit.describe() == ( + "post-export reform_validation reformed simulation 2 (1 pass(es), first " + "'reform_validation reform x'), all 4 batch(es)" + ) + baseline = _unit( + pool_module, + consumer=None, + reformed_simulation=None, + reform=None, + passes=(pool_module.PostExportPass("merged baseline plan", (KEY,)),), + batch_start=1, + batch_stop=3, + ) + assert baseline.describe() == "post-export merged baseline plan, batches 2-3 of 4" + for start, stop in ((0, 0), (3, 2), (-1, 2), (0, 5)): + with pytest.raises(ValueError, match="non-empty range"): + _unit(pool_module, batch_start=start, batch_stop=stop) + with pytest.raises(ValueError, match="names no reformed simulation"): + _unit(pool_module, reform=None) + with pytest.raises(ValueError, match="names the consumer"): + _unit(pool_module, consumer=None) + with pytest.raises(TypeError, match="reformed simulation's number"): + _unit(pool_module, reformed_simulation=None) + with pytest.raises(TypeError, match="description"): + _unit(pool_module, reform=object()) + with pytest.raises(ValueError, match="PostExportPass"): + _unit(pool_module, passes=()) + + +class _FixtureValueError(ValueError): + pass + + +class _UnprintableError(RuntimeError): + def __str__(self) -> str: + raise TypeError("no text") + + +@pytest.mark.parametrize( + ("error", "name", "base", "text"), + [ + (KeyError("medicare_enrolled"), "KeyError", KeyError, "'medicare_enrolled'"), + ( + _FixtureValueError("bad value"), + "_FixtureValueError", + ValueError, + "bad value", + ), + (RuntimeError("fixture engine refuses x"), "RuntimeError", RuntimeError, None), + ( + _UnprintableError(), + "_UnprintableError", + RuntimeError, + "", + ), + ], +) +def test_a_returned_failure_raises_with_the_workers_class_name_and_text( + pool_module, error, name, base, text +) -> None: + """A report that records ``f"{type(error).__name__}: {error}"`` records + what the serial scorer would have, and ``except`` on the built-in base + still catches it.""" + try: + raise error + except Exception as raised: + failure = pool_module.PostExportUnitFailure.from_exception("scoring", raised) + failure = pickle.loads(pickle.dumps(failure)) + rebuilt = failure.exception() + assert type(rebuilt).__name__ == name + assert isinstance(rebuilt, base) + expected = str(error) if text is None else text + assert str(rebuilt) == expected + assert f"{type(rebuilt).__name__}: {rebuilt}" == f"{name}: {expected}" + assert name in rebuilt.worker_traceback + with pytest.raises(ValueError, match="Unknown post-export failure stage"): + pool_module.PostExportUnitFailure.from_exception("elsewhere", error) + + +def test_a_worker_finds_a_loaded_release_tool_or_loads_it_once( + pool_module, tmp_path, monkeypatch +) -> None: + tool = tmp_path / "fixture_release_tool.py" + tool.write_text("LOADS = globals().get('LOADS', 0) + 1\n") + loaded = pool_module.release_tool("fixture_release_tool", tool) + try: + assert loaded.LOADS == 1 + assert sys.modules["fixture_release_tool"] is loaded + # Found again, under its name or as the main script spawn re-ran. + assert pool_module.release_tool("fixture_release_tool", tool) is loaded + del sys.modules["fixture_release_tool"] + monkeypatch.setitem(sys.modules, "__mp_main__", loaded) + assert pool_module.release_tool("fixture_release_tool", tool) is loaded + assert "fixture_release_tool" not in sys.modules + finally: + sys.modules.pop("fixture_release_tool", None) + # A different module already holding the name is left alone. + other = tmp_path / "other.py" + other.write_text("LOADS = 0\n") + monkeypatch.delitem(sys.modules, "__mp_main__") + occupant = pool_module.release_tool("fixture_release_tool", other) + try: + fresh = pool_module.release_tool("fixture_release_tool", tool) + assert fresh is not occupant and fresh.LOADS == 1 + assert sys.modules["fixture_release_tool"] is occupant + finally: + for name in [ + name + for name, module in sys.modules.items() + if getattr(module, "__file__", None) in (str(tool), str(other)) + ]: + sys.modules.pop(name, None) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py new file mode 100644 index 0000000000..01e866a1d0 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -0,0 +1,691 @@ +"""Pooled post-export scoring (tracker task 1.4 · 7). + +``_PooledPostExportScorer`` scores the requests the engine-free dry run +recorded in the shared worker pool and serves each consumer, when it runs +again in the parent, from the results. These tests run the shipped consumers +through it on the scoring tests' fake engine, in spawned workers, and require: + +- every file post-export scoring writes, and the manifests' scoring block, to + be byte-identical to the serial scorer's, at one and at three workers + (``assert_identical_across_worker_counts``), with only the block's + ``execution`` record (run metadata) apart; +- the serial scorer's refusals to happen in the workers, with the serial + error's class name and text: a population aggregate in a multi-batch pass, + a baseline-branch reader in a reform pass, a reform that moves a + behavioral-response parameter; +- the merged baseline pass's failure to fall back to each consumer's own pass, + as the serial scorer does, a changed batch file to stop scoring, and a + request the dry run did not record to be refused. +""" + +# The ``builder`` fixture is imported, and each test takes it by name. +# ruff: noqa: F401, F811 +from __future__ import annotations + +import json +import os +import sys +import types +from collections import defaultdict +from pathlib import Path + +import pytest + +from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, + ParameterChangesReform, +) +from microcosm.build.us_runtime.reform_validation import US_RELEASE_SPM_SELECTION +from microcosm.build.worker_pool import ( + WorkerPoolError, + WorkerPoolSettings, + WorkerPoolUnitError, +) +from microcosm.calibrate import TargetRegistry +from test_support.microcosm_build.us_post_export_pool import ( + COMPUTES, + ENGINE_LOG, + FAIL_ON, + FakeMicrosimulation, + build_fake_parameter_reform, + build_fake_reform, + engine_log, + identity_dataset, +) +from test_support.microcosm_build.us_post_export_scoring import ( + ReformValidationSpec, + _full_in_sample_fit, + _nested_frame, + _plan_args, + _written_h5, + builder, + reform_validation_module, + smoke_module, +) +from test_support.microcosm_build.worker_pool_identity import ( + assert_identical_across_worker_counts, + canonical_result_bytes, +) + +N_HOUSEHOLDS = 7 +BATCH_SIZE = 3 + + +@pytest.fixture +def pooled_reforms(monkeypatch, builder): + """The parent builds the fake reforms the workers build from descriptions, + and the demographics writer reads no H5 for its geography counts.""" + monkeypatch.setattr(smoke_module, "_build_reform", build_fake_reform) + monkeypatch.setattr(ReformValidationSpec, "build_reform", build_fake_reform) + monkeypatch.setattr( + reform_validation_module, "_build_parameter_reform", build_fake_parameter_reform + ) + monkeypatch.setattr( + builder, "geography_coverage_payload", lambda path: {"h5": Path(path).name} + ) + for name in (FAIL_ON, COMPUTES, ENGINE_LOG): + monkeypatch.delenv(name, raising=False) + + +def _release_plan(builder): + """The plan ``_main`` records for the nested frame, with a full fit.""" + fit = _full_in_sample_fit(builder.PERIOD) + plan = builder._record_post_export_scoring_plan( + _plan_args(), + n_households=N_HOUSEHOLDS, + result=fit, + release_id="fixture-release", + ) + assert plan.error is None + return plan, fit + + +def _pooling(builder, workers: int, **settings): + return builder._PostExportPooling( + WorkerPoolSettings(workers=workers, **settings), + chosen_by="test", + microsimulation_cls=FakeMicrosimulation, + dataset_from_frame=identity_dataset, + reform_builder=build_fake_reform, + ) + + +def _load(frame): + def load_frame(path, *, expected_sha256=None): + return frame + + return load_frame + + +def _serial_scorer(builder, plan, directory: Path): + return builder._HouseholdBatchedPostExportScorer( + _written_h5(directory), + maximum_microsim_batch_size=BATCH_SIZE, + expected_n_households=N_HOUSEHOLDS, + microsimulation_cls=FakeMicrosimulation, + dataset_from_frame=identity_dataset, + load_frame=_load(_nested_frame()), + baseline_plans=plan.baseline_plans, + ) + + +def _pooled_scorer(builder, plan, directory: Path, workers: int, **settings): + return builder._PooledPostExportScorer( + _written_h5(directory), + maximum_microsim_batch_size=BATCH_SIZE, + expected_n_households=N_HOUSEHOLDS, + consumer_requests=plan.consumer_requests, + pooling=_pooling(builder, workers, **settings), + load_frame=_load(_nested_frame()), + ) + + +def _certify_outputs(builder, scorer, plan, fit, release_dir: Path): + """Run every post-export stage as ``_certify_us_build`` does. + + Returns the files written and the manifests' scoring block, and, apart, + that block's ``execution`` record (run metadata). + """ + release_dir.mkdir(parents=True) + try: + smoke = scorer.open_consumer( + "reform_coverage_smoke", + plan.baseline_plan("reform_coverage_smoke"), + planned_reform_passes=plan.planned_reform_passes("reform_coverage_smoke"), + ) + gate = builder.us_reform_coverage_smoke_gate( + simulate=smoke.simulate, period=builder.PERIOD + ) + smoke_record = scorer.finish_consumer(smoke) + (release_dir / "reform_coverage_smoke.json").write_text( + json.dumps( + { + "schema_version": 1, + "enforced": True, + "reform_coverage_smoke": { + "passed": gate.passed, + "failures": list(gate.failures), + "details": dict(gate.details), + }, + "post_export_scoring": smoke_record, + }, + indent=2, + sort_keys=True, + ) + + "\n" + ) + builder._write_reform_validation( + release_dir=release_dir, + dataset_path=scorer.dataset_path, + result=fit, + registry=TargetRegistry((), country="us"), + release_id="fixture-release", + simulate_out_of_sample=True, + post_export_scorer=scorer, + baseline_plan=plan.baseline_plan("reform_validation"), + planned_reform_passes=plan.planned_reform_passes("reform_validation"), + ) + common = dict( + release_dir=release_dir, + dataset_path=scorer.dataset_path, + release_id="fixture-release", + post_export_scorer=scorer, + ) + builder._write_demographics( + **common, baseline_plan=plan.baseline_plan("demographics") + ) + builder._write_ssi_social_security_holdout( + **common, baseline_plan=plan.baseline_plan("ssi_social_security_holdout") + ) + builder._write_medicare_irmaa_holdout( + **common, baseline_plan=plan.baseline_plan("medicare_irmaa_holdout") + ) + block = builder._post_export_scoring_manifest_block(scorer) + finally: + builder._close_post_export_scorer(scorer) + execution = block.pop("execution") + files = {path.name: path.read_bytes() for path in sorted(release_dir.iterdir())} + return {"files": files, "block": block}, execution + + +def _reform_unit_count(plan) -> int: + return sum( + len(recorded.simulations) for recorded in plan.consumer_requests.values() + ) + + +def test_pooled_scoring_writes_the_serial_scorers_bytes_at_any_worker_count( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """Every output file and the manifests' block, scored in spawned workers, + are byte-identical to the serial scorer's at one and three workers. Each + worker engine is built as the serial scorer builds it: one batch at a + time, released before the next, with the SPM selection, a reform's + system alone, and its keys in ascending period order.""" + plan, fit = _release_plan(builder) + serial, serial_execution = _certify_outputs( + builder, + _serial_scorer(builder, plan, tmp_path / "serial"), + plan, + fit, + tmp_path / "serial" / "release", + ) + assert serial_execution == {"mode": "serial"} + assert set(serial["files"]) == { + "demographics.json", + "reform_coverage_smoke.json", + "reform_validation.json", + "us_medicare_irmaa_holdout.json", + "us_ssi_social_security_holdout.json", + } + executions, logs = {}, {} + + def run(workers: int): + directory = tmp_path / f"pooled-{workers}" + logs[workers] = directory / "engines" + logs[workers].mkdir(parents=True) + monkeypatch.setenv(ENGINE_LOG, str(logs[workers])) + outputs, executions[workers] = _certify_outputs( + builder, + _pooled_scorer(builder, plan, directory, workers), + plan, + fit, + directory / "release", + ) + return outputs + + pooled = assert_identical_across_worker_counts(run, worker_counts=(1, 3)) + assert canonical_result_bytes(pooled) == canonical_result_bytes(serial) + + reform_units = _reform_unit_count(plan) + for workers, execution in executions.items(): + report = execution.pop("report") + assert execution == { + "mode": "pooled", + "chosen_by": "test", + "requested_workers": workers, + "workers": workers, + "memory_cap_bytes": None, + "max_units_per_worker": None, + "max_attempts": 2, + "max_units_ahead": None, + "worker_environment_variables": [], + "units": {"baseline": workers, "reform": reform_units}, + } + assert report["units_completed"] == workers + reform_units + assert report["failed_attempts"] == [] + assert 1 <= report["max_live_workers"] <= workers + + events = engine_log(logs[3]) + constructions = [event for event in events if event["event"] == "construct"] + assert os.getpid() not in {event["pid"] for event in events} + assert len({event["pid"] for event in constructions}) > 1 + assert all( + event["spm"] == dict(US_RELEASE_SPM_SELECTION) for event in constructions + ) + assert all(not event["reform_argument"] for event in constructions) + assert all(event["unreleased"] == 0 for event in constructions) + assert all(len(event["households"]) <= BATCH_SIZE for event in constructions) + periods = defaultdict(list) + for event in events: + if event["event"] == "calculate": + periods[(event["pid"], event["engine"])].append(event["period"]) + assert periods and all(found == sorted(found) for found in periods.values()) + + +def _fixture_consumer(asks): + """A consumer that reads the baseline, opens one reformed simulation per + description in ``asks`` and asks it for its keys.""" + + def consumer(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + baseline = simulate(None) + totals = [baseline.calculate("age", 2024).sum()] + for description, keys in asks(totals[0]): + reformed = simulate( + description if records_only else build_fake_reform(description) + ) + for variable, period in keys: + totals.append(reformed.calculate(variable, period).sum()) + return totals + + return consumer + + +def _fixture_plan(builder, consumer): + return builder._post_export_scoring_plan( + n_households=N_HOUSEHOLDS, + maximum_microsim_batch_size=BATCH_SIZE, + consumers={"fixture": consumer}, + ) + + +FIXTURE_REFORM = ParameterChangesReform({"gov.irs.fixture": {"2024-01-01": 1}}) +OTHER_REFORM = ParameterChangesReform({"gov.irs.other": {"2024-01-01": 2}}) + + +def test_a_reform_request_the_dry_run_did_not_record_is_refused( + builder, + pooled_reforms, + tmp_path, +) -> None: + """The dry run sees zeros; a consumer that then asks for another key + would be served values scored for no recorded request.""" + + def asks(total): + return [(FIXTURE_REFORM, [("income_tax" if total == 0 else "snap", 2024)])] + + plan = _fixture_plan(builder, _fixture_consumer(asks)) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + with pytest.raises( + RuntimeError, match="not the next reform pass its engine-free dry run" + ): + _fixture_consumer(asks)(scoring.simulate) + finally: + scorer.close() + + +def test_a_consumer_that_skips_a_recorded_reform_pass_is_refused( + builder, + pooled_reforms, + tmp_path, +) -> None: + def asks(total): + first = [(FIXTURE_REFORM, [("income_tax", 2024)])] + return first + [(OTHER_REFORM, [("snap", 2024)])] if total == 0 else first + + consumer = _fixture_consumer(asks) + plan = _fixture_plan(builder, consumer) + assert plan.planned_reform_passes("fixture") == 2 + scorer = _pooled_scorer(builder, plan, tmp_path, 2) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + consumer(scoring.simulate) + with pytest.raises(RuntimeError, match=r"reformed simulation\(s\) \[1\]"): + scorer.finish_consumer(scoring) + finally: + scorer.close() + + +def test_a_baseline_key_outside_the_plan_is_refused( + builder, + pooled_reforms, + tmp_path, +) -> None: + def consumer(simulate): + baseline = simulate(None) + total = baseline.calculate("age", 2024).sum() + return baseline.calculate("age" if total == 0 else "snap", 2024).sum() + + plan = _fixture_plan(builder, consumer) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + with pytest.raises(RuntimeError, match="which its recorded plan does not hold"): + consumer(scoring.simulate) + finally: + scorer.close() + + +def test_only_recorded_consumers_open_each_once( + builder, pooled_reforms, tmp_path +) -> None: + plan = _fixture_plan(builder, _fixture_consumer(lambda total: [])) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + with pytest.raises(ValueError, match="has no recorded requests"): + scorer.open_consumer("demographics", ()) + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + scorer.finish_consumer(scoring) + with pytest.raises(ValueError, match="opened on this scorer already"): + scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + finally: + scorer.close() + + +RESPONSE_REFORM = ParameterChangesReform( + {"gov.simulation.labor_supply_responses.elasticities.income": {"2024-01-01": 0.25}} +) + + +@pytest.mark.parametrize( + ("description", "variable", "computes", "counts"), + [ + # A population aggregate, computed in a multi-batch pass. + ( + FIXTURE_REFORM, + "medicaid", + {"medicaid": ["medicaid_slcsp_state_average_cost_index"]}, + (1, 1), + ), + # A baseline-branch reader, computed by a reform engine. + ( + FIXTURE_REFORM, + "income_tax", + {"income_tax": ["relative_income_change"]}, + (1, 1), + ), + # A reform that moves a behavioral-response parameter: refused before + # its pass, as the serial scorer refuses it. + (RESPONSE_REFORM, "income_tax", {}, (1, 0)), + ], + ids=["population_aggregate", "baseline_branch_reader", "behavioral_response"], +) +def test_the_workers_refuse_what_the_serial_scorer_refuses( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + description, + variable, + computes, + counts, +) -> None: + """The refusal reaches the consumer as the serial scorer's error, with its + class name and text, and the consumer's counts move as the serial + scorer's: (reform systems, reform passes).""" + monkeypatch.setenv(COMPUTES, json.dumps(computes)) + + def asks(total): + return [(description, [(variable, 2024)])] + + consumer = _fixture_consumer(asks) + plan = _fixture_plan(builder, consumer) + errors, observed = {}, {} + for mode in ("serial", "pooled"): + scorer = ( + _serial_scorer(builder, plan, tmp_path / mode) + if mode == "serial" + else _pooled_scorer(builder, plan, tmp_path / mode, 1) + ) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + with pytest.raises(RuntimeError) as raised: + consumer(scoring.simulate) + errors[mode] = raised.value + observed[mode] = (scoring.reform_systems, scoring.reform_passes) + finally: + scorer.close() + assert type(errors["pooled"]).__name__ == type(errors["serial"]).__name__ + assert str(errors["pooled"]) == str(errors["serial"]) + assert observed == {"serial": counts, "pooled": counts} + assert "Traceback" in errors["pooled"].worker_traceback + + +def test_a_failed_merged_pass_falls_back_as_the_serial_scorer_does( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + capsys, +) -> None: + """A key only the Medicare holdout planned fails the merged pass; every + consumer then scores its own plan, and only that holdout records itself + unavailable, with the error the serial scorer records.""" + monkeypatch.setenv(FAIL_ON, "medicare_enrolled") + plan, fit = _release_plan(builder) + serial, _ = _certify_outputs( + builder, + _serial_scorer(builder, plan, tmp_path / "serial"), + plan, + fit, + tmp_path / "serial" / "release", + ) + capsys.readouterr() + pooled, execution = _certify_outputs( + builder, + _pooled_scorer(builder, plan, tmp_path / "pooled", 2), + plan, + fit, + tmp_path / "pooled" / "release", + ) + assert "merged baseline plan failed" in capsys.readouterr().out + assert canonical_result_bytes(pooled) == canonical_result_bytes(serial) + holdout = json.loads(pooled["files"]["us_medicare_irmaa_holdout.json"]) + assert holdout["status"] == "unavailable" + assert holdout["error"] == "RuntimeError: fixture engine refuses medicare_enrolled" + planned = [name for name, keys in plan.baseline_plans.items() if keys] + assert execution["report"]["units_completed"] == ( + 2 + 2 * len(planned) + _reform_unit_count(plan) + ) + + +def test_a_changed_batch_file_stops_pooled_scoring( + builder, + pooled_reforms, + tmp_path, +) -> None: + plan, _ = _release_plan(builder) + scorer = _pooled_scorer(builder, plan, tmp_path, 2) + try: + path, _ = scorer._batches().files[1] + Path(path).write_bytes(Path(path).read_bytes() + b"changed") + with pytest.raises(builder.PostExportBatchFileError, match="has SHA-256"): + scorer.open_consumer( + "reform_coverage_smoke", plan.baseline_plan("reform_coverage_smoke") + ) + # Nothing more is served, and no consumer falls back to its own pass. + with pytest.raises(RuntimeError, match="stopped earlier"): + scorer.open_consumer( + "reform_validation", plan.baseline_plan("reform_validation") + ) + finally: + scorer.close() + + +def test_a_worker_batch_file_failure_is_raised_as_the_tools_own_error(builder) -> None: + from microcosm.build.us_runtime.post_export_pool import PostExportUnitFailure + + try: + raise builder.PostExportBatchFileError("batch 2 changed") + except builder.PostExportBatchFileError as error: + failure = builder._post_export_unit_failure("scoring", error) + assert failure.batch_file_error + with pytest.raises(builder.PostExportBatchFileError, match="batch 2 changed"): + builder._raise_post_export_worker_failure(failure) + other = PostExportUnitFailure.from_exception("scoring", KeyError("snap")) + with pytest.raises(KeyError) as raised: + builder._raise_post_export_worker_failure(other) + assert isinstance(raised.value.__cause__, builder._PostExportWorkerTracebackError) + + +@pytest.mark.parametrize( + "writer", ["_write_ssi_social_security_holdout", "_write_medicare_irmaa_holdout"] +) +def test_the_holdouts_stop_on_a_pool_failure(builder, tmp_path, writer) -> None: + """A pool that cannot score the H5 is not an unavailable measurement.""" + + class FailingScorer: + def open_consumer(self, *args, **kwargs): + raise WorkerPoolError("a worker could not be started") + + with pytest.raises(WorkerPoolError, match="could not be started"): + getattr(builder, writer)( + release_dir=tmp_path, + dataset_path=tmp_path / "populace_us_2024.h5", + release_id="fixture-release", + post_export_scorer=FailingScorer(), + baseline_plan=(("age", builder.PERIOD, None),), + ) + assert not list(tmp_path.iterdir()) + + +class _ParentOnly: + """A value whose class a spawned worker cannot import.""" + + +def test_a_reform_a_worker_cannot_unpickle_stops_the_run_and_names_its_unit( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + module = types.ModuleType("parent_only_post_export_values") + _ParentOnly.__module__ = module.__name__ + module._ParentOnly = _ParentOnly + monkeypatch.setitem(sys.modules, module.__name__, module) + description = ParameterChangesReform( + {"gov.irs.fixture": {"2024-01-01": _ParentOnly()}} + ) + + def asks(total): + return [(description, [("income_tax", 2024)])] + + consumer = _fixture_consumer(asks) + plan = _fixture_plan(builder, consumer) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + with pytest.raises( + WorkerPoolUnitError, match=r"fixture reformed simulation 0 .*all 3 batch" + ): + consumer(scoring.simulate) + finally: + scorer.close() + + +def test_the_pool_starts_no_more_workers_than_units( + builder, + pooled_reforms, + tmp_path, +) -> None: + plan = _fixture_plan(builder, _fixture_consumer(lambda total: [])) + scorer = _pooled_scorer(builder, plan, tmp_path, 8) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + scorer.finish_consumer(scoring) + execution = scorer.execution_record() + finally: + scorer.close() + assert execution["units"] == {"baseline": 3, "reform": 0} + assert (execution["requested_workers"], execution["workers"]) == (8, 3) + assert execution["report"]["max_live_workers"] <= 3 + + +def test_workers_get_the_lock_check_record_and_the_set_environment( + builder, + monkeypatch, +) -> None: + from microcosm.build.us_runtime import take_up_contract + + monkeypatch.setattr( + take_up_contract, + "us_engine_abi_lock_check_environment", + lambda: {"MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD": "fixture record"}, + ) + pooling = _pooling( + builder, 6, worker_environment={"OMP_NUM_THREADS": "1"}, memory_cap_bytes=2**30 + ) + settings = builder._post_export_worker_settings(pooling, workers=4) + assert settings.workers == 4 + assert settings.memory_cap_bytes == 2**30 + assert settings.worker_environment == { + "OMP_NUM_THREADS": "1", + "MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD": "fixture record", + } + assert builder._post_export_worker_settings(pooling, workers=9).workers == 6 + monkeypatch.setattr( + take_up_contract, "us_engine_abi_lock_check_environment", lambda: {} + ) + inherited = builder._post_export_worker_settings(_pooling(builder, 2), workers=2) + assert inherited.worker_environment is None + + +def test_the_plan_records_each_consumers_requests_and_passes(builder) -> None: + """The reform passes hold every reform request, in order, and the + pre-OBBBA state's two keys are one pass, as the serial scorer runs it.""" + plan, _ = _release_plan(builder) + assert set(plan.consumer_requests) == set(plan.baseline_plans) + for name, recorded in plan.consumer_requests.items(): + assert recorded.baseline_plan == plan.baseline_plans[name] + assert len(recorded.reform_passes) == plan.planned_reform_passes(name) + reform_keys = [ + (request.reformed_simulation, request.key) + for request in recorded.descriptors + if request.reform is not None + ] + assert reform_keys == [ + (simulation, key) + for simulation, keys in recorded.reform_passes + for key in keys + ] + validation = plan.consumer_requests["reform_validation"] + assert max(len(keys) for _, keys in validation.reform_passes) == 2 + assert "consumer_requests" not in json.dumps(plan.record()) + + +def test_the_batch_ranges_cover_every_batch_once(builder) -> None: + for n_batches in (1, 2, 3, 7, 177): + for ranges in (1, 2, 4, 17, 200): + split = builder._post_export_batch_ranges(n_batches, ranges) + assert [position for batches in split for position in batches] == list( + range(n_batches) + ) + assert len(split) == min(ranges, n_batches) + sizes = {len(batches) for batches in split} + assert max(sizes) - min(sizes) <= 1 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py index 090ce5e1f9..c5f64cdd88 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py @@ -87,11 +87,21 @@ def test_probe_runs_every_stage_on_a_subsample( json.loads(line) for line in (tmp_path / "probe" / "passes.jsonl").read_text().splitlines() ] - assert {row["stage"] for row in passes} == { + # As in certification, every engine stage's baseline plan is registered: + # one merged pass, run when the smoke opens, serves them all, so + # demographics runs no pass of its own. + assert report["stages"]["open_scorer"]["registered_consumers"] == [ "reform_coverage_smoke", "reform_validation", "demographics", + ] + assert {row["stage"] for row in passes} == { + "reform_coverage_smoke", + "reform_validation", } + assert [(row["stage"], row["label"]) for row in passes if not row["reform"]] == [ + ("reform_coverage_smoke", "merged baseline plan") + ] assert all(row["batches"] >= probe_tool.MINIMUM_BATCHES for row in passes) smoke = { @@ -1237,3 +1247,168 @@ def score(self, keys, *, label, reform_system=None, outer=None): assert received == [{"label": "fixture reform", "outer": counter}] row = json.loads(passes.read_text()) assert (row["label"], row["reform"], row["batches"]) == ("fixture reform", True, 3) + + +def test_a_pooled_probe_writes_the_serial_probes_files_and_times_its_workers( + probe_tool, builder, chain, tmp_path, monkeypatch +) -> None: + """Scored in the shared worker pool, the probe writes the serial probe's + stage files byte for byte and reaches the same verdicts; ``passes.jsonl`` + then holds each pass a worker ran, with its time and memory, each stage + records the workers' CPU time, and the report holds the pool's record.""" + import os + + import microcosm.build.us_runtime.reform_coverage_smoke as smoke_module + import microcosm.build.us_runtime.reform_validation as reform_validation_module + from microcosm.build.worker_pool import WorkerPoolSettings + from test_support.microcosm_build.us_post_export_pool import ( + Float32FakeMicrosimulation, + build_fake_parameter_reform, + build_fake_reform, + identity_dataset, + ) + + frame, path, receipt, _ = chain + monkeypatch.setattr(builder, "installed_us_engine", lambda: fixture_engine(frame)) + monkeypatch.setattr(smoke_module, "_build_reform", build_fake_reform) + monkeypatch.setattr( + reform_validation_module.ReformValidationSpec, "build_reform", build_fake_reform + ) + monkeypatch.setattr( + reform_validation_module, "_build_parameter_reform", build_fake_parameter_reform + ) + engine = { + "microsimulation_cls": Float32FakeMicrosimulation, + "dataset_from_frame": identity_dataset, + } + stages = ("reform_coverage_smoke", "reform_validation", "demographics") + serial, _ = run_fixture_probe( + probe_tool, + builder, + path, + tmp_path / "serial", + receipt=receipt, + stages=stages, + scorer_options=engine, + ) + pooled, _ = run_fixture_probe( + probe_tool, + builder, + path, + tmp_path / "pooled", + receipt=receipt, + stages=stages, + scorer_options={}, + post_export_pooling=builder._PostExportPooling( + WorkerPoolSettings(workers=2), + chosen_by="test", + reform_builder=build_fake_reform, + **engine, + ), + ) + for report in (serial, pooled): + errors = { + name: record.get("traceback") + for name, record in report["stages"].items() + if record["status"] != "completed" + } + assert not errors, errors + for filename in ( + "reform_coverage_smoke.json", + "reform_validation.json", + "demographics.json", + ): + assert (tmp_path / "pooled" / filename).read_bytes() == ( + tmp_path / "serial" / filename + ).read_bytes(), filename + assert ( + pooled["stages"]["reform_coverage_smoke"]["probes"] + == serial["stages"]["reform_coverage_smoke"]["probes"] + ) + assert [row["verdict"] for row in pooled["verdicts"]] == [ + row["verdict"] for row in serial["verdicts"] + ] + serial_block = dict(serial["post_export_scoring"]) + pooled_block = dict(pooled["post_export_scoring"]) + assert serial_block.pop("execution") == {"mode": "serial"} + execution = pooled_block.pop("execution") + assert pooled_block == serial_block + assert execution["mode"] == "pooled" + assert execution["report"]["failed_attempts"] == [] + assert execution["report"]["peak_worker_memory_bytes"] is None or ( + execution["report"]["peak_worker_memory_bytes"] > 0 + ) + + def passes(directory): + return [ + json.loads(line) + for line in (directory / "passes.jsonl").read_text().splitlines() + ] + + serial_passes, pooled_passes = ( + passes(tmp_path / "serial"), + passes(tmp_path / "pooled"), + ) + assert {(row["stage"], row["label"]) for row in pooled_passes} == { + (row["stage"], row["label"]) for row in serial_passes + } + assert all(row["process"] == "pool worker" for row in pooled_passes) + assert os.getpid() not in {row["worker_pid"] for row in pooled_passes} + assert all( + row["cpu_seconds"] >= 0 and row["worker_peak_rss_gib"] > 0 + for row in pooled_passes + ) + smoke_timing = pooled["stages"]["reform_coverage_smoke"]["timing"] + assert smoke_timing["worker_passes"] == sum( + row["stage"] == "reform_coverage_smoke" for row in pooled_passes + ) + assert smoke_timing["worker_cpu_seconds"] > 0 + assert serial["stages"]["reform_coverage_smoke"]["timing"]["worker_passes"] == 0 + assert pooled["stages"]["open_scorer"]["mode"] == "pooled" + + +def test_the_row_map_reads_no_batch_until_it_maps_an_entity(probe_tool) -> None: + """The scorer's batches are files read one at a time; the row map holds + the sequence, not every batch at once, so the smoke stage's peak is the + one-batch-at-a-time peak certification has.""" + from collections.abc import Sequence + + class UnreadBatches(Sequence): + def __len__(self) -> int: + return 3 + + def __getitem__(self, position): + raise AssertionError(f"batch {position} was read") + + probe_tool.HouseholdRowMap(UnreadBatches(), sampler=None) + + +def test_a_stage_whose_dry_run_fails_fails_alone( + probe_tool, builder, fake_reforms, chain, tmp_path, monkeypatch +) -> None: + """The probe records every stage's plan before it opens the scorer; a + stage whose dry run raises is left out of it and fails with that error, + and the other stages still score.""" + frame, path, receipt, _ = chain + monkeypatch.setattr(builder, "installed_us_engine", lambda: fixture_engine(frame)) + + def broken_consumer(self): + def consumer(simulate): + raise ValueError("fixture dry run refused") + + return consumer + + monkeypatch.setattr(probe_tool.ExportProbe, "_smoke_consumer", broken_consumer) + report, _ = run_fixture_probe( + probe_tool, + builder, + path, + tmp_path / "probe", + receipt=receipt, + stages=("reform_coverage_smoke", "demographics"), + ) + assert report["stages"]["open_scorer"]["registered_consumers"] == ["demographics"] + smoke = report["stages"]["reform_coverage_smoke"] + assert smoke["status"] == "error" + assert smoke["error"] == "ValueError: fixture dry run refused" + assert report["stages"]["demographics"]["status"] == "completed" 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 88434291d8..f3f18d68af 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 @@ -795,8 +795,11 @@ def fake_write_calibration_diagnostics( builder._write_release_calibration_diagnostics( **common, post_export_scoring=plan.record() ) + # Raised once, for the merged baseline sweeps and pooled scoring + # (decision 1.1 · 1). + assert builder.POST_EXPORT_SCORING_METHOD == "household_batched_written_h5_v2" assert captured["build"]["post_export_scoring"] == { - "method": "household_batched_written_h5", + "method": "household_batched_written_h5_v2", "maximum_batch_size": 3, "n_households": 7, "n_batches": 3, @@ -851,10 +854,12 @@ def calls_to(name: str, among=None) -> list[ast.Call]: ] # The scorer opens on the written H5 with the plan recorded before export, - # keeping its household batch files in a directory in the build's --out. + # keeping its household batch files in a directory in the build's --out, + # in the worker pool certification was given. assert [ast.unparse(call) for call in calls_to("_open_post_export_scorer")] == [ "_open_post_export_scorer(post_export_scoring_plan, dataset_path, " - "batch_parent=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY)" + "batch_parent=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY, " + "pooling=post_export_pooling)" ] # It opens the file the build wrote, which the record pins by digest # (never a previous run's bytes at the same path, microcosm#443), and diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index e0ff6f7d90..2a1fa4e7f1 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -378,6 +378,9 @@ # Reviewed held-out population-structure diagnostic over the written # H5; no population treatment. "population_structure_holdout.py", + # The units, results and worker entry points of the release's pooled + # post-export scoring; reads no frame and treats no population. + "post_export_pool.py", # Picklable descriptions of the release's post-export scoring requests # and the reforms they carry; reads no frame and treats no population. "post_export_requests.py", 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 9a42ed32f9..1288ff9ed0 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 @@ -471,3 +471,101 @@ def test_batches_read_from_their_files_equal_the_written_h5s_batches( assert_same_batch(batches[number], selected) finally: scorer.close() + + +@pytest.mark.slow +def test_pooled_scoring_gives_the_serial_scorers_bytes_on_policyengine_us( + builder, tmp_path +) -> None: + """On a written H5 of the guard households in three batches, the smoke + (a neutralization probe and a parameter-change probe) and demographics, + scored in spawned policyengine-us workers, give byte-identical outputs and + consumer records to the serial scorer at one and two workers. Each worker + rebuilds the probes' reforms from their descriptions.""" + from microcosm.build.worker_pool import WorkerPoolSettings + from test_support.microcosm_build.worker_pool_identity import ( + assert_identical_across_worker_counts, + canonical_result_bytes, + ) + + path = _write_engine_h5(builder, tmp_path / "h5", _GUARD_HOUSEHOLDS) + probes = ( + _engine_probe( + "wages_income_tax_2024", + "income_tax", + 2024, + neutralized_variable="employment_income_before_lsr", + ), + _engine_probe( + "zero_single_standard_deduction_2026", + "income_tax", + 2026, + parameter_changes={ + "gov.irs.deductions.standard.amount.SINGLE": {"2026-01-01": 0} + }, + ), + ) + + def smoke(simulate): + return builder.us_reform_coverage_smoke_gate( + simulate=simulate, probes=probes, period=builder.PERIOD + ) + + consumers = { + "reform_coverage_smoke": smoke, + "demographics": builder._demographics_consumer, + } + plan = builder._post_export_scoring_plan( + n_households=len(_GUARD_HOUSEHOLDS), + maximum_microsim_batch_size=3, + consumers=consumers, + ) + + def score(scorer): + try: + outputs = {} + for name, consumer in consumers.items(): + scoring = scorer.open_consumer( + name, + plan.baseline_plan(name), + planned_reform_passes=plan.planned_reform_passes(name), + ) + output = consumer(scoring.simulate) + record = scorer.finish_consumer(scoring) + outputs[name] = ( + (output.passed, list(output.failures), output.details) + if name == "reform_coverage_smoke" + else tuple(np.asarray(item) for item in output), + record, + ) + block = scorer.manifest_record() + finally: + scorer.close() + block.pop("execution") + return outputs, block + + serial = score( + builder._HouseholdBatchedPostExportScorer( + path, + maximum_microsim_batch_size=3, + baseline_plans=plan.baseline_plans, + ) + ) + assert serial[1]["n_batches"] == 3 + + def pooled(workers): + return score( + builder._PooledPostExportScorer( + path, + maximum_microsim_batch_size=3, + consumer_requests=plan.consumer_requests, + pooling=builder._PostExportPooling( + WorkerPoolSettings(workers=workers), chosen_by="test" + ), + ) + ) + + result = assert_identical_across_worker_counts(pooled, worker_counts=(1, 2)) + assert canonical_result_bytes(result) == canonical_result_bytes(serial) + gate = result[0]["reform_coverage_smoke"][0] + assert all(row["effect"] != 0.0 for row in gate[2]["results"].values()) diff --git a/test_support/microcosm_build/us_post_export_pool.py b/test_support/microcosm_build/us_post_export_pool.py new file mode 100644 index 0000000000..0079b00a3e --- /dev/null +++ b/test_support/microcosm_build/us_post_export_pool.py @@ -0,0 +1,216 @@ +"""Fakes a spawned pool worker can import, for pooled post-export scoring tests. + +Pooled scoring (``_PooledPostExportScorer`` in +``tools/build_us_fiscal_refresh_release.py``) sends its engine, batch dataset +and reform builder to every worker by name, so each must be a module-level +object a fresh process can import. These give the values of the scoring tests' +fake engine (:mod:`test_support.microcosm_build.us_post_export_scoring`), so the +pooled and serial scorers can be run on the same fake and compared byte for +byte. + +Behaviour a test sets in the parent reaches each worker through its +environment, which spawned workers inherit: + +- :data:`FAIL_ON`: a variable every engine refuses to compute; +- :data:`COMPUTES`: JSON mapping a variable to the watched formulas computing + it leaves a value for (the population-aggregate and baseline-branch + refusals); +- :data:`ENGINE_LOG`: a directory; each process appends one JSON line per + engine construction and per calculation to ``.jsonl`` there. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +from microcosm.build.us_runtime.post_export_requests import ParameterChangesReform +from microcosm.build.us_runtime.reform_validation import ReformValidationSpec +from microcosm.build.us_runtime.release_input_coverage import ReformCoverageProbe +from test_support.microcosm_build.us_post_export_scoring import ( + _FakeParameterTree, + _FakeReform, + _FakeSeries, + _household_positions, + _map_values, + _native_entity, + _native_values, +) + +FAIL_ON = "MICROCOSM_TEST_POST_EXPORT_FAIL_ON" +COMPUTES = "MICROCOSM_TEST_POST_EXPORT_COMPUTES" +ENGINE_LOG = "MICROCOSM_TEST_POST_EXPORT_ENGINE_LOG" + +#: Parameter paths a fake reform sets from a ``ParameterChangesReform`` +#: payload, so a reform can move a behavioral-response parameter. +_RESPONSE_PARAMETERS = "gov.simulation." + + +def _log(event: dict) -> None: + directory = os.environ.get(ENGINE_LOG) + if not directory: + return + path = Path(directory) / f"{os.getpid()}.jsonl" + with path.open("a") as handle: + handle.write(json.dumps(event, sort_keys=True) + "\n") + + +def build_fake_reform(description): + """The fake reform of a description, as the scoring tests' ``fake_reforms`` + fixture builds it in the parent: labelled by the probe's or spec's id, or + by the parameter changes' JSON.""" + if isinstance(description, ReformCoverageProbe | ReformValidationSpec): + return _FakeReform(description.id) + if isinstance(description, ParameterChangesReform): + changes = dict(description.parameter_changes) + parameters = { + path: next(iter(value.values())) if isinstance(value, dict) else value + for path, value in changes.items() + if path.startswith(_RESPONSE_PARAMETERS) + } + return _FakeReform( + json.dumps(changes, sort_keys=True, default=str), parameters=parameters + ) + raise TypeError(f"no fake reform for {type(description).__name__}") + + +def build_fake_parameter_reform(changes): + """``reform_validation._build_parameter_reform`` on the fake.""" + return build_fake_reform(ParameterChangesReform(changes)) + + +def identity_dataset(batch_frame): + """Each batch frame is its own dataset.""" + return batch_frame + + +class FakeSystem: + """A reform's rules: its fake reform and its parameter tree.""" + + def __init__(self, reform=None) -> None: + self.reform = reform + self.parameters = _FakeParameterTree( + {} if reform is None else reform.parameters + ) + + +class _FakeHolder: + def __init__(self, periods) -> None: + self._periods = periods + + def get_known_periods(self): + return sorted(self._periods) + + +#: This process's engines, to count those not yet released at a construction. +_ENGINES: list = [] + + +class FakeMicrosimulation: + """The scoring tests' fake engine as a module-level class.""" + + default_tax_benefit_system = FakeSystem + default_tax_benefit_system_instance = SimpleNamespace( + parameters=_FakeParameterTree({}) + ) + + def __init__(self, *, dataset, reform=None, tax_benefit_system=None, spm=None): + unreleased = sum(engine.dataset is not None for engine in _ENGINES) + self.dataset = dataset + self.reform = reform + self.tax_benefit_system = tax_benefit_system + self.spm = spm + self.branches: dict = {} + self.known: dict[str, set[int]] = {} + self.number = len(_ENGINES) + _ENGINES.append(self) + system_reform = getattr(tax_benefit_system, "reform", None) + _log( + { + "event": "construct", + "engine": self.number, + "households": [ + int(value) for value in dataset.table("household")["household_id"] + ], + "reform": None + if self.policy_reform is None + else self.policy_reform.label, + "reform_argument": reform is not None, + "system_reform": None if system_reform is None else system_reform.label, + "spm": spm, + "unreleased": unreleased, + } + ) + + @property + def policy_reform(self): + if self.reform is not None: + return self.reform + return getattr(self.tax_benefit_system, "reform", None) + + def get_holder(self, variable): + return _FakeHolder(self.known.get(variable, ())) + + def calculate(self, variable, period, map_to=None): + frame = self.dataset + assert frame is not None, "calculate on a released engine" + if variable == os.environ.get(FAIL_ON): + raise RuntimeError(f"fixture engine refuses {variable}") + period = int(period) + _log( + { + "event": "calculate", + "engine": self.number, + "variable": variable, + "period": period, + } + ) + computes = json.loads(os.environ.get(COMPUTES) or "{}") + for computed in (variable, *computes.get(variable, ())): + self.known.setdefault(computed, set()).add(period) + native = _native_entity(variable) + reform = self.policy_reform + delta = 0.0 if reform is None else reform.delta + values = _native_values(frame, variable, period, delta) + target = map_to or native + values = _map_values(frame, values, native, target) + weights = frame.weights_for("household").values[ + _household_positions(frame, target) + ] + return _FakeSeries(values, weights) + + +def engine_log(directory: Path) -> list[dict]: + """Every process's logged events, each with its process id.""" + events = [] + for path in sorted(Path(directory).glob("*.jsonl")): + for line in path.read_text().splitlines(): + events.append({"pid": int(path.stem), **json.loads(line)}) + return events + + +def float32_weights(series, period: int, uprating) -> _FakeSeries: + factor = np.float32(uprating.get(int(period), 1.0)) + weights = series.weights.astype(np.float32) * factor + return _FakeSeries(np.asarray(series), weights.astype(np.float64)) + + +#: The export probe tests' uprating of 2026 weights (see +#: :mod:`test_support.microcosm_build.us_post_export_probe`). +FLOAT32_UPRATING = {2026: 352_304_000 / 346_588_000} + + +class Float32FakeMicrosimulation(FakeMicrosimulation): + """:class:`FakeMicrosimulation` with policyengine-core's float32 weights, + uprated at a later period, as the export probe's tests score.""" + + def calculate(self, variable, period, map_to=None): + series = super().calculate(variable, period, map_to=map_to) + return float32_weights(series, period, FLOAT32_UPRATING) + + +__all__ = [name for name in globals() if not name.startswith("__")] diff --git a/test_support/microcosm_build/us_post_export_probe.py b/test_support/microcosm_build/us_post_export_probe.py index a04276409e..44102e6c40 100644 --- a/test_support/microcosm_build/us_post_export_probe.py +++ b/test_support/microcosm_build/us_post_export_probe.py @@ -124,13 +124,20 @@ def fixture_export_probe( batch_size: int | None = None, fail_on: str | None = None, census: bool = False, + scorer_options=None, **options, ): """An ``ExportProbe`` scoring with the float32 fake engine (not run); returns (probe, log). ``fail_on`` names a variable the fake engine - refuses to compute.""" + refuses to compute. ``scorer_options`` replaces the fake engine the + serial scorer is given (the log then records nothing).""" log = _EngineLog() log.fail_on = fail_on + if scorer_options is None: + scorer_options = { + "microsimulation_cls": float32_engine(log), + "dataset_from_frame": lambda batch_frame: batch_frame, + } probe = probe_tool.ExportProbe( export_path, out_dir, @@ -141,10 +148,7 @@ def fixture_export_probe( "sample_us_export_households", "sample_us_export_households.py" ), batch_size=batch_size, - scorer_options={ - "microsimulation_cls": float32_engine(log), - "dataset_from_frame": lambda batch_frame: batch_frame, - }, + scorer_options=scorer_options, load_frame=load_table_h5, measure_entity=_native_entity, chunk_rows=7, From bd0dbfa394b23df103dcf3fa9a2d5039bb3e67ce Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:56:47 +0400 Subject: [PATCH 02/26] Score post-export requests in the shared worker pool MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tracker task 1.4 · 7. _PooledPostExportScorer scores the requests the plan's engine-free dry run recorded in the shared worker pool and serves each consumer, run again in the certifying process, from the results: - the pool runs the merged baseline pass split into one range of batches per worker, then one unit per reformed simulation holding every recorded pass of it over every batch, so a worker builds a reform's rules once, as the serial scorer does; after a failed merged pass it also runs each consumer's own baseline pass first, and a changed batch file stops it instead; - a worker (microcosm.build.us_runtime.post_export_pool) reads each batch from the scorer's batch file and scores it with the serial scorer's own per-batch code (_score_post_export_batches), with the same population-aggregate, baseline-branch and behavioral-response refusals; failures come back as data and are raised where the serial scorer raises, with the worker's exception's class name and text; - each consumer's baseline is served its recorded plan and each reformed simulation its recorded passes in order, and any other request is refused; parts are joined in batch order, so outputs are byte-identical to the serial scorer's; - workers get this process's policyengine-us lock-check record, and the manifests' post_export_scoring block records how scoring ran under execution (run metadata). POST_EXPORT_SCORING_METHOD is raised once, to household_batched_written_h5_v2 (decision 1.1 · 1). The dry run now records each reform pass's keys, and the plan holds every consumer's requests. The held-out reports re-raise WorkerPoolError. Certification takes the pool settings as a parameter; certify_main still passes none (serial) until 1.4 · 6 decides the defaults. The serial merged pass's handling of a changed batch file is left to tracker task 1.4 · 4a. The export probe records every engine stage's plan before it opens the scorer and registers it (one shared baseline pass, as certification), can score in the pool, writes one passes.jsonl line per worker pass with its time and memory, records worker CPU per stage, and its household row map reads one batch file at a time. Co-Authored-By: Claude Opus 5.5 --- .../us-pooled-post-export-scoring.changed.md | 1 + docs/us-release-build-rule.md | 64 +- .../build/us_runtime/post_export_pool.py | 372 +++++ tools/build_us_fiscal_refresh_release.py | 1348 +++++++++++++++-- tools/probe_us_post_export.py | 200 ++- 5 files changed, 1820 insertions(+), 165 deletions(-) create mode 100644 changelog.d/us-pooled-post-export-scoring.changed.md create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py diff --git a/changelog.d/us-pooled-post-export-scoring.changed.md b/changelog.d/us-pooled-post-export-scoring.changed.md new file mode 100644 index 0000000000..12660d8fa6 --- /dev/null +++ b/changelog.d/us-pooled-post-export-scoring.changed.md @@ -0,0 +1 @@ +US post-export scoring can run in the shared worker pool (`_PooledPostExportScorer`): the merged baseline pass is split into one range of household batches per worker, each reformed simulation's recorded passes are one unit, and each post-export stage then runs in the certifying process over the results, refusing any request its engine-free dry run did not record. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's merged baseline pass instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan (one shared baseline pass, as certification runs), can score in the pool and writes each worker pass's time and memory to `passes.jsonl`; its household row map reads one batch file at a time. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index b63d1297ef..ce4816d844 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -489,18 +489,62 @@ one Microsimulation over the whole file. - `_record_post_export_request_descriptors` runs the same dry run and returns every request, baseline and reform, as a picklable `PostExportRequest` (`microcosm.build.us_runtime.post_export_requests`), which a process started - with `spawn` can unpickle; the release itself still takes only the baseline - plans and reform-pass counts. A `prefetch` of several keys of one reformed - simulation is one pass, and its keys follow in ascending period order, as - the scorer computes them. A reform request holds + with `spawn` can unpickle, and the reform passes the scorer runs for them. + A `prefetch` of several keys of one reformed simulation is one pass, and its + keys follow in ascending period order, as the scorer computes them. A reform request holds the description its stage builds the reform from: the smoke probe, the reform-validation spec, or a cumulative OBBBA state's parameter changes. The dry run builds no reform, and refuses a reform it cannot describe or pickle. It also refuses a key asked of a reformed simulation after its stage opened the next one: the scorer finishes a reformed simulation when the next opens and refuses it further keys, so the plan fails before the export instead. - Nothing records the descriptors; the guard sweep below rebuilds each reform - from its descriptor in the worker that scores it. + Nothing records the descriptors in a file; pooled scoring (next item) and + the guard sweep below rebuild each reform from its descriptor in the worker + that scores it. +- With pooled scoring (`_PooledPostExportScorer`) the scoring runs in the + shared worker pool (`microcosm.build.worker_pool`) and the stages run + afterwards in the certifying process, over the results: + - The pool runs twice. First the shared baseline pass, split into one range + of batches per worker. Then one unit per reformed simulation, holding all + of that simulation's recorded passes over every batch, in the order the + stages run: a worker builds the reform's rules once per unit, as the + serial scorer builds them once per reformed simulation. If the shared pass + fails, the second run also holds each stage's own baseline pass before + that stage's reform units. + - A worker reads each batch from the scorer's batch file, refusing one that + changed, and scores it with the serial scorer's own code + (`_score_post_export_batches`): one engine per batch, keys in ascending + period order, the population-aggregate refusal in a pass over more than + one batch, the baseline-branch refusal and the behavioral-response check + of a reform pass. + - A failure in a worker comes back with the unit's results. The certifying + process raises it when the stage asks for that pass, where the serial + scorer would have raised, as an error with the worker's exception's class + name and message, so a held-out report that records the error records the + same text. A changed batch file raises `PostExportBatchFileError`, and a + pool that cannot score (a unit that failed on every attempt, a worker that + could not start) raises `WorkerPoolError`; both stop certification, the + held-out reports included. + - Each stage then runs as in the serial path and builds its own reforms (the + smoke records each list edit's resolved lists from its own). Its baseline + is served its recorded plan, and each reformed simulation its recorded + passes in order. A stage that asks for anything else is refused, so a + stage whose requests depended on the values it got back cannot be served + values scored for a different request. Each key's per-batch values are + joined in batch order, so every output, both manifests' consumer records + and the smoke's scoring record are byte-identical to the serial scorer's. + - Workers inherit the certifying process's environment, thread variables + included, unless the pool settings set others, and each is given the + process's policyengine-us lock-check record + (`MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD`), so its import of the release + tool skips the lock-file check. A worker spawned from certification runs + certification's script again as `__mp_main__`, which imports the release + tool; that is the import the worker needs, so it runs once per worker + start. + - The manifests' `post_export_scoring` block records how scoring ran under + `execution`: `{"mode": "serial"}`, or the pool's settings, unit counts and + report (worker starts, failed attempts, peak worker memory). That record is + run metadata, outside every output comparison (decision 1.1 · 1). - Each batch engine keeps policyengine-us's projection of the release year to its last CPI-U year (2035), because the plans request keys in later years (reform validation reaches past 2025). The build's own simulations hold @@ -580,10 +624,10 @@ counts and the scored H5 digest. Run this fixture sweep before R4's full-export timing steps, and repeat it after a probe, spec or engine-lock change before starting a release. R4's existing full-export rehearsal times the smoke and validation -baseline plans plus three selected reform passes (`tools/probe_us_post_export.py` -still scores each stage's baseline plan in a pass of its own, which the release -no longer does); it does not cover every -reform and does not replace this sweep. +baseline plans plus three selected reform passes; it does not cover every +reform and does not replace this sweep. `tools/probe_us_post_export.py` +registers every stage's baseline plan, as certification does, so its baseline +is one shared pass. `calibration_diagnostics.json` records the plan under `build.post_export_scoring` (method, batch size, batch count, each stage's baseline keys and periods), and diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py new file mode 100644 index 0000000000..4aab8dda80 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py @@ -0,0 +1,372 @@ +"""The units, results and worker entry points of pooled US post-export scoring. + +The release tool (``tools/build_us_fiscal_refresh_release.py``) scores the +written release H5 in household batches. With pooled scoring it sends the +scoring to worker processes of the shared pool +(:mod:`microcosm.build.worker_pool`) and runs each post-export consumer again +in its own process over the results: + +- the engine-free dry run records every request each consumer makes + (:mod:`microcosm.build.us_runtime.post_export_requests`), and which of a + reformed simulation's requests the serial scorer scores together in one + pass; +- each :class:`PostExportUnit` is a run of one or more such passes over a range + of the H5's household batches: the merged baseline plan over a range of + batches, or every pass of one reformed simulation over all of them; +- a worker reads each batch from the file the release tool's scorer wrote it + to, builds one engine per batch, scores the pass's keys on it in ascending + period order, applies the same refusals as the serial scorer, and returns + each key's values and weights per batch (:class:`PostExportPassValues`); +- the release tool joins each key's parts in batch order, as the serial scorer + does, and serves them to the consumer it runs again. + +A failure inside a pass is returned as data (:class:`PostExportUnitFailure`), +not raised, so the pool keeps running and the release tool raises it where the +serial scorer would have: when the consumer asks for that pass. +:exc:`MemoryError` is raised, so the pool runs the unit again in a fresh +worker. + +The types live here, in an importable package, so a spawned worker can +unpickle them however the release tool was loaded. The worker entry points +(:func:`start_post_export_worker`, :func:`score_post_export_unit`) live here +for the same reason; the worker finds the release tool, or loads it from its +file, when it starts (:func:`release_tool`). +""" + +from __future__ import annotations + +import builtins +import importlib.util +import sys +import traceback +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from microcosm.build.us_runtime.post_export_requests import ( + PostExportReform, + check_post_export_reform, +) + +__all__ = [ + "PostExportPass", + "PostExportPassTiming", + "PostExportPassValues", + "PostExportUnit", + "PostExportUnitFailure", + "PostExportUnitResult", + "release_tool", + "score_post_export_unit", + "start_post_export_worker", +] + +#: One scored request: (variable, period, map_to), the release tool's +#: ``PostExportKey``. +type PostExportKey = tuple[str, int, str | None] + +#: Where a pass failed: building the reform's rules, the check that the reform +#: keeps the behavioral-response parameters at baseline, or scoring a batch. +FAILURE_STAGES = ("rules", "responses", "scoring") + + +def _check_key(key: object) -> None: + if ( + not isinstance(key, tuple) + or len(key) != 3 + or not isinstance(key[0], str) + or not key[0] + or isinstance(key[1], bool) + or not isinstance(key[1], int) + or not (key[2] is None or (isinstance(key[2], str) and key[2])) + ): + raise ValueError( + "A post-export key is (variable, period, map_to): a variable name, " + f"an integer period and an entity name or None; got {key!r}." + ) + + +@dataclass(frozen=True) +class PostExportPass: + """One batch-outer pass: each batch engine scores ``keys`` in this order. + + Attributes: + label: The pass's name in errors and progress, as the serial scorer + names it (``"merged baseline plan"``, ``" baseline + plan"``, ``" reform @, ..."``). + keys: Unique keys in ascending period order. + """ + + label: str + keys: tuple[PostExportKey, ...] + + def __post_init__(self) -> None: + if not isinstance(self.label, str) or not self.label: + raise ValueError("A post-export pass needs a label.") + keys = tuple(self.keys) + if not keys: + raise ValueError(f"Post-export pass {self.label!r} has no keys.") + for key in keys: + _check_key(key) + if len(set(keys)) != len(keys): + raise ValueError(f"Post-export pass {self.label!r} repeats a key.") + periods = [key[1] for key in keys] + if periods != sorted(periods): + raise ValueError( + f"Post-export pass {self.label!r} must hold its keys in " + "ascending period order; each engine refuses an earlier period " + "after a later one." + ) + object.__setattr__(self, "keys", keys) + + +@dataclass(frozen=True) +class PostExportUnit: + """Passes a worker runs over the household batches ``[batch_start, batch_stop)``. + + Attributes: + consumer: The consumer whose passes these are, or ``None`` for the + merged baseline plan of every consumer. + reformed_simulation: For a reform unit, which of the consumer's + ``simulate(reform)`` calls made the simulation, numbered from 0; + ``None`` for a baseline unit. + reform: ``None`` for a baseline unit; otherwise the description the + worker rebuilds the reform from + (:func:`~microcosm.build.us_runtime.post_export_requests.build_post_export_reform`). + The worker builds the reform's rules once and scores every pass + with them, as the serial scorer does for one reformed simulation. + passes: The passes, in the order the serial scorer runs them. + batch_start: The first batch, numbered from 0. + batch_stop: One past the last batch. + n_batches: The H5's batch count. A pass over more than one batch of + the H5 refuses the formulas that aggregate over their whole + simulation, whatever part of the H5 this unit scores. + """ + + consumer: str | None + reformed_simulation: int | None + reform: PostExportReform | None + passes: tuple[PostExportPass, ...] + batch_start: int + batch_stop: int + n_batches: int + + # Not hashable: most reform descriptions hold dictionaries. + __hash__ = None # type: ignore[assignment] + + def __post_init__(self) -> None: + passes = tuple(self.passes) + if not passes or not all(isinstance(item, PostExportPass) for item in passes): + raise ValueError("A post-export unit needs one or more PostExportPass.") + object.__setattr__(self, "passes", passes) + for name in ("batch_start", "batch_stop", "n_batches"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError(f"PostExportUnit.{name} must be an integer.") + if not 0 <= self.batch_start < self.batch_stop <= self.n_batches: + raise ValueError( + "A post-export unit's batches must be a non-empty range within " + f"the H5's {self.n_batches}; got [{self.batch_start}, " + f"{self.batch_stop})." + ) + if self.consumer is not None and ( + not isinstance(self.consumer, str) or not self.consumer + ): + raise ValueError("PostExportUnit.consumer must be a name or None.") + if self.reform is None: + if self.reformed_simulation is not None: + raise ValueError("A baseline unit names no reformed simulation.") + return + check_post_export_reform(self.reform) + if self.consumer is None: + raise ValueError("A reform unit names the consumer that asked for it.") + simulation = self.reformed_simulation + if isinstance(simulation, bool) or not isinstance(simulation, int): + raise TypeError("A reform unit names its reformed simulation's number.") + if simulation < 0: + raise ValueError("A reformed simulation's number is 0 or more.") + + def describe(self) -> str: + """The unit's name in pool errors.""" + if self.batch_stop - self.batch_start == self.n_batches: + batches = f"all {self.n_batches} batch(es)" + else: + batches = ( + f"batches {self.batch_start + 1}-{self.batch_stop} of {self.n_batches}" + ) + if self.reform is None: + return f"post-export {self.passes[0].label}, {batches}" + return ( + f"post-export {self.consumer} reformed simulation " + f"{self.reformed_simulation} ({len(self.passes)} pass(es), first " + f"{self.passes[0].label!r}), {batches}" + ) + + +@dataclass(frozen=True) +class PostExportPassValues: + """One pass's values: for each key of the pass, in order, one + ``(values, weights)`` pair per batch of the unit, in batch order.""" + + parts: tuple[tuple[tuple[Any, Any], ...], ...] + + +@dataclass(frozen=True) +class PostExportUnitFailure: + """Why a pass of a unit has no values. + + Attributes: + stage: Where it failed (:data:`FAILURE_STAGES`). + error_name: The exception's class name. + error_module: The module of the exception's class. + builtin_base: The first built-in exception class among the class's + bases (``KeyError``, ``RuntimeError``, ``Exception``, ...). + message: ``str()`` of the exception. + traceback: The exception's traceback, formatted in the worker. + batch_file_error: Whether it is the release tool's + ``PostExportBatchFileError`` (a batch file that changed or cannot + be read), which the release tool raises as its own. + """ + + stage: str + error_name: str + error_module: str + builtin_base: str + message: str + traceback: str + batch_file_error: bool = False + + @classmethod + def from_exception( + cls, stage: str, error: BaseException, *, batch_file_error: bool = False + ) -> PostExportUnitFailure: + if stage not in FAILURE_STAGES: + raise ValueError(f"Unknown post-export failure stage {stage!r}.") + base = next( + kind + for kind in type(error).__mro__ + if kind.__module__ == "builtins" and issubclass(kind, BaseException) + ) + try: + message = str(error) + except Exception: # an exception whose str raises + message = f"" + return cls( + stage=stage, + error_name=type(error).__name__, + error_module=type(error).__module__, + builtin_base=base.__name__, + message=message, + traceback="".join(traceback.format_exception(error)), + batch_file_error=batch_file_error, + ) + + def exception(self) -> BaseException: + """An exception with the worker's exception's class name and ``str()``. + + Its class is made here, named as the worker's and derived from the + built-in exception class the worker's derived from, so ``except + KeyError`` still catches a ``KeyError`` and a report that records + ``f"{type(error).__name__}: {error}"`` records what the serial scorer + would have. The worker's traceback is the exception's + ``worker_traceback``. + """ + base = getattr(builtins, self.builtin_base, None) + if not (isinstance(base, type) and issubclass(base, Exception)): + base = Exception + message = self.message + + def describe(error) -> str: + return message + + kind = type( + self.error_name, + (base,), + {"__module__": self.error_module, "__str__": describe}, + ) + try: + error = kind(message) + except Exception: + # A built-in base that does not take one message argument. + error = type(self.error_name, (Exception,), {"__str__": describe})(message) + error.worker_traceback = self.traceback + return error + + +@dataclass(frozen=True) +class PostExportPassTiming: + """What one pass cost its worker. + + Attributes: + wall_seconds: Wall time of the pass. + cpu_seconds: The worker's CPU time during the pass. + footprint_bytes: The worker's memory footprint when the pass ended + (:func:`microcosm.build.worker_pool.process_memory_bytes`), or + ``None`` where it cannot be read. + peak_rss_bytes: The worker's peak resident memory since it started. + """ + + wall_seconds: float + cpu_seconds: float + footprint_bytes: int | None + peak_rss_bytes: int + + +@dataclass(frozen=True) +class PostExportUnitResult: + """A unit's outcome: per pass, its values or its failure, and its timing.""" + + outcomes: tuple[PostExportPassValues | PostExportUnitFailure, ...] + timings: tuple[PostExportPassTiming, ...] + worker_pid: int + + +# --------------------------------------------------------------------------- +# The worker's entry points +# --------------------------------------------------------------------------- + + +def release_tool(module_name: str, path: str | Path): + """The release tool in this process: loaded already, or from ``path``. + + A worker spawned from a release run has run the parent's main script again + as ``__mp_main__``. That script is either the release tool itself or + certification's script, which imports the tool, so the tool is usually + loaded already; it is loaded from ``path`` only when it is not (the + parent loaded it by path, as the tests and the export probe do). Either + way the tool's module body runs once per worker. + """ + path = Path(path).resolve() + for candidate in ( + sys.modules.get(module_name), + sys.modules.get("__mp_main__"), + sys.modules.get("__main__"), + ): + file = getattr(candidate, "__file__", None) + if file is not None and Path(file).resolve() == path: + return candidate + name = module_name + if name in {"__main__", "__mp_main__"} or name in sys.modules: + name = f"_post_export_release_tool_{abs(hash(str(path)))}" + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + raise ImportError(f"cannot load the release tool from {path}") + module = importlib.util.module_from_spec(spec) + # Registered before it runs, as ``dataclasses`` resolves annotations + # through ``sys.modules``. + sys.modules[name] = module + try: + spec.loader.exec_module(module) + except BaseException: + sys.modules.pop(name, None) + raise + return module + + +def start_post_export_worker(module_name: str, path: str, *arguments: Any): + """The pool's initializer: the release tool's worker over its batch files.""" + return release_tool(module_name, path)._PostExportWorker(*arguments) + + +def score_post_export_unit(worker, unit: PostExportUnit) -> PostExportUnitResult: + """The pool's unit function: score ``unit`` (``worker.score``).""" + return worker.score(unit) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 7d544a5041..b0af04ad6d 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -366,9 +366,20 @@ population_structure_holdout_unavailable, write_population_structure_holdout, ) +from microcosm.build.us_runtime.post_export_pool import ( + PostExportPass, + PostExportPassTiming, + PostExportPassValues, + PostExportUnit, + PostExportUnitFailure, + PostExportUnitResult, + score_post_export_unit, + start_post_export_worker, +) from microcosm.build.us_runtime.post_export_requests import ( RECORDS_REQUESTS_ONLY, PostExportRequest, + build_post_export_reform, check_post_export_reform, ) from microcosm.build.us_runtime.puf_capital_gains_tail import ( @@ -448,6 +459,13 @@ load_selection_source_from_manifest, select_frozen_support, ) +from microcosm.build.worker_pool import ( + WorkerPool, + WorkerPoolError, + WorkerPoolReport, + WorkerPoolSettings, + process_memory_bytes, +) from microcosm.calibrate import ( CalibrationResult, L0RefitResult, @@ -5112,11 +5130,14 @@ def _select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame # so a measure that reaches such a formula fails the stage instead of scoring # a batch-local aggregate. -#: Recorded in ``post_export_scoring`` blocks; bump with any change to how the -#: written H5 is scored that can change a scored value. Regrouping keys into -#: fewer passes while every value stays byte-identical (the merged baseline -#: pass and the shared pre-OBBBA pass, microcosm#1595) keeps it. -POST_EXPORT_SCORING_METHOD = "household_batched_written_h5" +#: Recorded in ``post_export_scoring`` blocks. Version 2 covers the merged +#: baseline pass and the shared pre-OBBBA pass (microcosm#1595) and scoring in +#: the shared worker pool with each consumer run again over the results +#: (``_PooledPostExportScorer``), which leave every scored value byte-identical +#: to version 1's; decision 1.1 · 1 raises the label once for all of them. +#: Raise it again with any change to how the written H5 is scored that can +#: change a scored value. +POST_EXPORT_SCORING_METHOD = "household_batched_written_h5_v2" #: One scored request: (variable, period, map_to). PostExportKey = tuple[str, int, str | None] @@ -5289,10 +5310,11 @@ class _RecordingPostExportSimulation: also shared, so a reformed simulation's recorder refuses every key once a later one is opened, as the scorer refuses a finished ``_BatchedPostExportReform``. ``reform_passes``, also shared, gets one - entry per batched reform pass: when the consumer runs for real, each - ``calculate`` or ``prefetch`` that asks a reformed simulation for a key it - was not asked before is one pass of ``_BatchedPostExportReform``, which - computes the new keys in ascending period order. + ``(simulation, keys)`` entry per batched reform pass: when the consumer + runs for real, each ``calculate`` or ``prefetch`` that asks a reformed + simulation for a key it was not asked before is one pass of + ``_BatchedPostExportReform``, which computes the new keys in ascending + period order. """ def __init__( @@ -5300,7 +5322,7 @@ def __init__( asked: dict[tuple[int | None, PostExportKey], None], simulation: int | None, reforms: Sequence[object], - reform_passes: list[int], + reform_passes: list[tuple[int, tuple[PostExportKey, ...]]], ) -> None: self._asked = asked self._simulation = simulation @@ -5332,7 +5354,7 @@ def _record(self, keys: Sequence[PostExportKey]) -> None: ) self._asked.update(dict.fromkeys((self._simulation, key) for key in new_keys)) if new_keys and self._simulation is not None: - self._reform_passes.append(self._simulation) + self._reform_passes.append((self._simulation, new_keys)) def _dry_run_post_export_requests( @@ -5369,14 +5391,18 @@ def _dry_run_post_export_requests( def _dry_run_post_export( consumer: Callable[[Callable[[Any], Any]], object], -) -> tuple[tuple[tuple[int | None, object, PostExportKey], ...], int]: - """``_dry_run_post_export_requests``'s requests and the number of batched - reform passes the scorer runs for them: one per ``calculate`` or - ``prefetch`` that asks a reformed simulation for a key not asked of it - before, so a ``prefetch`` of several keys is one pass.""" +) -> tuple[ + tuple[tuple[int | None, object, PostExportKey], ...], + tuple[tuple[int, tuple[PostExportKey, ...]], ...], +]: + """``_dry_run_post_export_requests``'s requests and the batched reform + passes the scorer runs for them, as ``(simulation, keys)`` in run order: + one per ``calculate`` or ``prefetch`` that asks a reformed simulation for + a key not asked of it before, so a ``prefetch`` of several keys is one + pass, whose keys are in ascending period order.""" asked: dict[tuple[int | None, PostExportKey], None] = {} reforms: list[object] = [] - reform_passes: list[int] = [] + reform_passes: list[tuple[int, tuple[PostExportKey, ...]]] = [] def simulate(reform): if reform is None: @@ -5400,7 +5426,7 @@ def simulate(reform): if simulation is not None ), ) - return requests, len(reform_passes) + return requests, tuple(reform_passes) def _record_post_export_request_descriptors( @@ -5448,7 +5474,7 @@ def _record_post_export_requests( """ requests, reform_passes = _dry_run_post_export(consumer) baseline = tuple(key for simulation, _, key in requests if simulation is None) - return baseline, reform_passes + return baseline, len(reform_passes) def _record_post_export_baseline_plan( @@ -5458,6 +5484,85 @@ def _record_post_export_baseline_plan( return _record_post_export_requests(consumer)[0] +class _PostExportConsumerRequests: + """Every request one consumer's engine-free dry run made, and its passes. + + ``descriptors`` are the consumer's requests as picklable + ``PostExportRequest`` descriptors, in the order the serial scorer runs + them; ``baseline_plan`` their baseline keys; ``reform_passes`` the + batched reform passes the serial scorer runs for the rest, as + ``(reformed simulation, keys)`` in run order. Pooled scoring sends these + passes to workers and serves the consumer, when it runs again, exactly + these requests (``_PooledPostExportScorer``). (A plain class, for the + reason :class:`_PostExportScoringPlan` gives.) + """ + + def __init__( + self, + name: str, + descriptors: Sequence[PostExportRequest], + reform_passes: Sequence[tuple[int, tuple[PostExportKey, ...]]], + ) -> None: + self.name = str(name) + self.descriptors = tuple(descriptors) + self.baseline_plan = tuple( + request.key for request in self.descriptors if request.reform is None + ) + self.reform_passes = tuple( + (int(simulation), tuple(keys)) for simulation, keys in reform_passes + ) + self.reforms: dict[int, object] = {} + asked: dict[int, list[PostExportKey]] = {} + for request in self.descriptors: + if request.reform is not None: + self.reforms.setdefault(request.reformed_simulation, request.reform) + asked.setdefault(request.reformed_simulation, []).append(request.key) + passed: dict[int, list[PostExportKey]] = {} + for simulation, keys in self.reform_passes: + passed.setdefault(simulation, []).extend(keys) + if {simulation: tuple(keys) for simulation, keys in passed.items()} != { + simulation: tuple(keys) for simulation, keys in asked.items() + }: + raise ValueError( + f"{self.name}: the dry run's reform passes do not hold exactly " + "its reform requests, in their order." + ) + self.simulations = tuple(dict.fromkeys(sim for sim, _ in self.reform_passes)) + if list(self.simulations) != sorted(self.simulations): + raise ValueError( + f"{self.name}: a reformed simulation's passes must all come " + "before the next simulation's." + ) + + def passes_of(self, simulation: int) -> tuple[tuple[PostExportKey, ...], ...]: + """The keys of each reform pass of one reformed simulation, in order.""" + return tuple( + keys for number, keys in self.reform_passes if number == simulation + ) + + +def _record_post_export_consumer_requests( + name: str, consumer: Callable[[Callable[[Any], Any]], object] +) -> _PostExportConsumerRequests: + """Every request and reform pass of ``consumer``, from one engine-free dry run.""" + requests, reform_passes = _dry_run_post_export(consumer) + descriptors = tuple( + PostExportRequest( + consumer=name, + position=position, + variable=variable, + period=period, + map_to=map_to, + reform=reform, + reformed_simulation=simulation, + ) + for position, (simulation, reform, (variable, period, map_to)) in enumerate( + requests + ) + ) + return _PostExportConsumerRequests(name, descriptors, reform_passes) + + class _AscendingPeriodEngine: """One batch engine that refuses a period earlier than one it computed.""" @@ -5622,14 +5727,19 @@ def __init__( maximum_batch_size: int | None, baseline_plans: Mapping[str, tuple[PostExportKey, ...]], reform_passes: Mapping[str, int] | None = None, + consumer_requests: Mapping[str, _PostExportConsumerRequests] | None = None, error: str | None = None, ) -> None: + """``consumer_requests`` holds every request of each consumer's dry + run, which pooled scoring sends to workers; the record of the plan + leaves it out, as it does the reform pass counts.""" self.n_households = int(n_households) self.maximum_batch_size = maximum_batch_size self.baseline_plans = { consumer: tuple(plan) for consumer, plan in baseline_plans.items() } self.reform_passes = dict(reform_passes or {}) + self.consumer_requests = dict(consumer_requests or {}) self.error = error @property @@ -5692,14 +5802,19 @@ def _post_export_scoring_plan( consumers: Mapping[str, Callable[[Callable[[Any], Any]], object]], ) -> _PostExportScoringPlan: requests = { - name: _record_post_export_requests(consumer) + name: _record_post_export_consumer_requests(name, consumer) for name, consumer in consumers.items() } return _PostExportScoringPlan( n_households=int(n_households), maximum_batch_size=maximum_microsim_batch_size, - baseline_plans={name: plan for name, (plan, _) in requests.items()}, - reform_passes={name: passes for name, (_, passes) in requests.items()}, + baseline_plans={ + name: recorded.baseline_plan for name, recorded in requests.items() + }, + reform_passes={ + name: len(recorded.reform_passes) for name, recorded in requests.items() + }, + consumer_requests=requests, ) @@ -5885,6 +6000,23 @@ def __init__(self, directory: Path, batch_frames: Sequence[Frame]) -> None: del payload self._files = tuple(files) + @property + def files(self) -> tuple[tuple[str, str], ...]: + """Each batch's file and the SHA-256 written for it, in batch order.""" + return tuple((str(path), sha256) for path, sha256 in self._files) + + @classmethod + def written(cls, files: Sequence[tuple[str, str]]) -> _PostExportBatchFiles: + """Batches another process wrote, from its :attr:`files`. + + A pool worker reads its batches this way: each file is still refused + unless its bytes hash to the digest the scorer recorded. + """ + batches = cls.__new__(cls) + batches._files = tuple((Path(path), str(sha256)) for path, sha256 in files) + batches.directory = batches._files[0][0].parent if batches._files else Path(".") + return batches + def __len__(self) -> int: return len(self._files) @@ -5992,16 +6124,7 @@ def __init__( microsimulation_cls = Microsimulation self._microsimulation_cls = microsimulation_cls if dataset_from_frame is None: - - def dataset_from_frame(batch_frame: Frame): - # Consumer plans read years after PERIOD (reform validation - # reaches past 2025), so the scorer keeps the engine's - # projection: it does not ask for PERIOD alone. - return _dataset_from_frame( - batch_frame, - assert_no_formula_owned_columns=False, - ) - + dataset_from_frame = _post_export_dataset self._dataset_from_frame = dataset_from_frame # Each finished consumer's scoring record, for the manifests' block. # Records, not consumers: a finished consumer's arrays must be freed. @@ -6082,8 +6205,14 @@ def manifest_record(self) -> dict[str, object]: } for name, record in self.consumer_records.items() }, + "execution": self.execution_record(), } + def execution_record(self) -> dict[str, object]: + """How this scorer ran: run metadata, outside every output comparison + (decision 1.1 · 1). This scorer runs every pass in its own process.""" + return {"mode": "serial"} + def close(self) -> None: self._finish_open_reform() self._batch_frames = None @@ -6177,52 +6306,23 @@ def _baseline_for( return served, True def _construct(self, batch_frame: Frame, *, reform_system): - dataset = self._dataset_from_frame(batch_frame) - if reform_system is None: - return self._microsimulation_cls( - dataset=dataset, spm=dict(US_RELEASE_SPM_SELECTION) - ) - # The reform's system alone, not ``reform=`` as well. Given both, - # policyengine-us 2.2.1 clones the supplied system on every - # construction (``SPMSimulationMixin._prepare_spm_system`` -> - # ``clone_spm_system``: the whole parameter tree rebuilt and every - # variable deep-copied, so each batch starts on cold caches), core - # applies the reform again to the clone, and core adds a ``baseline`` - # branch whose holders copy every input array. Given the system alone - # it shares the system's policy (``share_spm_policy``). - # ``POST_EXPORT_BASELINE_BRANCH_READERS`` and - # ``POST_EXPORT_BEHAVIORAL_RESPONSE_PARAMETERS`` list formulas that - # read the baseline branch, and the scorer guards those uses. - return self._microsimulation_cls( - tax_benefit_system=reform_system, - dataset=dataset, - spm=dict(US_RELEASE_SPM_SELECTION), + return _construct_post_export_engine( + self._microsimulation_cls, + self._dataset_from_frame(batch_frame), + reform_system=reform_system, ) def _assert_reform_keeps_baseline_responses( self, reform_system, key: PostExportKey, *, label: str ) -> None: - """Refuse a reform that moves a behavioral-response parameter. - - A batch reform engine has no ``baseline`` branch, so policyengine-us - scores its labor-supply and capital-gains responses as 0. A whole-file - reform engine has one and scores them from these parameters, as 0 at - the engine's zero default elasticities. The guard requires these - parameters to stay at baseline before building a batch reform engine. - """ - moved = _moved_behavioral_response_parameters( + """Refuse a reform that moves a behavioral-response parameter + (``_refuse_moved_behavioral_responses``).""" + _refuse_moved_behavioral_responses( reform_system, self._microsimulation_cls.default_tax_benefit_system_instance, - key[1], + key, + label=label, ) - if moved: - raise RuntimeError( - f"Post-export scoring ({label}) refuses a reform that sets " - f"behavioral-response parameters off baseline at {key[1]}: " - f"{', '.join(moved)}. Batch reform engines carry no baseline " - "branch, so policyengine-us would score these responses as zero " - "(microcosm#956)." - ) def _score( self, @@ -6239,9 +6339,6 @@ def _score( """ batches = self._batches() batched = len(batches) > 1 - watched = _post_export_watched_variables( - batched=batched, reform=reform_system is not None - ) if batched: print( f"Scoring post-export {label} ({len(keys)} key(s)) in " @@ -6249,65 +6346,175 @@ def _score( "households.", flush=True, ) - parts: dict[PostExportKey, list[tuple[np.ndarray, np.ndarray]]] = { - key: [] for key in keys - } sweep = _WorkCounter( stage_id="post_export_scoring", unit="scoring_batch", total=len(batches), outer=outer, ) - for batch in range(1, len(batches) + 1): - # Read by position: ``enumerate`` keeps its last item, so the - # previous batch's frame would stay alive while the next is read. - batch_frame = batches[batch - 1] - with _automatic_gc_suspended(): - simulation = self._construct(batch_frame, reform_system=reform_system) - # The engine holds its own copy of the batch; the frame read - # from the batch's file is freed before the next one is read. - del batch_frame - try: - known_at_load = _engine_known_periods(simulation, watched) - engine = _AscendingPeriodEngine(simulation, label=label) - for key in keys: - parts[key].append( - _post_export_values_and_weights(engine.calculate(key), key) - ) - # Before the release below drops the engine's holders. - _assert_post_export_scoring_is_batch_invariant( - simulation, - watched, - known_at_load, - label=label, - batched=batched, - reform=reform_system is not None, - ) - finally: - # microcosm#456: free this batch engine's array mass by - # refcount before the next batch builds its own, also - # when a key raises. - release_engine_simulation(simulation) - del simulation, engine - _collect_batch_garbage() - sweep.advance(pass_name=label, batch=batch, batches=len(batches)) - _collect_family_garbage() + parts = _score_post_export_batches( + batches, + range(len(batches)), + keys, + label=label, + construct=self._construct, + reform_system=reform_system, + batched=batched, + advance=lambda position: sweep.advance( + pass_name=label, batch=position + 1, batches=len(batches) + ), + ) return { key: _concatenate_post_export_parts(key_parts) for key, key_parts in parts.items() } +def _construct_post_export_engine(microsimulation_cls, dataset, *, reform_system): + """One batch engine, for the serial scorer and pool workers alike. + + A reform engine gets the reform's system alone, not ``reform=`` as well. + Given both, policyengine-us 2.2.1 clones the supplied system on every + construction (``SPMSimulationMixin._prepare_spm_system`` -> + ``clone_spm_system``: the whole parameter tree rebuilt and every variable + deep-copied, so each batch starts on cold caches), core applies the reform + again to the clone, and core adds a ``baseline`` branch whose holders copy + every input array. Given the system alone it shares the system's policy + (``share_spm_policy``). ``POST_EXPORT_BASELINE_BRANCH_READERS`` and + ``POST_EXPORT_BEHAVIORAL_RESPONSE_PARAMETERS`` list formulas that read the + baseline branch, and the scorer guards those uses. + """ + if reform_system is None: + return microsimulation_cls(dataset=dataset, spm=dict(US_RELEASE_SPM_SELECTION)) + return microsimulation_cls( + tax_benefit_system=reform_system, + dataset=dataset, + spm=dict(US_RELEASE_SPM_SELECTION), + ) + + +def _post_export_reform_pass_label(consumer: str, keys: Sequence[PostExportKey]) -> str: + """A reform pass's name in errors and progress, serial or pooled.""" + return f"{consumer} reform " + ", ".join( + f"{variable}@{period}" for variable, period, _ in keys + ) + + +def _score_post_export_batches( + batches: Sequence[Frame], + positions: Iterable[int], + keys: Sequence[PostExportKey], + *, + label: str, + construct: Callable[..., Any], + reform_system, + batched: bool, + advance: Callable[[int], None] | None = None, +) -> dict[PostExportKey, list[tuple[np.ndarray, np.ndarray]]]: + """Score ``keys`` on one engine per batch at ``positions``, in that order. + + The serial scorer's pass (``_HouseholdBatchedPostExportScorer._score``) + and a pool worker's (``_PostExportWorker``) both run this, so a key's + values for a batch come from the same engine construction and the same + calls in either. Each engine computes the keys in their order (ascending + periods), refuses the formulas batching would score wrongly, and is + released before the next batch is read. ``batched`` says whether the H5 + has more than one batch, whichever of its batches are scored here. + Returns each key's ``(values, weights)`` per batch, in batch order; + ``advance(position)`` runs after each batch. + """ + watched = _post_export_watched_variables( + batched=batched, reform=reform_system is not None + ) + parts: dict[PostExportKey, list[tuple[np.ndarray, np.ndarray]]] = { + key: [] for key in keys + } + for position in positions: + # Read by position: ``enumerate`` keeps its last item, so the + # previous batch's frame would stay alive while the next is read. + batch_frame = batches[position] + with _automatic_gc_suspended(): + simulation = construct(batch_frame, reform_system=reform_system) + # The engine holds its own copy of the batch; the frame read from + # the batch's file is freed before the next one is read. + del batch_frame + try: + known_at_load = _engine_known_periods(simulation, watched) + engine = _AscendingPeriodEngine(simulation, label=label) + for key in keys: + parts[key].append( + _post_export_values_and_weights(engine.calculate(key), key) + ) + # Before the release below drops the engine's holders. + _assert_post_export_scoring_is_batch_invariant( + simulation, + watched, + known_at_load, + label=label, + batched=batched, + reform=reform_system is not None, + ) + finally: + # microcosm#456: free this batch engine's array mass by + # refcount before the next batch builds its own, also when a + # key raises. + release_engine_simulation(simulation) + del simulation, engine + _collect_batch_garbage() + if advance is not None: + advance(position) + _collect_family_garbage() + return parts + + +def _refuse_moved_behavioral_responses( + reform_system, baseline_system, key: PostExportKey, *, label: str +) -> None: + """Refuse a reform that moves a behavioral-response parameter. + + A batch reform engine has no ``baseline`` branch, so policyengine-us + scores its labor-supply and capital-gains responses as 0. A whole-file + reform engine has one and scores them from these parameters, as 0 at the + engine's zero default elasticities. The guard requires these parameters + to stay at baseline before building a batch reform engine. + """ + moved = _moved_behavioral_response_parameters( + reform_system, baseline_system, key[1] + ) + if moved: + raise RuntimeError( + f"Post-export scoring ({label}) refuses a reform that sets " + f"behavioral-response parameters off baseline at {key[1]}: " + f"{', '.join(moved)}. Batch reform engines carry no baseline " + "branch, so policyengine-us would score these responses as zero " + "(microcosm#956)." + ) + + +def _post_export_dataset(batch_frame: Frame): + """The dataset a batch engine scores (``_HouseholdBatchedPostExportScorer``). + + Consumer plans read years after PERIOD (reform validation reaches past + 2025), so the scorer keeps the engine's projection: it does not ask for + PERIOD alone. + """ + return _dataset_from_frame(batch_frame, assert_no_formula_owned_columns=False) + + def _open_post_export_scorer( plan: _PostExportScoringPlan, dataset_path: Path, *, batch_parent: Path | None = None, + pooling: _PostExportPooling | None = None, ) -> _HouseholdBatchedPostExportScorer | None: """Open the scorer the plan recorded before export, or None if no stage runs. - The scorer keeps its household batch files in a new directory of its own - inside ``batch_parent`` (the system's temporary directory without one). + With ``pooling`` the scorer scores the plan's recorded requests in the + shared worker pool (``_PooledPostExportScorer``); without it, every pass + runs in this process. The scorer keeps its household batch files in a new + directory of its own inside ``batch_parent`` (the system's temporary + directory without one). """ if plan.error is not None: raise RuntimeError( @@ -6315,6 +6522,23 @@ def _open_post_export_scorer( ) if not plan.baseline_plans: return None + if pooling is not None: + missing = sorted(set(plan.baseline_plans) - set(plan.consumer_requests)) + if missing: + raise RuntimeError( + "Pooled post-export scoring needs every consumer's recorded " + f"requests; the plan holds none for {', '.join(missing)}." + ) + return _PooledPostExportScorer( + dataset_path, + maximum_microsim_batch_size=plan.maximum_batch_size, + batch_parent=batch_parent, + expected_n_households=plan.n_households, + consumer_requests={ + name: plan.consumer_requests[name] for name in plan.baseline_plans + }, + pooling=pooling, + ) return _HouseholdBatchedPostExportScorer( dataset_path, maximum_microsim_batch_size=plan.maximum_batch_size, @@ -6406,9 +6630,7 @@ def _reform_values( self, reform_system, keys: tuple[PostExportKey, ...] ) -> dict[PostExportKey, _PostExportValues]: """One batched reform pass over ``keys`` (ascending period order).""" - label = f"{self.name} reform " + ", ".join( - f"{variable}@{period}" for variable, period, _ in keys - ) + label = _post_export_reform_pass_label(self.name, keys) checked_periods: set[int] = set() for key in keys: if key[1] not in checked_periods: @@ -6416,17 +6638,19 @@ def _reform_values( self._scorer._assert_reform_keeps_baseline_responses( reform_system, key, label=label ) - self.reform_passes += 1 - planned = self.planned_reform_passes - outer = ( - OuterProgress(self.reform_passes, planned, "reform_pass") - if planned is not None and self.reform_passes <= planned - else None - ) + outer = self._count_reform_pass() return self._scorer._score( keys, label=label, reform_system=reform_system, outer=outer ) + def _count_reform_pass(self) -> OuterProgress | None: + """Count one reform pass; return its place among the planned passes.""" + self.reform_passes += 1 + planned = self.planned_reform_passes + if planned is not None and self.reform_passes <= planned: + return OuterProgress(self.reform_passes, planned, "reform_pass") + return None + class _PlannedPostExportBaseline: """The baseline simulation a consumer sees: served from its scored plan.""" @@ -6526,6 +6750,866 @@ def finish(self) -> None: rule_modules.close() +# --------------------------------------------------------------------------- +# Pooled post-export scoring (tracker task 1.4 · 7) +# --------------------------------------------------------------------------- +# +# The serial scorer runs every pass in its own process, one after another. +# The pooled scorer (``_PooledPostExportScorer``) runs the same passes in the +# shared worker pool (``microcosm.build.worker_pool``) and serves each +# consumer from their results: +# +# * The plan's engine-free dry run recorded every request of every consumer +# and the reform passes the serial scorer runs for them +# (``_PostExportConsumerRequests``). +# * The pool runs twice. First the merged baseline plan, split into ranges of +# batches, one unit per range. Then one unit per reformed simulation, with +# every recorded pass of it over every batch, in the order the consumers +# run: a worker builds the reform's rules once for the unit, as the serial +# scorer builds them once per reformed simulation. If the merged baseline +# pass failed, the second run also holds each consumer's own baseline plan +# before its reform units, as the serial scorer then scores it. +# * A worker reads each batch from the scorer's batch file (refusing one +# whose bytes changed), builds one engine per batch and scores the pass's +# keys on it exactly as the serial scorer does +# (``_score_post_export_batches``): ascending periods, the +# population-aggregate refusal of a pass over a multi-batch H5, the +# baseline-branch refusal and the behavioral-response check of a reform +# pass. A failure is returned with the unit, not raised. +# * The consumers then run in this process, as in the serial path, and build +# their own reforms (the smoke check records each list edit's resolved +# lists from its own). Each baseline is served the consumer's recorded +# plan and refuses any other key. Each reformed simulation is served its +# recorded passes in order and refuses any other request, so a consumer +# whose requests depend on the values it gets back cannot be scored with +# values computed for another request. Each key's parts are joined in +# batch order (``_concatenate_post_export_parts``), so every value, total +# and output is byte-identical to the serial scorer's. A pass that failed +# in a worker raises an error with the worker's exception's class name and +# message when the consumer asks for it, where the serial scorer would +# have raised. + + +def _peak_rss_bytes() -> int: + import resource + + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + # ru_maxrss is bytes on macOS and kilobytes on Linux. + return int(peak if sys.platform == "darwin" else peak * 1024) + + +def _post_export_unit_failure( + stage: str, error: BaseException +) -> PostExportUnitFailure: + return PostExportUnitFailure.from_exception( + stage, error, batch_file_error=isinstance(error, PostExportBatchFileError) + ) + + +class _PostExportWorkerTracebackError(Exception): + """The traceback of an exception a pool worker returned.""" + + def __str__(self) -> str: + return f"in a pool worker:\n{self.args[0]}" + + +def _raise_post_export_worker_failure(failure: PostExportUnitFailure): + """Raise what a worker's pass raised, chained to the worker's traceback. + + A changed or unreadable batch file raises this tool's own + :class:`PostExportBatchFileError`, which the held-out reports re-raise. + """ + if failure.batch_file_error: + error: BaseException = PostExportBatchFileError(failure.message) + else: + error = failure.exception() + raise error from _PostExportWorkerTracebackError(failure.traceback) + + +class _PostExportWorker: + """A pool worker's side of pooled post-export scoring. + + The pool's initializer (``start_post_export_worker``) builds one in each + worker from the batch files the parent's scorer wrote; each unit is then + one :meth:`score`. ``microsimulation_cls``, ``dataset_from_frame`` and + ``reform_builder`` are policyengine-us's ``Microsimulation``, + :func:`_post_export_dataset` and ``build_post_export_reform`` unless the + parent passed others (tests do). + """ + + def __init__( + self, + batch_files: Sequence[tuple[str, str]], + n_batches: int, + microsimulation_cls=None, + dataset_from_frame=None, + reform_builder=None, + ) -> None: + self._batches = _PostExportBatchFiles.written(batch_files) + if len(self._batches) != int(n_batches): + raise ValueError( + f"A post-export worker got {len(self._batches)} batch files for " + f"an H5 of {n_batches} batches." + ) + if microsimulation_cls is None: + from policyengine_us import Microsimulation + + microsimulation_cls = Microsimulation + self._microsimulation_cls = microsimulation_cls + self._dataset_from_frame = dataset_from_frame or _post_export_dataset + self._build_reform = reform_builder or build_post_export_reform + + def _construct(self, batch_frame: Frame, *, reform_system): + return _construct_post_export_engine( + self._microsimulation_cls, + self._dataset_from_frame(batch_frame), + reform_system=reform_system, + ) + + def score(self, unit: PostExportUnit) -> PostExportUnitResult: + """Run each pass of ``unit``; return its values or its failure. + + A reform unit's rules are built once, before its first pass (whose + timing includes them), and the modules their build added are removed + when the unit ends. A failure to build them is every pass's failure. + """ + if unit.n_batches != len(self._batches): + raise ValueError( + f"{unit.describe()} names an H5 of {unit.n_batches} batches; " + f"this worker has {len(self._batches)}." + ) + outcomes: list[PostExportPassValues | PostExportUnitFailure] = [] + timings: list[PostExportPassTiming] = [] + wall, cpu = time.perf_counter(), time.process_time() + system = None + rules_failure: PostExportUnitFailure | None = None + rule_modules: EngineVariableModuleScope | None = None + try: + if unit.reform is not None: + rule_modules = EngineVariableModuleScope().open() + try: + system = self._microsimulation_cls.default_tax_benefit_system( + reform=self._build_reform(unit.reform) + ) + except MemoryError: + raise + except Exception as error: + rules_failure = _post_export_unit_failure("rules", error) + for scoring_pass in unit.passes: + outcomes.append( + rules_failure + if rules_failure is not None + else self._score_pass(unit, scoring_pass, system) + ) + timings.append( + PostExportPassTiming( + wall_seconds=time.perf_counter() - wall, + cpu_seconds=time.process_time() - cpu, + footprint_bytes=process_memory_bytes(os.getpid()), + peak_rss_bytes=_peak_rss_bytes(), + ) + ) + wall, cpu = time.perf_counter(), time.process_time() + finally: + system = None + if rule_modules is not None: + rule_modules.close() + return PostExportUnitResult( + outcomes=tuple(outcomes), timings=tuple(timings), worker_pid=os.getpid() + ) + + def _score_pass( + self, unit: PostExportUnit, scoring_pass: PostExportPass, system + ) -> PostExportPassValues | PostExportUnitFailure: + label = scoring_pass.label + if system is not None: + # The serial reform pass checks each of its periods once, in key + # order, before it builds a batch engine. + try: + checked: set[int] = set() + for key in scoring_pass.keys: + if key[1] not in checked: + checked.add(key[1]) + _refuse_moved_behavioral_responses( + system, + self._microsimulation_cls.default_tax_benefit_system_instance, + key, + label=label, + ) + except MemoryError: + raise + except Exception as error: + return _post_export_unit_failure("responses", error) + try: + parts = _score_post_export_batches( + self._batches, + range(unit.batch_start, unit.batch_stop), + scoring_pass.keys, + label=label, + construct=self._construct, + reform_system=system, + batched=unit.n_batches > 1, + ) + except MemoryError: + raise + except Exception as error: + return _post_export_unit_failure("scoring", error) + return PostExportPassValues( + parts=tuple(tuple(parts[key]) for key in scoring_pass.keys) + ) + + +def _describe_post_export_unit(index: int, unit: PostExportUnit) -> str: + return unit.describe() + + +class _PostExportPooling: + """How pooled post-export scoring runs. + + ``settings`` are the shared pool's: the most workers, the per-worker + memory cap, the replacement interval, the attempts per unit and the + environment each worker gets. The scorer starts no more workers than a + pool run has units, and adds this process's policyengine-us lock-check + record to each worker's environment (``_post_export_worker_settings``). + ``chosen_by`` says how the worker count was chosen; the manifests record + it with the settings as run metadata. + + ``microsimulation_cls``, ``dataset_from_frame`` and ``reform_builder`` + replace, in every worker and for the scorer's own checks, the engine, the + batch dataset and the reform builder; each must be importable by name in a + spawned worker. ``None`` keeps policyengine-us's ``Microsimulation``, + :func:`_post_export_dataset` and ``build_post_export_reform``. (A plain + class, for the reason :class:`_PostExportScoringPlan` gives.) + """ + + def __init__( + self, + settings: WorkerPoolSettings, + *, + chosen_by: str, + microsimulation_cls=None, + dataset_from_frame=None, + reform_builder=None, + ) -> None: + if not isinstance(settings, WorkerPoolSettings): + raise TypeError("Pooled post-export scoring needs WorkerPoolSettings.") + if not isinstance(chosen_by, str) or not chosen_by: + raise ValueError("Say how the post-export worker count was chosen.") + self.settings = settings + self.chosen_by = chosen_by + self.microsimulation_cls = microsimulation_cls + self.dataset_from_frame = dataset_from_frame + self.reform_builder = reform_builder + + +def _post_export_worker_settings( + pooling: _PostExportPooling, *, workers: int +) -> WorkerPoolSettings: + """The pool's settings: at most ``workers`` workers, each handed this + process's policyengine-us lock-check record. + + A worker imports the release tool, whose spec bundle checks the + policyengine-us lock file (two tax-benefit systems built and the engine's + source indexed) unless its parent hands it the record of a check the + parent passed (``us_engine_abi_lock_check_environment``). Without one + (no attested check ran here), each worker checks the lock file itself. + """ + from microcosm.build.us_runtime.take_up_contract import ( + us_engine_abi_lock_check_environment, + ) + + settings = pooling.settings + environment = { + **(settings.worker_environment or {}), + **us_engine_abi_lock_check_environment(), + } + return dataclasses.replace( + settings, + workers=max(1, min(settings.workers, int(workers))), + worker_environment=environment or None, + ) + + +def _post_export_batch_ranges(n_batches: int, ranges: int) -> tuple[range, ...]: + """``n_batches`` split into at most ``ranges`` contiguous, near-equal ranges.""" + count = max(1, min(int(ranges), int(n_batches))) + bounds = [index * n_batches // count for index in range(count + 1)] + return tuple( + range(start, stop) + for start, stop in zip(bounds, bounds[1:], strict=False) + if start < stop + ) + + +class _PooledPostExportScorer(_HouseholdBatchedPostExportScorer): + """Scores the recorded requests in the shared worker pool and serves each + consumer, when it runs again in this process, from the results (see the + block comment above). + + ``consumer_requests`` are the plan's records of each consumer's dry run + (``_PostExportScoringPlan.consumer_requests``), in the order the + consumers run; every one is registered, so the merged baseline pass holds + every plan. Only those consumers may be opened, each once, in that order + (one that stops early is passed over when the next opens). The pool + starts when the first consumer opens and stops when the scorer closes. + ``pass_timing_listener``, if set, is called with one row per pass a worker + ran, as its results arrive (the export probe writes them out). + """ + + def __init__( + self, + dataset_path: Path, + *, + maximum_microsim_batch_size: int | None, + consumer_requests: Mapping[str, _PostExportConsumerRequests], + pooling: _PostExportPooling, + expected_n_households: int | None = None, + batch_parent: Path | None = None, + load_frame=None, + ) -> None: + requests = dict(consumer_requests) + for name, recorded in requests.items(): + if not isinstance(recorded, _PostExportConsumerRequests): + raise TypeError( + f"{name}: pooled post-export scoring needs the consumer's " + "recorded requests (_PostExportConsumerRequests)." + ) + super().__init__( + dataset_path, + maximum_microsim_batch_size=maximum_microsim_batch_size, + expected_n_households=expected_n_households, + batch_parent=batch_parent, + microsimulation_cls=pooling.microsimulation_cls, + dataset_from_frame=pooling.dataset_from_frame, + load_frame=load_frame, + baseline_plans={ + name: recorded.baseline_plan for name, recorded in requests.items() + }, + ) + self._requests = requests + self._pooling = pooling + self.pass_timing_listener: Callable[[dict[str, object]], None] | None = None + self._pool: WorkerPool | None = None + self._started = False + self._workers = 0 + self._units = {"baseline": 0, "reform": 0} + self._stream: Iterator[PostExportUnitResult] | None = None + self._stream_units: tuple[PostExportUnit, ...] = () + self._next_unit = 0 + # Why the pool stopped serving, once it has. + self._stopped: BaseException | None = None + self._opened: list[str] = [] + self._simulations_opened: dict[str, int] = {} + self._passes_asked: dict[tuple[str, int], int] = {} + self._rules_counted: set[tuple[str, int]] = set() + # The reform unit whose passes are being served: (consumer, + # simulation, unit, result). + self._serving: tuple[str, int, PostExportUnit, PostExportUnitResult] | None = ( + None + ) + + # ---- the pool ---------------------------------------------------------- + + def _baseline_units( + self, consumer: str | None, label: str, keys: Sequence[PostExportKey] + ) -> tuple[PostExportUnit, ...]: + scoring_pass = PostExportPass(label=label, keys=tuple(keys)) + return tuple( + PostExportUnit( + consumer=consumer, + reformed_simulation=None, + reform=None, + passes=(scoring_pass,), + batch_start=batches.start, + batch_stop=batches.stop, + n_batches=self.n_batches, + ) + for batches in _post_export_batch_ranges( + self.n_batches, self._pooling.settings.workers + ) + ) + + def _reform_units(self, consumer: str) -> tuple[PostExportUnit, ...]: + recorded = self._requests[consumer] + return tuple( + PostExportUnit( + consumer=consumer, + reformed_simulation=simulation, + reform=recorded.reforms[simulation], + passes=tuple( + PostExportPass( + label=_post_export_reform_pass_label(consumer, keys), keys=keys + ) + for keys in recorded.passes_of(simulation) + ), + batch_start=0, + batch_stop=self.n_batches, + n_batches=self.n_batches, + ) + for simulation in recorded.simulations + ) + + def _start(self) -> None: + """Run the merged baseline pass, then start the reform units. + + A start that failed is not tried again: every later request names the + failure. + """ + if self._stopped is not None: + raise RuntimeError( + "Pooled post-export scoring stopped earlier; nothing more is served." + ) from self._stopped + if self._started: + return + self._batches() + self._started = True + try: + self._start_pool() + except BaseException as error: + self._stopped = error + raise + + def _start_pool(self) -> None: + merged = _ascending_period_plan( + key for plan in self._unserved_baseline_plans.values() for key in plan + ) + baseline_units = ( + self._baseline_units(None, "merged baseline plan", merged) if merged else () + ) + reform_units = tuple( + unit for name in self._requests for unit in self._reform_units(name) + ) + self._units = {"baseline": len(baseline_units), "reform": len(reform_units)} + if not baseline_units and not reform_units: + return + self._workers = max( + 1, + min( + self._pooling.settings.workers, + max(len(baseline_units), len(reform_units)), + ), + ) + pooling = self._pooling + self._pool = WorkerPool( + _post_export_worker_settings(pooling, workers=self._workers), + unit_function=score_post_export_unit, + initializer=start_post_export_worker, + initargs=( + __name__, + str(Path(__file__).resolve()), + self._batches().files, + self.n_batches, + pooling.microsimulation_cls, + pooling.dataset_from_frame, + pooling.reform_builder, + ), + describe_unit=_describe_post_export_unit, + ) + if baseline_units: + self._run_merged_baseline(baseline_units, merged) + if self._merged_baseline_failed: + layout = [] + for name, recorded in self._requests.items(): + if recorded.baseline_plan: + layout.extend( + self._baseline_units( + name, f"{name} baseline plan", recorded.baseline_plan + ) + ) + layout.extend(self._reform_units(name)) + stream_units = tuple(layout) + else: + stream_units = reform_units + if stream_units: + self._stream_units = stream_units + self._stream = self._pool.map(stream_units) + + def _run_merged_baseline( + self, units: Sequence[PostExportUnit], keys: Sequence[PostExportKey] + ) -> None: + label = units[0].passes[0].label + print( + f"Scoring post-export {label} ({len(keys)} key(s)) in " + f"{self.n_batches} batches of up to {self.max_batch_households:,} " + f"households, in {len(units)} pool unit(s) on up to {self._workers} " + "worker(s).", + flush=True, + ) + sweep = _WorkCounter( + stage_id="post_export_scoring", unit="scoring_batch", total=self.n_batches + ) + parts: dict[PostExportKey, list[tuple[np.ndarray, np.ndarray]]] = { + key: [] for key in keys + } + failure: PostExportUnitFailure | None = None + results = self._pool.map(units) + try: + for unit, result in zip(units, results, strict=True): + self._report_timing(unit, result) + outcome = result.outcomes[0] + if isinstance(outcome, PostExportUnitFailure): + if outcome.batch_file_error: + # The scored file's integrity: no consumer's own + # pass could read the batch either. + _raise_post_export_worker_failure(outcome) + failure = failure or outcome + continue + if failure is None: + for key, key_parts in zip(keys, outcome.parts, strict=True): + parts[key].extend(key_parts) + sweep.advance( + unit.batch_stop - unit.batch_start, + pass_name=label, + batch=unit.batch_stop, + batches=self.n_batches, + ) + finally: + results.close() + if failure is not None: + # As the serial scorer: every consumer then scores its own plan. + self._merged_baseline_failed = True + del parts + print( + f"Post-export merged baseline plan failed ({failure.error_name}: " + f"{failure.message}); each consumer scores its own baseline plan " + "instead.", + flush=True, + ) + _collect_family_garbage() + return + self._merged_baseline = { + key: _concatenate_post_export_parts(parts.pop(key)) for key in keys + } + + def _report_timing( + self, unit: PostExportUnit, result: PostExportUnitResult + ) -> None: + listener = self.pass_timing_listener + if listener is None: + return + for scoring_pass, timing, outcome in zip( + unit.passes, result.timings, result.outcomes, strict=True + ): + listener( + { + "label": scoring_pass.label, + "keys": len(scoring_pass.keys), + "reform": unit.reform is not None, + "batches": unit.batch_stop - unit.batch_start, + "batch_start": unit.batch_start, + "worker_pid": result.worker_pid, + "failed": isinstance(outcome, PostExportUnitFailure), + "wall_seconds": round(timing.wall_seconds, 3), + "cpu_seconds": round(timing.cpu_seconds, 3), + "footprint_bytes": timing.footprint_bytes, + "peak_rss_bytes": timing.peak_rss_bytes, + } + ) + + def _take(self, consumer: str, simulation: int | None): + """The next run of stream units for ``(consumer, simulation)``. + + Units of a consumer opened before this one, which stopped before + asking for them, are passed over. Any other unit in the way means the + consumer asked out of its recorded order, which is refused. + """ + if self._stopped is not None: + raise RuntimeError( + "Pooled post-export scoring stopped earlier; nothing more is served." + ) from self._stopped + taken: list[tuple[PostExportUnit, PostExportUnitResult]] = [] + while self._next_unit < len(self._stream_units): + unit = self._stream_units[self._next_unit] + ours = unit.consumer == consumer and unit.reformed_simulation == simulation + if not ours and (taken or unit.consumer == consumer): + break + if not ours and unit.consumer not in self._opened: + break + self._next_unit += 1 + try: + result = next(self._stream) + except BaseException as error: + # The pool stopped (a unit failed on every attempt, a worker + # could not start, the scorer closed): nothing after it can + # be served. + self._stopped = error + raise + self._report_timing(unit, result) + if ours: + taken.append((unit, result)) + if not taken: + asked = ( + "baseline plan" + if simulation is None + else (f"reformed simulation {simulation}") + ) + raise RuntimeError( + f"{consumer} asked for its {asked} out of the order its " + "engine-free dry run recorded; pooled post-export scoring " + "serves each consumer its recorded requests in that order." + ) + return taken + + # ---- consumers --------------------------------------------------------- + + def open_consumer( + self, + name: str, + baseline_plan: Sequence[PostExportKey], + planned_reform_passes: int | None = None, + ) -> _PostExportConsumer: + if name not in self._requests: + raise ValueError( + f"{name} has no recorded requests; pooled post-export scoring " + "serves only the consumers whose dry run the plan recorded." + ) + if name in self._opened: + raise ValueError( + f"{name} was opened on this scorer already; pooled post-export " + "scoring serves each recorded consumer once." + ) + self._batches() + self._opened.append(name) + self._start() + return super().open_consumer( + name, baseline_plan, planned_reform_passes=planned_reform_passes + ) + + def finish_consumer(self, scoring: _PostExportConsumer) -> dict[str, object]: + if scoring._scorer is self and scoring.name not in self.consumer_records: + recorded = self._requests[scoring.name] + unasked = [ + simulation + for simulation in recorded.simulations + if self._passes_asked.get((scoring.name, simulation), 0) + != len(recorded.passes_of(simulation)) + ] + if unasked: + raise RuntimeError( + f"{scoring.name} finished without asking reformed " + f"simulation(s) {unasked} for every pass its engine-free dry " + "run recorded; pooled post-export scoring serves each " + "consumer its recorded requests only, so a consumer must ask " + "for the same keys whatever values it gets back." + ) + return super().finish_consumer(scoring) + + def _baseline_for( + self, name: str, baseline_plan: tuple[PostExportKey, ...] + ) -> tuple[dict[PostExportKey, _PostExportValues], bool]: + if ( + not baseline_plan + or self._registered_baseline_plans.get(name) != baseline_plan + ): + # Nothing to score, or a plan other than the registered one, which + # the serial scorer's check refuses. + return super()._baseline_for(name, baseline_plan) + if not self._merged_baseline_failed: + if ( + self._merged_baseline is None + or name not in self._unserved_baseline_plans + ): + raise RuntimeError( + f"{name}: the pool's merged baseline pass holds no values " + "for it; pooled post-export scoring scores nothing in this " + "process." + ) + # The merged pass's values, served as the serial scorer serves them. + return super()._baseline_for(name, baseline_plan) + # The merged pass failed: the consumer's own pass, from the stream. + parts: dict[PostExportKey, list[tuple[np.ndarray, np.ndarray]]] = { + key: [] for key in baseline_plan + } + failure: PostExportUnitFailure | None = None + for _, result in self._take(name, None): + outcome = result.outcomes[0] + if isinstance(outcome, PostExportUnitFailure): + failure = failure or outcome + elif failure is None: + for key, key_parts in zip(baseline_plan, outcome.parts, strict=True): + parts[key].extend(key_parts) + if failure is not None: + del parts + _raise_post_export_worker_failure(failure) + return { + key: _concatenate_post_export_parts(parts.pop(key)) for key in baseline_plan + }, False + + def _open_reform_for(self, consumer: _PostExportConsumer, reform): + self._finish_open_reform() + simulation = self._simulations_opened.get(consumer.name, 0) + self._simulations_opened[consumer.name] = simulation + 1 + self._open_reform = _PooledPostExportReform(consumer, simulation) + return self._open_reform + + def _reform_pass( + self, + consumer: _PostExportConsumer, + simulation: int, + keys: tuple[PostExportKey, ...], + ) -> dict[PostExportKey, _PostExportValues]: + """Serve one reform pass of a consumer's reformed simulation. + + It must be the next pass the dry run recorded for that simulation. + The consumer's counts move as the serial scorer's do: a reform system + once its rules are built, then a reform pass once its + behavioral-response check passes. + """ + name = consumer.name + recorded = self._requests[name].passes_of(simulation) + asked = self._passes_asked.get((name, simulation), 0) + if asked >= len(recorded) or recorded[asked] != tuple(keys): + requested = ", ".join( + f"{variable}@{period}" for variable, period, _ in keys + ) + raise RuntimeError( + f"{name} asked reformed simulation {simulation} for {requested}, " + "which is not the next reform pass its engine-free dry run " + "recorded. Pooled post-export scoring scores only the recorded " + "requests, so a consumer must ask for the same keys whatever " + "values it gets back." + ) + if asked == 0: + [(unit, result)] = self._take(name, simulation) + self._serving = (name, simulation, unit, result) + serving = self._serving + if serving is None or serving[:2] != (name, simulation): + raise RuntimeError( + f"{name}: reformed simulation {simulation}'s results are no " + "longer held." + ) + unit, result = serving[2], serving[3] + self._passes_asked[(name, simulation)] = asked + 1 + if asked + 1 == len(recorded): + self._serving = None + outcome = result.outcomes[asked] + failed = isinstance(outcome, PostExportUnitFailure) + if failed and outcome.stage == "rules": + _raise_post_export_worker_failure(outcome) + if (name, simulation) not in self._rules_counted: + self._rules_counted.add((name, simulation)) + consumer.reform_systems += 1 + if failed and outcome.stage == "responses": + _raise_post_export_worker_failure(outcome) + outer = consumer._count_reform_pass() + if failed: + _raise_post_export_worker_failure(outcome) + label = unit.passes[asked].label + values = { + key: _concatenate_post_export_parts(key_parts) + for key, key_parts in zip(keys, outcome.parts, strict=True) + } + _WorkCounter( + stage_id="post_export_scoring", + unit="scoring_batch", + total=self.n_batches, + outer=outer, + ).advance( + self.n_batches, + pass_name=label, + batch=self.n_batches, + batches=self.n_batches, + ) + return values + + # ---- records and closing ----------------------------------------------- + + def execution_record(self) -> dict[str, object]: + """How this scorer ran: run metadata, outside every output comparison.""" + settings = self._pooling.settings + record: dict[str, object] = { + "mode": "pooled", + "chosen_by": self._pooling.chosen_by, + "requested_workers": settings.workers, + "workers": self._workers, + "memory_cap_bytes": settings.memory_cap_bytes, + "max_units_per_worker": settings.max_units_per_worker, + "max_attempts": settings.max_attempts, + "max_units_ahead": settings.max_units_ahead, + "worker_environment_variables": sorted(settings.worker_environment or ()), + "units": dict(self._units), + "report": None, + } + if self._pool is not None: + record["report"] = _worker_pool_report_record(self._pool.report()) + return record + + def close(self) -> None: + stream, self._stream = self._stream, None + self._serving = None + try: + if stream is not None: + # An unfinished run closes the pool, stopping its workers. + stream.close() + if self._pool is not None: + self._pool.close() + finally: + super().close() + + +def _worker_pool_report_record(report: WorkerPoolReport) -> dict[str, object]: + return { + "worker_starts": report.worker_starts, + "units_completed": report.units_completed, + "max_live_workers": report.max_live_workers, + "peak_worker_memory_bytes": report.peak_worker_memory_bytes, + "workers_stopped_over_cap": report.workers_stopped_over_cap, + "failed_attempts": [ + { + "unit": attempt.label, + "attempt": attempt.attempt, + "cause": attempt.cause, + } + for attempt in report.failed_attempts + ], + } + + +class _PooledPostExportReform: + """A reformed simulation a consumer sees in pooled scoring: each pass it + asks for is served from the pool's results (``_PooledPostExportScorer``), + and must be the pass the dry run recorded. As in the serial scorer, a + finished reform refuses further keys.""" + + def __init__(self, consumer: _PostExportConsumer, simulation: int) -> None: + self._consumer = consumer + self._simulation = simulation + self._results: dict[PostExportKey, _PostExportValues] = {} + self._finished = False + + def calculate(self, variable, period=None, map_to=None) -> _PostExportValues: + key = _post_export_key(variable, period, map_to) + self._score_new((key,)) + return self._results[key] + + def prefetch(self, requests) -> None: + """Serve every requested key not yet served as one recorded pass.""" + self._score_new(tuple(_post_export_key(*request) for request in requests)) + + def _score_new(self, keys: Sequence[PostExportKey]) -> None: + if self._finished: + asked = keys[0] if len(keys) == 1 else tuple(keys) + raise RuntimeError( + f"{self._consumer.name} asked a finished reform for {asked}. A " + "post-export consumer scores each reform completely before it " + "opens the next one, which finishes and releases the earlier." + ) + new_keys = _ascending_period_plan( + key for key in keys if key not in self._results + ) + if not new_keys: + return + self._results.update( + self._consumer._scorer._reform_pass( + self._consumer, self._simulation, new_keys + ) + ) + + def finish(self) -> None: + self._finished = True + self._results = {} + + def _reform_household_income_tax( *, base_frame: Frame, @@ -11859,8 +12943,9 @@ def _write_ssi_social_security_holdout( maximum_microsim_batch_size=maximum_microsim_batch_size, ) payload["release_id"] = release_id - except PostExportBatchFileError: - # The scored file's integrity, not a measurement: it stops certification. + except (PostExportBatchFileError, WorkerPoolError): + # The scored file's integrity, or the worker pool's failure to score + # it, not a measurement: it stops certification. raise except Exception as error: # Reporting is observational, including an unavailable measurement. @@ -11893,8 +12978,9 @@ def _write_medicare_irmaa_holdout( maximum_microsim_batch_size=maximum_microsim_batch_size, ) payload["release_id"] = release_id - except PostExportBatchFileError: - # The scored file's integrity, not a measurement: it stops certification. + except (PostExportBatchFileError, WorkerPoolError): + # The scored file's integrity, or the worker pool's failure to score + # it, not a measurement: it stops certification. raise except Exception as error: # Reporting is observational, including an unavailable measurement. @@ -19818,6 +20904,7 @@ def _certify_us_build( *, certification: _Certification, telemetry: _BuildProgress | None = None, + post_export_pooling: _PostExportPooling | None = None, ) -> None: """Run a finished build's post-export checks and write its manifests. @@ -19833,7 +20920,9 @@ def _certify_us_build( packages) is the build's, from the record. A build has no tier: ``certification`` is the tier certification chose, the release directory it placed the build's files in and the ID it publishes the build under, - and both manifests record it beside the build's provenance. + and both manifests record it beside the build's provenance. With + ``post_export_pooling`` the post-export stages are scored in the shared + worker pool (``_PooledPostExportScorer``); without it, in this process. """ certify_started = time.perf_counter() @@ -19902,11 +20991,14 @@ def _certify_us_build( # household-batched scorer instead of one whole-pool Microsimulation each. # It loads the written H5 once, binds its sha256 (the manifest must pin # the same bytes), and serves the baseline plans recorded above from one - # merged baseline pass (microcosm#1595). + # merged baseline pass (microcosm#1595). With pooling, the plan's + # recorded requests are scored in the shared worker pool and each stage + # is served from the results, byte-identically. post_export_scorer = _open_post_export_scorer( post_export_scoring_plan, dataset_path, batch_parent=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY, + pooling=post_export_pooling, ) # microcosm#368: reform-coverage smoke on the WRITTEN release H5. The column # gate above proves the required keys exist and carry signal; this is the diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index bb0f3268dc..213e7528cc 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -31,7 +31,12 @@ ``--target-surface`` says otherwise). The engine stages run in ``_main``'s order (smoke, validation, demographics on -one scorer, then source coverage). The frame-based stages (1-3) run first, +one scorer, then source coverage). As in certification, the scorer registers +every engine stage's recorded baseline plan, so one shared baseline pass, run +when the first stage opens, serves them all; with the release tool's +``_PostExportPooling`` (``ExportProbe(post_export_pooling=...)``) the stages' +recorded requests are scored in the shared worker pool, as certification +scores them. The frame-based stages (1-3) run first, while the loaded frame is held, instead of after the scorer as in ``_main``: they read only the frame, so the order changes no verdict. Unlike the release, a stage that raises is recorded with its traceback and the next @@ -92,7 +97,13 @@ Every stage records wall time, CPU time and peak resident memory (sampled every 0.5 s with psutil, else the process peak); every batch-outer scoring -pass is one line of ``passes.jsonl``. +pass is one line of ``passes.jsonl``. With pooled scoring, a line is one pass +a pool worker ran (a range of the shared baseline pass, or one reform pass), +with the worker's process ID, its wall and CPU time, and the worker's memory +footprint and peak resident memory; each stage records the CPU time of the +worker passes whose results reached it (``worker_cpu_seconds``), and the +report's ``post_export_scoring.execution`` holds the pool's settings and +report (worker starts, failed attempts, peak worker memory). Usage:: @@ -989,7 +1000,10 @@ class HouseholdRowMap: """ def __init__(self, batch_frames: Sequence[Any], *, sampler) -> None: - self._batches = tuple(batch_frames) + # The sequence itself, not a tuple of its items: the scorer's batches + # are files, read one at a time as they are indexed, so the map holds + # one batch frame at a time, as certification's scorer does. + self._batches = batch_frames self._sampler = sampler self._cache: dict[str, tuple[np.ndarray, np.ndarray]] = {} @@ -1543,14 +1557,28 @@ def _gib(value: float) -> float: class StageClock: - """Runs each stage, recording wall/CPU/peak RSS and any exception.""" + """Runs each stage, recording wall/CPU/peak RSS and any exception. + + With pooled scoring, the CPU time of the passes pool workers ran, whose + results reached this process during a stage, is that stage's + ``worker_cpu_seconds`` (:meth:`add_worker_pass`); ``cpu_seconds`` is this + process's alone. + """ def __init__(self, sampler: RssSampler | None) -> None: self.sampler = sampler self.current = "setup" + self._worker_cpu = 0.0 + self._worker_passes = 0 + + def add_worker_pass(self, cpu_seconds: float) -> None: + self._worker_cpu += float(cpu_seconds) + self._worker_passes += 1 def run(self, name: str, fn: Callable[[], Mapping[str, Any]]) -> dict[str, Any]: self.current = name + self._worker_cpu = 0.0 + self._worker_passes = 0 before = self.sampler.reset() if self.sampler else 0 wall = time.perf_counter() cpu = time.process_time() @@ -1568,6 +1596,8 @@ def run(self, name: str, fn: Callable[[], Mapping[str, Any]]) -> dict[str, Any]: "cpu_seconds": round(time.process_time() - cpu, 3), "rss_before_gib": _gib(before), "peak_rss_gib": _gib(self.sampler.peak()) if self.sampler else None, + "worker_passes": self._worker_passes, + "worker_cpu_seconds": round(self._worker_cpu, 3), } print( f"[probe] {name}: {record['status']} in " @@ -1820,6 +1850,7 @@ def __init__( builder=None, sampler=None, scorer_options: Mapping[str, Any] | None = None, + post_export_pooling=None, load_frame: Callable[..., Any] | None = None, measure_entity: Callable[[str], str | None] | None = None, sample_rss: bool = True, @@ -1892,6 +1923,10 @@ def __init__( probes = us_release_reform_coverage_probes() self.probes = tuple(probes) self.scorer_options = dict(scorer_options or {}) + # The release tool's ``_PostExportPooling``: with it the engine stages + # are scored in the shared worker pool, as certification scores them; + # without it every pass runs in this process. + self.post_export_pooling = post_export_pooling self.load_frame = load_frame self.measure_entity = measure_entity self.chunk_bytes = int(chunk_bytes or self.sampler.DEFAULT_CHUNK_BYTES) @@ -1900,6 +1935,9 @@ def __init__( self.passes_path = self.out_dir / PASSES_FILENAME self.frame = None self.scorer = None + self.scoring_plan = None + self.stage_request_errors: dict[str, Exception] = {} + self.n_households: int | None = None self.sha256: str | None = None self.design: SampleDesign | None = None self.design_problems: list[str] = [] @@ -2174,6 +2212,7 @@ def _design(self) -> dict[str, Any]: ) self._verify_source() n = int(frame.n("household")) + self.n_households = n self.batch_size = choose_batch_size(n, self.batch_size_requested) for probe in self.probes: self.carriers_by_probe[str(probe.id)] = probe_carrier_households( @@ -2458,14 +2497,75 @@ def _take_up(self) -> dict[str, Any]: # ---- the household-batched scorer ---------------------------------------- + def _engine_consumers(self) -> dict[str, Callable[[], Any]]: + """The engine stages to run, in ``_main``'s order: for each, a function + that returns its consumer (a function of the ``simulate`` seam).""" + makers: dict[str, Callable[[], Any]] = { + "reform_coverage_smoke": self._smoke_consumer, + "reform_validation": lambda: self._validation_consumer()[0], + "demographics": lambda: self.builder._demographics_consumer, + } + return {name: make for name, make in makers.items() if name in self.stages} + + def _record_stage_requests(self) -> dict[str, Any]: + """Each engine stage's recorded requests, from its own dry run. + + A stage whose consumer cannot be made, or whose dry run raises, is + left out of the plan, and its own stage raises that error, so the + other stages still run (the release would refuse the plan before its + export instead). + """ + requests: dict[str, Any] = {} + self.stage_request_errors = {} + for name, make in self._engine_consumers().items(): + try: + requests[name] = self.builder._record_post_export_consumer_requests( + name, make() + ) + except Exception as error: + self.stage_request_errors[name] = error + return requests + def _open_scorer(self) -> dict[str, Any]: - scorer_cls = _timed_scorer_class(self.builder, self.passes_path, self.clock) - scorer = scorer_cls( - self.export_path, - maximum_microsim_batch_size=self.batch_size, - load_frame=self.load_frame, - **self.scorer_options, + """Record the engine stages' plan and open the scorer it registers. + + As in certification, every stage's baseline plan is registered, so + one merged baseline pass serves them all; with ``post_export_pooling`` + the recorded requests are scored in the shared worker pool, and each + pass a worker ran is one line of ``passes.jsonl``. + """ + builder = self.builder + requests = self._record_stage_requests() + plan = builder._PostExportScoringPlan( + n_households=int(self.n_households or 0), + maximum_batch_size=self.batch_size, + baseline_plans={ + name: recorded.baseline_plan for name, recorded in requests.items() + }, + reform_passes={ + name: len(recorded.reform_passes) for name, recorded in requests.items() + }, + consumer_requests=requests, ) + self.scoring_plan = plan + if self.post_export_pooling is not None: + scorer = builder._PooledPostExportScorer( + self.export_path, + maximum_microsim_batch_size=self.batch_size, + consumer_requests=plan.consumer_requests, + pooling=self.post_export_pooling, + load_frame=self.load_frame, + ) + scorer.pass_timing_listener = self._record_worker_pass + else: + scorer_cls = _timed_scorer_class(builder, self.passes_path, self.clock) + scorer = scorer_cls( + self.export_path, + maximum_microsim_batch_size=self.batch_size, + load_frame=self.load_frame, + baseline_plans=plan.baseline_plans, + **self.scorer_options, + ) if scorer.dataset_sha256 != self.sha256: scorer.close() raise ValueError("The scorer loaded different bytes than the probe.") @@ -2477,12 +2577,51 @@ def _open_scorer(self) -> dict[str, Any]: ) self.scorer = scorer return { + "mode": "serial" if self.post_export_pooling is None else "pooled", "n_households": scorer.n_households, "n_batches": scorer.n_batches, "max_batch_households": scorer.max_batch_households, "maximum_batch_size": scorer.maximum_batch_size, + "registered_consumers": list(plan.baseline_plans), } + def _record_worker_pass(self, row: Mapping[str, Any]) -> None: + """One line of ``passes.jsonl`` per pass a pool worker ran, written as + its results reach this process, under the stage running then.""" + self.clock.add_worker_pass(row["cpu_seconds"]) + footprint = row.get("footprint_bytes") + line = { + "stage": self.clock.current, + "label": row["label"], + "keys": row["keys"], + "reform": row["reform"], + "batches": row["batches"], + "batch_start": row["batch_start"], + "process": "pool worker", + "worker_pid": row["worker_pid"], + "failed": row["failed"], + "wall_seconds": row["wall_seconds"], + "cpu_seconds": row["cpu_seconds"], + "worker_footprint_gib": None if footprint is None else _gib(footprint), + "worker_peak_rss_gib": _gib(row["peak_rss_bytes"]), + } + with self.passes_path.open("a") as handle: + handle.write(json.dumps(line) + "\n") + + def _scoring(self, name: str): + """Open ``name`` on the scorer with its registered plan.""" + error = self.stage_request_errors.get(name) + if error is not None: + # The stage fails with its own dry run's error, as it would if it + # had recorded its plan itself. + raise error + plan = self.scoring_plan + return self.scorer.open_consumer( + name, + plan.baseline_plan(name), + planned_reform_passes=plan.planned_reform_passes(name), + ) + def _resolve_entity(self, variable: str) -> str | None: if self.measure_entity is not None: return self.measure_entity(variable) @@ -2498,23 +2637,25 @@ def _resolve_entity(self, variable: str) -> str | None: # ---- 2. reform-coverage smoke ---------------------------------------------- - def _smoke(self) -> dict[str, Any]: + def _smoke_consumer(self) -> Callable[[Callable[[Any], Any]], Any]: builder = self.builder probes = self.probes + if not self.custom_probes: + # The release's own consumer: the shipped probes, in its order. + return builder._reform_coverage_smoke_consumer - if self.custom_probes: + def gate_for(simulate): + return builder.us_reform_coverage_smoke_gate( + simulate=simulate, probes=probes, period=builder.PERIOD + ) - def gate_for(simulate): - return builder.us_reform_coverage_smoke_gate( - simulate=simulate, probes=probes, period=builder.PERIOD - ) + return gate_for - else: - # The release's own consumer: the shipped probes, in its order. - gate_for = builder._reform_coverage_smoke_consumer - - plan = builder._record_post_export_baseline_plan(gate_for) - scoring = self.scorer.open_consumer("reform_coverage_smoke", plan) + def _smoke(self) -> dict[str, Any]: + probes = self.probes + gate_for = self._smoke_consumer() + scoring = self._scoring("reform_coverage_smoke") + plan = self.scoring_plan.baseline_plan("reform_coverage_smoke") recorder = SimulateRecorder(scoring.simulate) gate = gate_for(recorder) scoring_record = self.scorer.finish_consumer(scoring) @@ -2755,7 +2896,8 @@ def _smoke_analysis( # ---- 3. reform validation ----------------------------------------------- - def _validation(self) -> dict[str, Any]: + def _validation_consumer(self): + """Reform validation's consumer and how its in-sample rows are scored.""" builder = self.builder if self.calibration_diagnostics is None: result = SimpleNamespace( @@ -2776,8 +2918,13 @@ def _validation(self) -> dict[str, Any]: payload_for = builder._reform_validation_consumer( result=result, release_id=self._release_id() ) - plan = builder._record_post_export_baseline_plan(payload_for) - scoring = self.scorer.open_consumer("reform_validation", plan) + return payload_for, in_sample + + def _validation(self) -> dict[str, Any]: + builder = self.builder + payload_for, in_sample = self._validation_consumer() + scoring = self._scoring("reform_validation") + plan = self.scoring_plan.baseline_plan("reform_validation") payload = payload_for(scoring.simulate) scoring_record = self.scorer.finish_consumer(scoring) builder.write_reform_validation( @@ -2818,8 +2965,7 @@ def _validation(self) -> dict[str, Any]: def _demographics(self) -> dict[str, Any]: builder = self.builder - plan = builder._record_post_export_baseline_plan(builder._demographics_consumer) - scoring = self.scorer.open_consumer("demographics", plan) + scoring = self._scoring("demographics") ages, weights = builder._demographics_consumer(scoring.simulate) self.scorer.finish_consumer(scoring) payload = builder.demographics_payload( From 2b046b51d06c290195ecfb5d38f784501a144fdb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:11:41 +0400 Subject: [PATCH 03/26] Add failing tests for pooled post-export scoring as the default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tracker task 1.4 · 7, with the worker settings 1.4 · 6 recommends, which Anthony approved on 27 November. The tests require: - microcosm.build.host_resources to read the cores a process may use (its CPU affinity, limited by a cgroup v1 or v2 CPU quota) and the machine's memory (limited by a cgroup memory limit); - plan_post_export_workers to choose min(usable cores - 1, floor((0.75 * memory - 3 GiB) / 5 GiB)) workers, each capped at max(5 GiB, (0.75 * memory - 3 GiB) / workers) and replaced after 2 units, with inherited thread settings; to take a positive count or serial from MICROCOSM_POST_EXPORT_WORKERS and refuse anything else; and to refuse a machine too small for one worker unless the variable names a count or serial; - certification to choose its pool settings from the environment before it places the build, and pass them to _certify_us_build; the export probe's command to do the same before it loads the export; - the manifests' execution record to hold the plan. The certification tests that stub _certify_us_build take the new keyword, and the harness whose stand-in scorer is the serial scorer sets MICROCOSM_POST_EXPORT_WORKERS=serial. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_host_resources.py | 83 ++++++++++++ .../us/test_us_fiscal_refresh_builder.py | 27 ++-- .../us/test_us_post_export_pool.py | 114 +++++++++++++++++ .../us/test_us_post_export_pooled_scoring.py | 118 ++++++++++++++++++ 4 files changed, 334 insertions(+), 8 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_host_resources.py diff --git a/packages/microcosm-build/tests/engine_free/shared/test_host_resources.py b/packages/microcosm-build/tests/engine_free/shared/test_host_resources.py new file mode 100644 index 0000000000..9e6d14b0d0 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_host_resources.py @@ -0,0 +1,83 @@ +"""The memory and CPU cores a process may use (``microcosm.build.host_resources``). + +Pool sizes are planned from these (decision 1.1 · 2): the cores the process +may run on, limited by a cgroup CPU quota, and the machine's memory, limited +by a cgroup memory limit. The cgroup files are read from a directory the test +writes, in both cgroup versions' layouts. +""" + +from __future__ import annotations + +import pytest + +from microcosm.build import host_resources + +GIB = 2**30 + + +def _write(root, relative: str, text: str) -> None: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text + "\n") + + +def test_usable_cores_are_the_cpus_the_process_may_use(tmp_path) -> None: + assert host_resources.usable_cores(cpu_count=10, cgroup_root=tmp_path) == 10 + assert host_resources.usable_cores() >= 1 + + +@pytest.mark.parametrize( + ("files", "expected"), + [ + # cgroup v2: no quota, a fractional quota rounded up, a quota above + # the CPUs the process may use. + ({"cpu.max": "max 100000"}, 10), + ({"cpu.max": "150000 100000"}, 2), + ({"cpu.max": "1600000 100000"}, 10), + # cgroup v1: no quota, a quota of 2.5 CPUs. + ({"cpu/cpu.cfs_quota_us": "-1", "cpu/cpu.cfs_period_us": "100000"}, 10), + ({"cpu/cpu.cfs_quota_us": "250000", "cpu/cpu.cfs_period_us": "100000"}, 3), + # A file that cannot be read as a quota sets none. + ({"cpu.max": "unexpected"}, 10), + ({"cpu/cpu.cfs_quota_us": "100000", "cpu/cpu.cfs_period_us": "0"}, 10), + ], +) +def test_a_cgroup_cpu_quota_limits_the_usable_cores(tmp_path, files, expected) -> None: + for relative, text in files.items(): + _write(tmp_path, relative, text) + assert host_resources.usable_cores(cpu_count=10, cgroup_root=tmp_path) == expected + + +def test_total_memory_is_the_machines_memory(tmp_path) -> None: + assert ( + host_resources.total_memory_bytes( + physical_memory_bytes=32 * GIB, cgroup_root=tmp_path + ) + == 32 * GIB + ) + assert host_resources.total_memory_bytes() > 0 + + +@pytest.mark.parametrize( + ("files", "expected"), + [ + ({"memory.max": "max"}, 32 * GIB), + ({"memory.max": str(8 * GIB)}, 8 * GIB), + ({"memory.max": str(64 * GIB)}, 32 * GIB), + # cgroup v1 reports "no limit" as a number near 2**63. + ({"memory/memory.limit_in_bytes": str(2**63 - 4096)}, 32 * GIB), + ({"memory/memory.limit_in_bytes": str(12 * GIB)}, 12 * GIB), + ({"memory.max": "unexpected"}, 32 * GIB), + ], +) +def test_a_cgroup_memory_limit_limits_the_total_memory( + tmp_path, files, expected +) -> None: + for relative, text in files.items(): + _write(tmp_path, relative, text) + assert ( + host_resources.total_memory_bytes( + physical_memory_bytes=32 * GIB, cgroup_root=tmp_path + ) + == expected + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index c95b3267a6..49d7ce481e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -7295,6 +7295,9 @@ def close(self): captured["scorer_closed"] = True monkeypatch.setattr(builder, "_HouseholdBatchedPostExportScorer", WrittenH5Scorer) + # The stand-in is the serial scorer; certification uses it only when the + # operator asks for serial scoring (pooled scoring is the default). + monkeypatch.setenv("MICROCOSM_POST_EXPORT_WORKERS", "serial") read_population_structure = builder.population_structure_holdout_from_h5 def population_structure_from_h5(dataset_path, **kwargs): @@ -21048,7 +21051,7 @@ def test_certify_main_refuses_another_commit_and_a_certified_build( monkeypatch.setattr( builder, "_certify_us_build", - lambda record, *, certification, telemetry: certified.append( + lambda record, *, certification, telemetry, **options: certified.append( (record, certification, telemetry) ), ) @@ -21149,7 +21152,9 @@ def test_certification_chooses_the_tier_of_a_failed_build( monkeypatch.setattr( builder, "_certify_us_build", - lambda record, *, certification, telemetry: certified.append(certification), + lambda record, *, certification, telemetry, **options: certified.append( + certification + ), ) with pytest.raises( @@ -21240,7 +21245,9 @@ def test_an_evidence_certification_refuses_what_no_owner_can_ship( monkeypatch.setattr( builder, "_certify_us_build", - lambda record, *, certification, telemetry: certified.append(certification), + lambda record, *, certification, telemetry, **options: certified.append( + certification + ), ) owners = tmp_path / "owners.json" owners.write_text( @@ -21300,7 +21307,9 @@ def test_no_tier_certifies_a_written_h5_that_failed_its_own_checks( monkeypatch.setattr( builder, "_certify_us_build", - lambda record, *, certification, telemetry: certified.append(certification), + lambda record, *, certification, telemetry, **options: certified.append( + certification + ), ) owners = tmp_path / "owners.json" owners.write_text(json.dumps({"Export audit failed:": "PolicyEngine/microcosm#1"})) @@ -21337,7 +21346,7 @@ def test_certify_main_refuses_a_build_that_wrote_failed_weight_evidence( monkeypatch.setattr( builder, "_certify_us_build", - lambda record, *, certification, telemetry: certified.append(record), + lambda record, *, certification, telemetry, **options: certified.append(record), ) build_dir = path.parent / builder.US_BUILD_FILES_DIRECTORY (build_dir / builder.FINAL_HOUSEHOLD_WEIGHTS_FILENAME).write_bytes(b"w") @@ -21377,7 +21386,7 @@ def test_certify_main_marks_its_staging_run_failed(tmp_path: Path, monkeypatch) seen = _stub_certify_telemetry(builder, monkeypatch) error = RuntimeError("Release gates failed: the smoke failed") - def failing_certification(record, *, certification, telemetry): + def failing_certification(record, *, certification, telemetry, **options): raise error monkeypatch.setattr(builder, "_certify_us_build", failing_certification) @@ -21830,7 +21839,7 @@ def test_certify_main_refuses_packages_other_than_the_builds( monkeypatch.setattr( builder, "_certify_us_build", - lambda record, *, certification, telemetry: certified.append(record), + lambda record, *, certification, telemetry, **options: certified.append(record), ) built_with = payload["runtime"]["policyengine-us"] monkeypatch.setattr( @@ -21950,7 +21959,9 @@ def test_certification_and_the_build_refuse_another_checkouts_packages( monkeypatch.setattr( builder, "_certify_us_build", - lambda record, *, certification, telemetry: certified.append(certification), + lambda record, *, certification, telemetry, **options: certified.append( + certification + ), ) with pytest.raises(SystemExit, match="Refusing to certify a build with packages"): builder.certify_main([str(path.parent)]) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py index dd82f0ffac..d40a1a83fd 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py @@ -178,3 +178,117 @@ def test_a_worker_finds_a_loaded_release_tool_or_loads_it_once( if getattr(module, "__file__", None) in (str(tool), str(other)) ]: sys.modules.pop(name, None) + + +# --------------------------------------------------------------------------- +# The default worker settings (tracker decision 1.4 · 6, approved 27 November) +# --------------------------------------------------------------------------- + +GIB = 2**30 +VARIABLE = "MICROCOSM_POST_EXPORT_WORKERS" + + +def _plan(pool_module, memory, cores, value=None): + environment = {} if value is None else {VARIABLE: value} + return pool_module.plan_post_export_workers( + environment, total_memory_bytes=int(memory), usable_cores=cores + ) + + +@pytest.mark.parametrize( + ("memory", "cores", "workers", "cap"), + [ + # 1.4 · 6's table: the 32 GiB, 6-core design target, Anthony's Mac, + # the build Mac, and a 16 GiB machine. + (32 * GIB, 6, 4, 21 * GIB // 4), + (32 * GIB, 10, 4, 21 * GIB // 4), + (128 * GIB, 18, 17, 93 * GIB // 17), + (16 * GIB, 8, 1, 9 * GIB), + # The memory term reaches 4 from 30.67 GiB, so a Linux host's 31.3 + # GiB keeps 4; a container given 32 * 10**9 bytes (29.8 GiB) gets 3. + (int(31.3 * GIB), 10, 4, (3 * int(31.3 * GIB) // 4 - 3 * GIB) // 4), + (32 * 10**9, 10, 3, (3 * 32 * 10**9 // 4 - 3 * GIB) // 3), + # The cores term: usable cores less one, at least one. + (32 * GIB, 3, 2, 21 * GIB // 2), + (32 * GIB, 1, 1, 21 * GIB), + ], +) +def test_the_formula_picks_the_workers_and_each_ones_cap( + pool_module, memory, cores, workers, cap +) -> None: + for value in (None, "", "auto"): + plan = _plan(pool_module, memory, cores, value) + assert not plan.serial + assert plan.workers == workers + assert plan.chosen_by == "formula" + assert plan.memory_cap_bytes == max(5 * GIB, cap) + assert plan.max_units_per_worker == 2 + assert plan.budget_bytes == int(memory) * 3 // 4 + assert plan.planned_peak_bytes == 3 * GIB + workers * 5 * GIB + settings = plan.pool_settings() + assert settings.workers == workers + assert settings.memory_cap_bytes == plan.memory_cap_bytes + assert settings.max_units_per_worker == 2 + # Workers inherit the parent's thread variables (1.4 · 6, part 5). + assert settings.worker_environment is None + assert (settings.max_attempts, settings.max_units_ahead) == (2, None) + + +def test_a_machine_too_small_for_one_worker_is_refused_unless_told( + pool_module, +) -> None: + """Under about 10.7 GiB, 75% of memory less this process's 3 GiB leaves no + room for one 5 GiB worker: refused, before anything is loaded, unless the + operator names a count or serial scoring.""" + for value in (None, "auto"): + with pytest.raises(pool_module.PostExportWorkersError) as refused: + _plan(pool_module, 10 * GIB, 8, value) + message = str(refused.value) + assert "post-export scoring" in message + assert "8.00 GiB" in message and "7.50 GiB" in message + assert VARIABLE in message and "serial" in message + assert _plan(pool_module, 10.7 * GIB, 8).workers == 1 + explicit = _plan(pool_module, 10 * GIB, 8, "2") + assert (explicit.workers, explicit.chosen_by) == (2, f"{VARIABLE}=2") + assert explicit.memory_cap_bytes == 5 * GIB + assert explicit.planned_peak_bytes > explicit.budget_bytes + assert "above" in explicit.describe() + assert _plan(pool_module, 10 * GIB, 8, "serial").serial + + +def test_an_operator_names_a_count_or_serial_scoring(pool_module) -> None: + one = _plan(pool_module, 32 * GIB, 10, "1") + # One pool worker, a separate process with the cap and replacement. + assert (one.serial, one.workers) == (False, 1) + assert one.memory_cap_bytes == 21 * GIB + many = _plan(pool_module, 32 * GIB, 10, "12") + assert many.workers == 12 and many.memory_cap_bytes == 5 * GIB + serial = _plan(pool_module, 32 * GIB, 10, "serial") + assert serial.serial and serial.workers is None + assert serial.chosen_by == f"{VARIABLE}=serial" + assert serial.pool_settings() is None + assert "in this process" in serial.describe() + + +@pytest.mark.parametrize("value", ["0", "-1", "four", " 4", "4.0", "+4", "Serial"]) +def test_any_other_setting_is_refused(pool_module, value) -> None: + with pytest.raises(pool_module.PostExportWorkersError, match=VARIABLE): + _plan(pool_module, 32 * GIB, 10, value) + + +def test_the_plan_says_what_it_chose_and_why(pool_module) -> None: + plan = _plan(pool_module, 32 * GIB, 10) + assert plan.record() == { + "mode": "pooled", + "chosen_by": "formula", + "workers": 4, + "total_memory_bytes": 32 * GIB, + "usable_cores": 10, + "budget_bytes": 24 * GIB, + "planned_peak_bytes": 23 * GIB, + "memory_cap_bytes": 21 * GIB // 4, + "max_units_per_worker": 2, + } + line = plan.describe() + for text in ("4 pool workers", "formula", "23.00 GiB", "24.00 GiB", "5.25 GiB"): + assert text in line, text diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index 01e866a1d0..d1fc4d5bbd 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -274,6 +274,7 @@ def run(workers: int): "max_units_ahead": None, "worker_environment_variables": [], "units": {"baseline": workers, "reform": reform_units}, + "resources": None, } assert report["units_completed"] == workers + reform_units assert report["failed_attempts"] == [] @@ -689,3 +690,120 @@ def test_the_batch_ranges_cover_every_batch_once(builder) -> None: assert len(split) == min(ranges, n_batches) sizes = {len(batches) for batches in split} assert max(sizes) - min(sizes) <= 1 + + +# --------------------------------------------------------------------------- +# Pooled scoring is certification's default (1.4 · 6's settings, approved by +# Anthony on 27 November) +# --------------------------------------------------------------------------- + +GIB = 2**30 +WORKERS_VARIABLE = "MICROCOSM_POST_EXPORT_WORKERS" + + +def test_the_environment_chooses_pooled_or_serial_scoring(builder, capsys) -> None: + resources = {"total_memory_bytes": 32 * GIB, "usable_cores": 10} + pooling = builder._post_export_pooling_from_environment({}, **resources) + assert pooling.chosen_by == "formula" + settings = pooling.settings + assert (settings.workers, settings.max_units_per_worker) == (4, 2) + assert settings.memory_cap_bytes == 21 * GIB // 4 + assert settings.worker_environment is None + assert pooling.resources["planned_peak_bytes"] == 23 * GIB + assert "4 pool workers" in capsys.readouterr().out + named = builder._post_export_pooling_from_environment( + {WORKERS_VARIABLE: "6"}, **resources + ) + assert (named.settings.workers, named.chosen_by) == (6, f"{WORKERS_VARIABLE}=6") + assert ( + builder._post_export_pooling_from_environment( + {WORKERS_VARIABLE: "serial"}, **resources + ) + is None + ) + assert "in this process" in capsys.readouterr().out + for environment, machine in ( + ({WORKERS_VARIABLE: "lots"}, resources), + ({}, {"total_memory_bytes": 8 * GIB, "usable_cores": 10}), + ): + with pytest.raises(SystemExit, match=WORKERS_VARIABLE): + builder._post_export_pooling_from_environment(environment, **machine) + + +def test_the_execution_record_holds_the_plan_it_ran( + builder, + pooled_reforms, + tmp_path, +) -> None: + plan = _fixture_plan(builder, _fixture_consumer(lambda total: [])) + pooling = builder._PostExportPooling( + WorkerPoolSettings(workers=2), + chosen_by="formula", + microsimulation_cls=FakeMicrosimulation, + dataset_from_frame=identity_dataset, + reform_builder=build_fake_reform, + resources={"usable_cores": 3}, + ) + scorer = builder._PooledPostExportScorer( + _written_h5(tmp_path), + maximum_microsim_batch_size=BATCH_SIZE, + consumer_requests=plan.consumer_requests, + pooling=pooling, + load_frame=_load(_nested_frame()), + ) + scorer.close() + record = scorer.execution_record() + assert (record["chosen_by"], record["resources"]) == ( + "formula", + {"usable_cores": 3}, + ) + + +def test_certification_chooses_its_workers_before_it_places_the_build( + builder, +) -> None: + """A bad setting or a machine too small for one worker stops + certification before it copies the build's files or loads the H5, and + the pool settings reach the post-export scorer.""" + import ast + import inspect + + source = inspect.getsource(builder._certify_main_with_close_out) + chosen = source.index( + "post_export_pooling = _post_export_pooling_from_environment()" + ) + assert chosen < source.index("_place_build_for_certification(") + calls = [ + node + for node in ast.walk(ast.parse(source)) + if isinstance(node, ast.Call) + and getattr(node.func, "id", None) == "_certify_us_build" + ] + assert [ast.unparse(call) for call in calls] == [ + "_certify_us_build(record, certification=certification, " + "telemetry=telemetry, post_export_pooling=post_export_pooling)" + ] + + +def test_the_probe_command_scores_as_certification_does(builder) -> None: + """The export probe's command reads the same setting, before it loads + the export, so it times pooled scoring by default.""" + import ast + import inspect + + from test_support.microcosm_build.us_export_subsample import _load_tool + + probe_tool = _load_tool("probe_us_post_export", "probe_us_post_export.py") + source = inspect.getsource(probe_tool.main) + chosen = source.index( + "post_export_pooling = load_builder()._post_export_pooling_from_environment()" + ) + assert chosen < source.index("report = probe_export(") + (call,) = [ + node + for node in ast.walk(ast.parse(source)) + if isinstance(node, ast.Call) + and getattr(node.func, "id", None) == "probe_export" + ] + keywords = {keyword.arg: ast.unparse(keyword.value) for keyword in call.keywords} + assert keywords["post_export_pooling"] == "post_export_pooling" From ee45d49f231c553fb9c14c96acd19bc26ae81a06 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:15:31 +0400 Subject: [PATCH 04/26] Make pooled post-export scoring certification's default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tracker task 1.4 · 7, with the worker settings 1.4 · 6 recommends, which Anthony approved on 27 November: - microcosm.build.host_resources reads the cores this process may use (os.process_cpu_count(), limited by a cgroup v1 or v2 CPU quota) and the machine's memory (limited by a cgroup memory limit); - plan_post_export_workers chooses min(usable cores - 1, floor((0.75 * memory - 3 GiB) / 5 GiB)) workers, each capped at max(5 GiB, (0.75 * memory - 3 GiB) / workers) and replaced after 2 units, with inherited thread settings. MICROCOSM_POST_EXPORT_WORKERS takes auto, a positive count or serial; anything else, or a machine too small for one worker without a named count, is refused; - certification reads it before it places the build and passes the pool to _certify_us_build, printing the workers, the planned peak beside the budget and the cap; the export probe's command reads it before it loads the export; - the manifests' execution record holds the plan's readings. Co-Authored-By: Claude Opus 5.5 --- .../us-pooled-post-export-scoring.changed.md | 2 +- docs/agent-guide.md | 4 +- docs/us-release-build-rule.md | 36 ++- .../src/microcosm/build/host_resources.py | 129 ++++++++++ .../build/us_runtime/post_export_pool.py | 233 ++++++++++++++++++ tools/build_us_fiscal_refresh_release.py | 55 ++++- tools/probe_us_post_export.py | 8 +- 7 files changed, 455 insertions(+), 12 deletions(-) create mode 100644 packages/microcosm-build/src/microcosm/build/host_resources.py diff --git a/changelog.d/us-pooled-post-export-scoring.changed.md b/changelog.d/us-pooled-post-export-scoring.changed.md index 12660d8fa6..e9ef8bcbc4 100644 --- a/changelog.d/us-pooled-post-export-scoring.changed.md +++ b/changelog.d/us-pooled-post-export-scoring.changed.md @@ -1 +1 @@ -US post-export scoring can run in the shared worker pool (`_PooledPostExportScorer`): the merged baseline pass is split into one range of household batches per worker, each reformed simulation's recorded passes are one unit, and each post-export stage then runs in the certifying process over the results, refusing any request its engine-free dry run did not record. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's merged baseline pass instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan (one shared baseline pass, as certification runs), can score in the pool and writes each worker pass's time and memory to `passes.jsonl`; its household row map reads one batch file at a time. +US certification scores post-export stages in the shared worker pool by default (`_PooledPostExportScorer`), with tracker decision 1.4 · 6's settings: `MICROCOSM_POST_EXPORT_WORKERS` unset or `auto` starts at most min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers and refuses, before the build is placed, a machine with no room for one; a positive number starts that many, and `serial` scores in the certifying process as before; each worker is replaced after 2 units and capped at max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers). In the pool, the merged baseline pass is split into one range of household batches per worker, each reformed simulation's recorded passes are one unit, and each post-export stage then runs in the certifying process over the results, refusing any request its engine-free dry run did not record. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's merged baseline pass instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan (one shared baseline pass, as certification runs), can score in the pool and writes each worker pass's time and memory to `passes.jsonl`; its household row map reads one batch file at a time. diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 1c69fd253f..5f5a038719 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -433,7 +433,9 @@ tier's `releases//`, runs only `microcosm-publish-release-build --preflight-only`, which checks the build offline, and leaves publication to Max. -The US fiscal-refresh builder scores its written H5 in household batches. +The US fiscal-refresh builder scores its written H5 in household batches, +in the shared worker pool unless `MICROCOSM_POST_EXPORT_WORKERS=serial` +(see [the release build rule](us-release-build-rule.md#post-export-scoring)). Alongside its out-of-sample reports, it writes `us_ssi_social_security_holdout.json`: the household-weighted share of SSI recipients also receiving Social Security at ages 18–64 and 65+, compared with diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index ce4816d844..c56d706d99 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -501,9 +501,32 @@ one Microsimulation over the whole file. Nothing records the descriptors in a file; pooled scoring (next item) and the guard sweep below rebuild each reform from its descriptor in the worker that scores it. -- With pooled scoring (`_PooledPostExportScorer`) the scoring runs in the - shared worker pool (`microcosm.build.worker_pool`) and the stages run - afterwards in the certifying process, over the results: +- Certification scores in the shared worker pool by default + (`_PooledPostExportScorer`, `microcosm.build.worker_pool`), and the stages + run afterwards in the certifying process, over the results. The worker + settings are tracker decision 1.4 · 6's, until task 2.6 · 2's planner + replaces them (`plan_post_export_workers` in + `microcosm.build.us_runtime.post_export_pool`): + - `MICROCOSM_POST_EXPORT_WORKERS` unset, blank or `auto`: at most + min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers, at + least one. Usable cores are the CPUs the process may run on, limited by a + cgroup CPU quota; memory is the machine's, limited by a cgroup memory + limit (`microcosm.build.host_resources`). 0.75 is decision 1.1 · 2's + budget, 3 GiB the certifying process's planned peak and 5 GiB one + worker's. On a machine under about 10.7 GiB that leaves no room for one + worker, and certification refuses before it places the build or loads + the H5. + - A positive whole number: that many workers (`1` is one worker, a process + of its own), whatever the formula gives; `serial`: every pass in the + certifying process, as before. Anything else stops certification at the + same point. + - Each worker is replaced after 2 units and capped at + max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers) of memory footprint; a + worker over its cap is killed and its unit runs again in a fresh worker. + No more workers start than a pool run has units. + - Certification prints the plan: the workers, the planned peak beside the + budget and each worker's cap. `tools/probe_us_post_export.py` reads the + same setting the same way. - The pool runs twice. First the shared baseline pass, split into one range of batches per worker. Then one unit per reformed simulation, holding all of that simulation's recorded passes over every batch, in the order the @@ -542,9 +565,10 @@ one Microsimulation over the whole file. tool; that is the import the worker needs, so it runs once per worker start. - The manifests' `post_export_scoring` block records how scoring ran under - `execution`: `{"mode": "serial"}`, or the pool's settings, unit counts and - report (worker starts, failed attempts, peak worker memory). That record is - run metadata, outside every output comparison (decision 1.1 · 1). + `execution`: `{"mode": "serial"}`, or the pool's settings, how the worker + count was chosen, the plan's memory and core readings, unit counts and the + pool's report (worker starts, failed attempts, peak worker memory). That + record is run metadata, outside every output comparison (decision 1.1 · 1). - Each batch engine keeps policyengine-us's projection of the release year to its last CPI-U year (2035), because the plans request keys in later years (reform validation reaches past 2025). The build's own simulations hold diff --git a/packages/microcosm-build/src/microcosm/build/host_resources.py b/packages/microcosm-build/src/microcosm/build/host_resources.py new file mode 100644 index 0000000000..36b0b20865 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/host_resources.py @@ -0,0 +1,129 @@ +"""How much memory and how many CPU cores this process may use. + +Builds size their worker pools from the machine they run on (decision 1.1 · 2: +a budget of 75% of memory, and only the cores the process may use). These two +readings are what that sizing starts from: + +- :func:`usable_cores`: the CPUs this process may run on + (``os.process_cpu_count()``, which follows the CPU affinity mask, so + ``taskset`` and container cpusets, and ``PYTHON_CPU_COUNT``), limited by a + cgroup CPU quota rounded up (cgroup v2 ``cpu.max``, v1 ``cpu.cfs_quota_us`` + over ``cpu.cfs_period_us``). These are ``joblib.cpu_count()``'s rules + without ``LOKY_MAX_CPU_COUNT``, which the release tool fills with its + thread count. +- :func:`total_memory_bytes`: the machine's physical memory, limited by a + cgroup memory limit (v2 ``memory.max``, v1 ``memory.limit_in_bytes``), as a + container such as Modal's is limited. + +The cgroup files are read from ``/sys/fs/cgroup`` on Linux only; a file that is +absent or cannot be read as a limit sets none. Pooled post-export scoring +(tracker task 1.4 · 7) uses these; task 1.8 · 1 adds the budget options on top. +""" + +from __future__ import annotations + +import math +import os +import sys +from pathlib import Path + +__all__ = ["total_memory_bytes", "usable_cores"] + +_DEFAULT_CGROUP_ROOT = Path("/sys/fs/cgroup") + + +def _cgroup_root(cgroup_root: Path | None) -> Path | None: + if cgroup_root is not None: + return Path(cgroup_root) + if sys.platform.startswith("linux"): + return _DEFAULT_CGROUP_ROOT + return None + + +def _read(path: Path) -> str | None: + try: + return path.read_text().strip() + except OSError: + return None + + +def _cpu_quota(root: Path) -> float | None: + """The cgroup CPU quota in CPUs, or ``None`` for none.""" + text = _read(root / "cpu.max") + if text is not None: + fields = text.split() + if len(fields) == 2 and fields[0] != "max": + try: + quota, period = int(fields[0]), int(fields[1]) + except ValueError: + return None + if quota > 0 and period > 0: + return quota / period + return None + quota_text = _read(root / "cpu" / "cpu.cfs_quota_us") + period_text = _read(root / "cpu" / "cpu.cfs_period_us") + if quota_text is None or period_text is None: + return None + try: + quota, period = int(quota_text), int(period_text) + except ValueError: + return None + if quota > 0 and period > 0: + return quota / period + return None + + +def usable_cores( + *, cpu_count: int | None = None, cgroup_root: Path | None = None +) -> int: + """The CPU cores this process may use, at least one. + + ``cpu_count`` replaces ``os.process_cpu_count()``, and ``cgroup_root`` the + cgroup directory, for tests. + """ + if cpu_count is None: + cpu_count = os.process_cpu_count() or 1 + cores = max(1, int(cpu_count)) + root = _cgroup_root(cgroup_root) + if root is not None: + quota = _cpu_quota(root) + if quota is not None: + cores = min(cores, max(1, math.ceil(quota))) + return cores + + +def _memory_limit(root: Path) -> int | None: + """The cgroup memory limit in bytes, or ``None`` for none.""" + for relative in ("memory.max", "memory/memory.limit_in_bytes"): + text = _read(root / relative) + if text is None: + continue + try: + limit = int(text) + except ValueError: + # cgroup v2 writes "max" for no limit. + return None + return limit if limit > 0 else None + return None + + +def total_memory_bytes( + *, physical_memory_bytes: int | None = None, cgroup_root: Path | None = None +) -> int: + """The memory this process's machine or container has, in bytes. + + ``physical_memory_bytes`` replaces the machine's physical memory + (``SC_PHYS_PAGES`` pages of ``SC_PAGE_SIZE`` bytes, the same as + ``hw.memsize`` on macOS), and ``cgroup_root`` the cgroup directory, for + tests. A cgroup v1 limit of "no limit" is a number near ``2**63``, which + the physical memory then bounds. + """ + if physical_memory_bytes is None: + physical_memory_bytes = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") + total = int(physical_memory_bytes) + root = _cgroup_root(cgroup_root) + if root is not None: + limit = _memory_limit(root) + if limit is not None: + total = min(total, limit) + return total diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py index 4aab8dda80..3a81c70c5c 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py @@ -31,30 +31,47 @@ (:func:`start_post_export_worker`, :func:`score_post_export_unit`) live here for the same reason; the worker finds the release tool, or loads it from its file, when it starts (:func:`release_tool`). + +:func:`plan_post_export_workers` chooses how many workers pooled scoring +starts and the limits each runs under, from the machine and the operator's +``MICROCOSM_POST_EXPORT_WORKERS`` (tracker decision 1.4 · 6, approved by +Anthony on 27 November 2026, until task 2.6 · 2's planner replaces it). """ from __future__ import annotations import builtins import importlib.util +import os import sys import traceback +from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path from typing import Any +from microcosm.build import host_resources from microcosm.build.us_runtime.post_export_requests import ( PostExportReform, check_post_export_reform, ) +from microcosm.build.worker_pool import WorkerPoolSettings __all__ = [ + "MEMORY_BUDGET_FRACTION", + "PARENT_PEAK_BYTES", + "POST_EXPORT_WORKERS_VARIABLE", + "UNITS_PER_WORKER", + "WORKER_PEAK_BYTES", "PostExportPass", "PostExportPassTiming", "PostExportPassValues", "PostExportUnit", "PostExportUnitFailure", "PostExportUnitResult", + "PostExportWorkerPlan", + "PostExportWorkersError", + "plan_post_export_workers", "release_tool", "score_post_export_unit", "start_post_export_worker", @@ -370,3 +387,219 @@ def start_post_export_worker(module_name: str, path: str, *arguments: Any): def score_post_export_unit(worker, unit: PostExportUnit) -> PostExportUnitResult: """The pool's unit function: score ``unit`` (``worker.score``).""" return worker.score(unit) + + +# --------------------------------------------------------------------------- +# How many workers, and their limits (tracker decision 1.4 · 6) +# --------------------------------------------------------------------------- + +_GIB = 2**30 + +#: The variable an operator sets: unset, blank or ``auto`` for the formula, a +#: positive whole number for that many pool workers, or ``serial`` to score in +#: the certifying process alone. +POST_EXPORT_WORKERS_VARIABLE = "MICROCOSM_POST_EXPORT_WORKERS" + +#: The share of the machine's memory a build may plan to use (decision 1.1 · 2). +MEMORY_BUDGET_FRACTION = 0.75 + +#: The certifying process's planned peak while workers score: the release +#: tool's imports (about 1.1-1.2 GiB) and the baseline arrays it holds (up to +#: about 1.1 GiB at national size). +PARENT_PEAK_BYTES = 3 * _GIB + +#: One worker's planned peak over its replacement interval (1.4 · 6's one-batch +#: check: about 3.5-4.7 GiB over two reform passes). +WORKER_PEAK_BYTES = 5 * _GIB + +#: Units a worker runs before a fresh worker takes its place. A reform unit is +#: one reformed simulation's passes (one pass for every shipped consumer). +UNITS_PER_WORKER = 2 + + +class PostExportWorkersError(ValueError): + """``MICROCOSM_POST_EXPORT_WORKERS`` is not a setting, or the machine is + too small for one worker and the operator did not say to run anyway.""" + + +def _gib(count: int | float) -> str: + return f"{count / _GIB:.2f} GiB" + + +@dataclass(frozen=True) +class PostExportWorkerPlan: + """How post-export scoring runs on this machine. + + Attributes: + serial: Score in the certifying process alone (the operator's + ``serial``). + workers: The most pool workers; ``None`` when serial. The scorer + starts no more than a pool run has units. + chosen_by: ``"formula"``, or ``MICROCOSM_POST_EXPORT_WORKERS=``. + total_memory_bytes: The machine's or container's memory. + usable_cores: The cores this process may use. + memory_cap_bytes: Each worker's memory-footprint cap; ``None`` when + serial. + max_units_per_worker: Units a worker runs before it is replaced; + ``None`` when serial. + """ + + serial: bool + workers: int | None + chosen_by: str + total_memory_bytes: int + usable_cores: int + memory_cap_bytes: int | None + max_units_per_worker: int | None + + @property + def budget_bytes(self) -> int: + """75% of the memory (decision 1.1 · 2), in bytes.""" + return self.total_memory_bytes * 3 // 4 + + @property + def planned_peak_bytes(self) -> int | None: + """This process's planned peak plus every worker's.""" + if self.workers is None: + return None + return PARENT_PEAK_BYTES + self.workers * WORKER_PEAK_BYTES + + def pool_settings(self) -> WorkerPoolSettings | None: + """The shared pool's settings; ``None`` when serial. Workers inherit + this process's environment, thread variables included.""" + if self.serial: + return None + return WorkerPoolSettings( + workers=self.workers, + memory_cap_bytes=self.memory_cap_bytes, + max_units_per_worker=self.max_units_per_worker, + ) + + def record(self) -> dict[str, object]: + """The plan as run metadata, for the manifests' scoring block.""" + return { + "mode": "serial" if self.serial else "pooled", + "chosen_by": self.chosen_by, + "workers": self.workers, + "total_memory_bytes": self.total_memory_bytes, + "usable_cores": self.usable_cores, + "budget_bytes": self.budget_bytes, + "planned_peak_bytes": self.planned_peak_bytes, + "memory_cap_bytes": self.memory_cap_bytes, + "max_units_per_worker": self.max_units_per_worker, + } + + def describe(self) -> str: + """The line certification and the export probe print.""" + machine = ( + f"{self.usable_cores} usable core(s), {_gib(self.total_memory_bytes)} " + "of memory" + ) + if self.serial: + return ( + f"Post-export scoring runs in this process alone ({self.chosen_by}; " + f"{machine})." + ) + planned, budget = self.planned_peak_bytes, self.budget_bytes + against = "above" if planned > budget else "within" + return ( + f"Post-export scoring: up to {self.workers} pool worker" + f"{'' if self.workers == 1 else 's'} ({self.chosen_by}; {machine}). " + f"Planned peak {_gib(planned)} ({_gib(PARENT_PEAK_BYTES)} for this " + f"process, {_gib(WORKER_PEAK_BYTES)} per worker), {against} the " + f"budget of {_gib(budget)} (75% of memory). Each worker is capped at " + f"{_gib(self.memory_cap_bytes)} and replaced after " + f"{self.max_units_per_worker} units." + ) + + +def _requested_workers(value: str) -> int | str | None: + """``None`` for the formula, ``"serial"``, or a count.""" + if value in ("", "auto"): + return None + if value == "serial": + return "serial" + if value.isascii() and value.isdigit(): + try: + count = int(value) + except ValueError: # longer than int() will parse + count = 0 + if count > 0: + return count + raise PostExportWorkersError( + f"{POST_EXPORT_WORKERS_VARIABLE} must be auto, serial or a positive whole " + f"number of post-export scoring workers, got {value!r}." + ) + + +def plan_post_export_workers( + environment: Mapping[str, str] = os.environ, + *, + total_memory_bytes: int | None = None, + usable_cores: int | None = None, +) -> PostExportWorkerPlan: + """Choose the post-export pool's workers and limits for this machine. + + - Workers: ``min(usable cores - 1, floor((0.75 * memory - 3 GiB) / 5 GiB))``, + at least one, unless ``MICROCOSM_POST_EXPORT_WORKERS`` names a count + (``1`` is one pool worker, a process of its own) or ``serial``. + - A memory term below one means no room for this process and one worker + within the budget, which is refused unless the variable names a count + or ``serial``. + - Each worker is capped at ``max(5 GiB, (0.75 * memory - 3 GiB) / + workers)`` of memory footprint and replaced after + :data:`UNITS_PER_WORKER` units; it inherits this process's thread + variables. + + ``total_memory_bytes`` and ``usable_cores`` replace the machine's readings + (:mod:`microcosm.build.host_resources`), for tests. + + Raises: + PostExportWorkersError: For a value that is not a setting, or a + machine too small for one worker. + """ + requested = _requested_workers(environment.get(POST_EXPORT_WORKERS_VARIABLE, "")) + memory = int( + total_memory_bytes + if total_memory_bytes is not None + else host_resources.total_memory_bytes() + ) + cores = int( + usable_cores if usable_cores is not None else host_resources.usable_cores() + ) + room = memory * 3 // 4 - PARENT_PEAK_BYTES + if requested == "serial": + return PostExportWorkerPlan( + serial=True, + workers=None, + chosen_by=f"{POST_EXPORT_WORKERS_VARIABLE}=serial", + total_memory_bytes=memory, + usable_cores=cores, + memory_cap_bytes=None, + max_units_per_worker=None, + ) + if requested is None: + memory_term = room // WORKER_PEAK_BYTES + if memory_term < 1: + raise PostExportWorkersError( + f"There is no room for post-export scoring on this machine: " + f"this process and one pool worker need " + f"{_gib(PARENT_PEAK_BYTES + WORKER_PEAK_BYTES)} within the memory " + f"budget, 75% of {_gib(memory)}, which is {_gib(memory * 3 // 4)}. " + f"Set {POST_EXPORT_WORKERS_VARIABLE} to a number of workers, or " + "to serial to score in this process alone, to run it anyway." + ) + workers = min(max(1, cores - 1), memory_term) + chosen_by = "formula" + else: + workers = requested + chosen_by = f"{POST_EXPORT_WORKERS_VARIABLE}={requested}" + return PostExportWorkerPlan( + serial=False, + workers=workers, + chosen_by=chosen_by, + total_memory_bytes=memory, + usable_cores=cores, + memory_cap_bytes=max(WORKER_PEAK_BYTES, room // workers), + max_units_per_worker=UNITS_PER_WORKER, + ) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index b0af04ad6d..25229b5c8c 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -373,6 +373,8 @@ PostExportUnit, PostExportUnitFailure, PostExportUnitResult, + PostExportWorkersError, + plan_post_export_workers, score_post_export_unit, start_post_export_worker, ) @@ -6978,8 +6980,11 @@ class _PostExportPooling: replace, in every worker and for the scorer's own checks, the engine, the batch dataset and the reform builder; each must be importable by name in a spawned worker. ``None`` keeps policyengine-us's ``Microsimulation``, - :func:`_post_export_dataset` and ``build_post_export_reform``. (A plain - class, for the reason :class:`_PostExportScoringPlan` gives.) + :func:`_post_export_dataset` and ``build_post_export_reform``. + ``resources`` is the record of the plan the settings came from (the + machine's memory and cores, the budget and the planned peak), which the + execution record carries. (A plain class, for the reason + :class:`_PostExportScoringPlan` gives.) """ def __init__( @@ -6990,6 +6995,7 @@ def __init__( microsimulation_cls=None, dataset_from_frame=None, reform_builder=None, + resources: Mapping[str, object] | None = None, ) -> None: if not isinstance(settings, WorkerPoolSettings): raise TypeError("Pooled post-export scoring needs WorkerPoolSettings.") @@ -7000,6 +7006,40 @@ def __init__( self.microsimulation_cls = microsimulation_cls self.dataset_from_frame = dataset_from_frame self.reform_builder = reform_builder + self.resources = None if resources is None else dict(resources) + + +def _post_export_pooling_from_environment( + environment: Mapping[str, str] = os.environ, + *, + total_memory_bytes: int | None = None, + usable_cores: int | None = None, +) -> _PostExportPooling | None: + """The post-export pool for this machine and ``MICROCOSM_POST_EXPORT_WORKERS``. + + Pooled scoring is the default, with the worker count and limits of + ``plan_post_export_workers`` (tracker decision 1.4 · 6); ``serial`` returns + ``None``, which scores in this process. Prints the plan: the workers, the + planned peak beside the memory budget, each worker's cap. A value that is + not a setting, or a machine too small for one worker, stops the command, + which certification and the export probe do before they load the H5. + ``total_memory_bytes`` and ``usable_cores`` replace the machine's + readings, for tests. + """ + try: + plan = plan_post_export_workers( + environment, + total_memory_bytes=total_memory_bytes, + usable_cores=usable_cores, + ) + except PostExportWorkersError as error: + raise SystemExit(str(error)) from None + print(plan.describe(), flush=True) + if plan.serial: + return None + return _PostExportPooling( + plan.pool_settings(), chosen_by=plan.chosen_by, resources=plan.record() + ) def _post_export_worker_settings( @@ -7528,6 +7568,7 @@ def execution_record(self) -> dict[str, object]: "max_units_ahead": settings.max_units_ahead, "worker_environment_variables": sorted(settings.worker_environment or ()), "units": dict(self._units), + "resources": self._pooling.resources, "report": None, } if self._pool is not None: @@ -16419,6 +16460,9 @@ def _certify_main_with_close_out(argv: Sequence[str] | None) -> None: + ", so its checks run on the versions its manifests name." ) _refuse_reusing_a_certified_build(record.release_root) + # Pooled post-export scoring is the default; a bad setting, or a machine + # too small for one worker, stops here, before the build is placed. + post_export_pooling = _post_export_pooling_from_environment() certification = _Certification( evidence_release=args.evidence_release, owner_patterns=owner_patterns, @@ -16454,7 +16498,12 @@ def _certify_main_with_close_out(argv: Sequence[str] | None) -> None: run_id=run_id, emitter=_ACTIVE_EMITTER, ) - _certify_us_build(record, certification=certification, telemetry=telemetry) + _certify_us_build( + record, + certification=certification, + telemetry=telemetry, + post_export_pooling=post_export_pooling, + ) except BaseException as error: try: if telemetry is not None: diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index 213e7528cc..bf8b3d9a22 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -36,7 +36,8 @@ when the first stage opens, serves them all; with the release tool's ``_PostExportPooling`` (``ExportProbe(post_export_pooling=...)``) the stages' recorded requests are scored in the shared worker pool, as certification -scores them. The frame-based stages (1-3) run first, +scores them. The command does so by default, with certification's worker +settings, unless ``MICROCOSM_POST_EXPORT_WORKERS=serial``. The frame-based stages (1-3) run first, while the loaded frame is held, instead of after the scorer as in ``_main``: they read only the frame, so the order changes no verdict. Unlike the release, a stage that raises is recorded with its traceback and the next @@ -3439,6 +3440,10 @@ def main(argv: Sequence[str] | None = None) -> int: register = load_builder()._load_qrf_tail_concentration_exclusions( args.qrf_tail_register ) + # As certification: pooled scoring unless MICROCOSM_POST_EXPORT_WORKERS + # says serial; a bad setting, or a machine too small for one worker, + # stops here, before the export is loaded. + post_export_pooling = load_builder()._post_export_pooling_from_environment() report = probe_export( args.export, args.out, @@ -3467,6 +3472,7 @@ def main(argv: Sequence[str] | None = None) -> int: min_effective_households=args.min_effective_households, release_id=args.release_id, census=args.census, + post_export_pooling=post_export_pooling, ) summary = report["summary"] print( From 78a738783079ac2f2491ab8018341ef834967909 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:20:40 +0400 Subject: [PATCH 05/26] Add failing tests for review round 1 of pooled post-export scoring The tests require pooled scoring to: - refuse a reformed simulation whose reform is not the one the dry run recorded at that place (served by position alone, a consumer that opened its reforms in another order would get each other's values), one whose reform carries no description, and one beyond the recorded ones; the consumers' own builders mark each reform they build with its description; - fall back to each consumer's own baseline pass when a merged baseline unit fails on every attempt (an engine out of memory), as the serial scorer falls back when its merged pass raises MemoryError; - keep serving what the merged pass scored after the pool stopped, and refuse what needs the pool with PostExportPoolStoppedError, a WorkerPoolError, which the export probe records as its own failure; - raise a failed reform pass's error again when the consumer asks for the same keys again, as the serial scorer does; - record the environment the workers were given, and have each worker refuse a release tool whose bytes differ from the parent's. The export probe must register the two held-out reports' plans as certification does, count each entity's rows once in its row map, and refuse an engine given alongside pool settings. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pool.py | 24 ++ .../us/test_us_post_export_pooled_scoring.py | 308 +++++++++++++++++- .../us/test_us_post_export_probe.py | 97 +++++- .../microcosm_build/us_post_export_pool.py | 26 +- .../microcosm_build/us_post_export_probe.py | 5 +- 5 files changed, 449 insertions(+), 11 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py index d40a1a83fd..9259728c0e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py @@ -292,3 +292,27 @@ def test_the_plan_says_what_it_chose_and_why(pool_module) -> None: line = plan.describe() for text in ("4 pool workers", "formula", "23.00 GiB", "24.00 GiB", "5.25 GiB"): assert text in line, text + + +def test_a_worker_refuses_a_release_tool_other_than_the_parents( + pool_module, tmp_path +) -> None: + """A worker scores only with the code the scoring process runs: a tool + file that changed after the parent loaded it is refused at start.""" + import hashlib + + tool = tmp_path / "fixture_checked_tool.py" + tool.write_text("VALUE = 1\n") + digest = hashlib.sha256(tool.read_bytes()).hexdigest() + try: + with pytest.raises(RuntimeError, match="SHA-256"): + pool_module.release_tool("fixture_checked_tool", tool, sha256="0" * 64) + assert "fixture_checked_tool" not in sys.modules + loaded = pool_module.release_tool("fixture_checked_tool", tool, sha256=digest) + assert loaded.VALUE == 1 + # Found loaded already, it is checked against its file too. + tool.write_text("VALUE = 2\n") + with pytest.raises(RuntimeError, match="SHA-256"): + pool_module.release_tool("fixture_checked_tool", tool, sha256=digest) + finally: + sys.modules.pop("fixture_checked_tool", None) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index d1fc4d5bbd..f0bac32609 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -46,6 +46,7 @@ COMPUTES, ENGINE_LOG, FAIL_ON, + MEMORY_KEYS, FakeMicrosimulation, build_fake_parameter_reform, build_fake_reform, @@ -83,7 +84,7 @@ def pooled_reforms(monkeypatch, builder): monkeypatch.setattr( builder, "geography_coverage_payload", lambda path: {"h5": Path(path).name} ) - for name in (FAIL_ON, COMPUTES, ENGINE_LOG): + for name in (FAIL_ON, COMPUTES, ENGINE_LOG, MEMORY_KEYS): monkeypatch.delenv(name, raising=False) @@ -807,3 +808,308 @@ def test_the_probe_command_scores_as_certification_does(builder) -> None: ] keywords = {keyword.arg: ast.unparse(keyword.value) for keyword in call.keywords} assert keywords["post_export_pooling"] == "post_export_pooling" + + +# --------------------------------------------------------------------------- +# Review round 1 +# --------------------------------------------------------------------------- + + +def _reform_consumer(*opened): + """A consumer that reads the baseline, then opens each reform of the + dry run's order (``opened(total)`` picks the real run's order) and asks + each for income tax.""" + + (choose,) = opened + + def consumer(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + total = simulate(None).calculate("age", 2024).sum() + totals = [] + for description in choose(total): + reformed = simulate( + description if records_only else build_fake_reform(description) + ) + totals.append(reformed.calculate("income_tax", 2024).sum()) + return totals + + return consumer + + +def test_a_reform_other_than_the_recorded_one_is_refused( + builder, + pooled_reforms, + tmp_path, +) -> None: + """The dry run opened A then B; the real run opens B then A with the + same keys. Served by position alone, B would get A's values.""" + + def opened(total): + return ( + [FIXTURE_REFORM, OTHER_REFORM] + if total == 0 + else [OTHER_REFORM, FIXTURE_REFORM] + ) + + consumer = _reform_consumer(opened) + plan = _fixture_plan(builder, consumer) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + with pytest.raises( + RuntimeError, match="reformed simulation 0 with a reform other than" + ): + consumer(scoring.simulate) + finally: + scorer.close() + + +def test_a_reform_without_its_description_or_beyond_the_recorded_ones_is_refused( + builder, + pooled_reforms, + tmp_path, +) -> None: + def consumer(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + simulate(None).calculate("age", 2024) + if records_only: + simulate(FIXTURE_REFORM).calculate("income_tax", 2024) + return simulate + + plan = _fixture_plan(builder, consumer) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + with pytest.raises(RuntimeError, match="carries no description"): + scoring.simulate(object()) + built = build_fake_reform(FIXTURE_REFORM) + with pytest.raises(RuntimeError, match="more reformed simulations"): + scoring.simulate(built) + finally: + scorer.close() + + +def _baseline_consumer(*variables): + def consumer(simulate): + baseline = simulate(None) + return [baseline.calculate(variable, 2024).sum() for variable in variables] + + return consumer + + +def test_a_merged_pass_a_worker_cannot_finish_falls_back_as_the_serial_scorer_does( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + capsys, +) -> None: + """An engine runs out of memory on the merged pass's three keys but not + on either consumer's two. The serial scorer catches the MemoryError and + scores each consumer's own plan; so does the pool, once the merged unit + has failed on every attempt.""" + monkeypatch.setenv(MEMORY_KEYS, "2") + consumers = { + "first": _baseline_consumer("age", "snap"), + "second": _baseline_consumer("age", "income_tax"), + } + plan = builder._post_export_scoring_plan( + n_households=N_HOUSEHOLDS, + maximum_microsim_batch_size=BATCH_SIZE, + consumers=consumers, + ) + + def run(scorer): + try: + outputs = {} + for name, consumer in consumers.items(): + scoring = scorer.open_consumer(name, plan.baseline_plan(name)) + outputs[name] = consumer(scoring.simulate) + scorer.finish_consumer(scoring) + block = scorer.manifest_record() + finally: + scorer.close() + block.pop("execution") + return outputs, block + + serial = run(_serial_scorer(builder, plan, tmp_path / "serial")) + assert "merged baseline plan failed" in capsys.readouterr().out + pooled = run(_pooled_scorer(builder, plan, tmp_path / "pooled", 1)) + assert "merged baseline plan failed" in capsys.readouterr().out + assert canonical_result_bytes(pooled) == canonical_result_bytes(serial) + + +def test_a_stopped_pool_still_serves_what_it_already_scored( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """A reform unit that fails on every attempt stops the pool. A consumer + served from the merged pass's values is still served; one that needs the + pool is refused with a WorkerPoolError, which the held-out reports pass + on instead of recording an unavailable measurement.""" + monkeypatch.setenv(MEMORY_KEYS, "2") + + def prefetching(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + simulate(None).calculate("age", 2024) + reformed = simulate( + FIXTURE_REFORM if records_only else build_fake_reform(FIXTURE_REFORM) + ) + reformed.prefetch((("income_tax", 2024), ("snap", 2024), ("ssi", 2024))) + return reformed.calculate("income_tax", 2024).sum() + + consumers = { + "first": prefetching, + "second": _baseline_consumer("age"), + "third": _fixture_consumer( + lambda total: [(OTHER_REFORM, [("income_tax", 2024)])] + ), + } + plan = builder._post_export_scoring_plan( + n_households=N_HOUSEHOLDS, + maximum_microsim_batch_size=BATCH_SIZE, + consumers=consumers, + ) + serial = _serial_scorer(builder, plan, tmp_path / "serial") + try: + expected = consumers["second"]( + serial.open_consumer("second", plan.baseline_plan("second")).simulate + ) + finally: + serial.close() + scorer = _pooled_scorer(builder, plan, tmp_path / "pooled", 1) + try: + first = scorer.open_consumer("first", plan.baseline_plan("first")) + with pytest.raises(WorkerPoolUnitError, match="MemoryError"): + prefetching(first.simulate) + second = scorer.open_consumer("second", plan.baseline_plan("second")) + assert consumers["second"](second.simulate) == expected + scorer.finish_consumer(second) + third = scorer.open_consumer("third", plan.baseline_plan("third")) + with pytest.raises(builder.PostExportPoolStoppedError) as stopped: + consumers["third"](third.simulate) + assert isinstance(stopped.value, WorkerPoolError) + finally: + scorer.close() + + +def test_asking_again_after_a_failed_pass_raises_what_the_serial_scorer_raises( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + monkeypatch.setenv(COMPUTES, json.dumps({"income_tax": ["relative_income_change"]})) + + def consumer(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + simulate(None).calculate("age", 2024) + reformed = simulate( + FIXTURE_REFORM if records_only else build_fake_reform(FIXTURE_REFORM) + ) + errors = [] + for _ in range(2): + try: + reformed.calculate("income_tax", 2024) + except RuntimeError as error: + errors.append(f"{type(error).__name__}: {error}") + return errors + + plan = _fixture_plan(builder, consumer) + observed = {} + for mode in ("serial", "pooled"): + scorer = ( + _serial_scorer(builder, plan, tmp_path / mode) + if mode == "serial" + else _pooled_scorer(builder, plan, tmp_path / mode, 1) + ) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + errors = consumer(scoring.simulate) + observed[mode] = (errors, scoring.reform_systems, scoring.reform_passes) + finally: + scorer.close() + assert len(observed["serial"][0]) == 2 + assert observed["pooled"] == observed["serial"] + + +def test_the_execution_record_names_the_environment_workers_got( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + from microcosm.build.us_runtime import take_up_contract + + monkeypatch.setattr( + take_up_contract, + "us_engine_abi_lock_check_environment", + lambda: {"MICROCOSM_TEST_HANDED_DOWN": "handed down"}, + ) + plan = _fixture_plan(builder, _fixture_consumer(lambda total: [])) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + scorer.finish_consumer( + scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + ) + execution = scorer.execution_record() + finally: + scorer.close() + assert execution["worker_environment_variables"] == ["MICROCOSM_TEST_HANDED_DOWN"] + + +def test_the_consumers_builders_mark_each_reform_with_its_description( + monkeypatch, +) -> None: + """The smoke check's and reform validation's own builders mark every + reform they build with the description they built it from, which pooled + scoring compares with the reform its dry run recorded.""" + from microcosm.build.us_runtime.post_export_requests import reform_description + + class StubReform: + @classmethod + def from_dict(cls, changes, country_id): + return type("FromDict", (cls,), {"changes": dict(changes)}) + + core = types.ModuleType("policyengine_core") + reforms = types.ModuleType("policyengine_core.reforms") + reforms.Reform = StubReform + core.reforms = reforms + monkeypatch.setitem(sys.modules, "policyengine_core", core) + monkeypatch.setitem(sys.modules, "policyengine_core.reforms", reforms) + from microcosm.build.us_runtime.release_input_coverage import ( + us_release_reform_coverage_probes, + ) + + probes = us_release_reform_coverage_probes() + neutralizing = next(probe for probe in probes if probe.neutralized_variable) + changing = next( + probe + for probe in probes + if not probe.neutralized_variable and not probe.list_edits + ) + for probe in (neutralizing, changing): + assert reform_description(smoke_module._build_reform(probe)) == probe + specs = reform_validation_module.load_default_reform_specs(period=2024) + for spec in ( + next(spec for spec in specs if spec.neutralized_variable), + next(spec for spec in specs if spec.parameter_changes), + ): + assert reform_description(spec.build_reform()) == spec + changes = {"gov.irs.fixture": {"2024-01-01": 1}} + assert reform_description( + reform_validation_module._build_parameter_reform(changes) + ) == ParameterChangesReform(changes) + # Two builds are two reforms, each with its own description. + assert smoke_module._build_reform(changing) is not smoke_module._build_reform( + changing + ) + + +def test_workers_check_they_run_the_parents_release_tool(builder) -> None: + import hashlib + + tool = Path(builder.__file__) + assert builder._RELEASE_TOOL_SHA256 == hashlib.sha256(tool.read_bytes()).hexdigest() diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py index c5f64cdd88..96ccade625 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py @@ -87,13 +87,16 @@ def test_probe_runs_every_stage_on_a_subsample( json.loads(line) for line in (tmp_path / "probe" / "passes.jsonl").read_text().splitlines() ] - # As in certification, every engine stage's baseline plan is registered: - # one merged pass, run when the smoke opens, serves them all, so - # demographics runs no pass of its own. + # As in certification, every engine stage's baseline plan is registered, + # with the two held-out reports' (which the probe does not report): one + # merged pass, run when the smoke opens, serves them all, so demographics + # runs no pass of its own. assert report["stages"]["open_scorer"]["registered_consumers"] == [ "reform_coverage_smoke", "reform_validation", "demographics", + "ssi_social_security_holdout", + "medicare_irmaa_holdout", ] assert {row["stage"] for row in passes} == { "reform_coverage_smoke", @@ -1407,8 +1410,94 @@ def consumer(simulate): receipt=receipt, stages=("reform_coverage_smoke", "demographics"), ) - assert report["stages"]["open_scorer"]["registered_consumers"] == ["demographics"] + assert report["stages"]["open_scorer"]["registered_consumers"] == [ + "demographics", + "ssi_social_security_holdout", + "medicare_irmaa_holdout", + ] smoke = report["stages"]["reform_coverage_smoke"] assert smoke["status"] == "error" assert smoke["error"] == "ValueError: fixture dry run refused" assert report["stages"]["demographics"]["status"] == "completed" + + +def test_a_stage_the_stopped_pool_could_not_serve_is_the_probes_failure( + probe_tool, builder +) -> None: + """Once a unit has failed on every attempt, later stages that need the + pool are not scored. That is not a release failure of theirs: the stage + records it as the probe's own, and only the stage that met the failed + unit records the release's.""" + from types import SimpleNamespace + + probe = SimpleNamespace( + builder=builder, + clock=probe_tool.StageClock(None), + report={"stages": {}}, + verdicts=[], + _write_report=lambda: None, + ) + + def stopped(): + raise builder.PostExportPoolStoppedError( + "Pooled post-export scoring stopped earlier; nothing more is served." + ) + + record = probe_tool.ExportProbe._stage(probe, "demographics", stopped, "raises") + assert record["status"] == "error" + (verdict,) = probe.verdicts + assert verdict["release_consequence"] == "probe integrity" + assert "could not run this step" in verdict["reason"] + + +def test_the_row_map_counts_each_entitys_rows_once(probe_tool) -> None: + from collections.abc import Sequence + from types import SimpleNamespace + + class CountedBatches(Sequence): + reads = 0 + + def __len__(self) -> int: + return 3 + + def __getitem__(self, position): + if not 0 <= position < 3: + raise IndexError(position) + CountedBatches.reads += 1 + return SimpleNamespace(n=lambda entity: 2) + + row_map = probe_tool.HouseholdRowMap(CountedBatches(), sampler=None) + assert [row_map.n_rows("person") for _ in range(4)] == [6, 6, 6, 6] + assert CountedBatches.reads == 3 + + +def test_engine_options_and_pool_settings_are_not_given_together( + probe_tool, builder, chain, tmp_path +) -> None: + """With pooling the workers' engine is the pool settings'; an engine + given to the probe as well would be dropped without a word.""" + from microcosm.build.worker_pool import WorkerPoolSettings + + _, path, receipt, _ = chain + pooling = builder._PostExportPooling( + WorkerPoolSettings(workers=1), chosen_by="test" + ) + with pytest.raises(ValueError, match="scorer_options"): + fixture_export_probe( + probe_tool, + builder, + path, + tmp_path / "probe", + receipt=receipt, + scorer_options={"microsimulation_cls": object}, + post_export_pooling=pooling, + ) + probe, _ = fixture_export_probe( + probe_tool, + builder, + path, + tmp_path / "probe", + receipt=receipt, + post_export_pooling=pooling, + ) + assert probe.scorer_options == {} diff --git a/test_support/microcosm_build/us_post_export_pool.py b/test_support/microcosm_build/us_post_export_pool.py index 0079b00a3e..43984f1ec4 100644 --- a/test_support/microcosm_build/us_post_export_pool.py +++ b/test_support/microcosm_build/us_post_export_pool.py @@ -16,7 +16,12 @@ it leaves a value for (the population-aggregate and baseline-branch refusals); - :data:`ENGINE_LOG`: a directory; each process appends one JSON line per - engine construction and per calculation to ``.jsonl`` there. + engine construction and per calculation to ``.jsonl`` there; +- :data:`MEMORY_KEYS`: the most distinct keys one engine computes before it + raises ``MemoryError``, as an engine that ran out of memory would. + +Each fake reform carries the description it was built from, as the +consumers' own builders mark the reforms they build. """ from __future__ import annotations @@ -28,7 +33,10 @@ import numpy as np -from microcosm.build.us_runtime.post_export_requests import ParameterChangesReform +from microcosm.build.us_runtime.post_export_requests import ( + ParameterChangesReform, + described_reform, +) from microcosm.build.us_runtime.reform_validation import ReformValidationSpec from microcosm.build.us_runtime.release_input_coverage import ReformCoverageProbe from test_support.microcosm_build.us_post_export_scoring import ( @@ -44,6 +52,7 @@ FAIL_ON = "MICROCOSM_TEST_POST_EXPORT_FAIL_ON" COMPUTES = "MICROCOSM_TEST_POST_EXPORT_COMPUTES" ENGINE_LOG = "MICROCOSM_TEST_POST_EXPORT_ENGINE_LOG" +MEMORY_KEYS = "MICROCOSM_TEST_POST_EXPORT_MEMORY_KEYS" #: Parameter paths a fake reform sets from a ``ParameterChangesReform`` #: payload, so a reform can move a behavioral-response parameter. @@ -64,7 +73,7 @@ def build_fake_reform(description): fixture builds it in the parent: labelled by the probe's or spec's id, or by the parameter changes' JSON.""" if isinstance(description, ReformCoverageProbe | ReformValidationSpec): - return _FakeReform(description.id) + return described_reform(_FakeReform(description.id), description) if isinstance(description, ParameterChangesReform): changes = dict(description.parameter_changes) parameters = { @@ -72,8 +81,11 @@ def build_fake_reform(description): for path, value in changes.items() if path.startswith(_RESPONSE_PARAMETERS) } - return _FakeReform( - json.dumps(changes, sort_keys=True, default=str), parameters=parameters + return described_reform( + _FakeReform( + json.dumps(changes, sort_keys=True, default=str), parameters=parameters + ), + description, ) raise TypeError(f"no fake reform for {type(description).__name__}") @@ -169,6 +181,10 @@ def calculate(self, variable, period, map_to=None): "period": period, } ) + self.asked = getattr(self, "asked", set()) | {(variable, period, map_to)} + limit = os.environ.get(MEMORY_KEYS) + if limit and len(self.asked) > int(limit): + raise MemoryError(f"fixture engine holds more than {limit} keys") computes = json.loads(os.environ.get(COMPUTES) or "{}") for computed in (variable, *computes.get(variable, ())): self.known.setdefault(computed, set()).add(period) diff --git a/test_support/microcosm_build/us_post_export_probe.py b/test_support/microcosm_build/us_post_export_probe.py index 44102e6c40..29c98c3078 100644 --- a/test_support/microcosm_build/us_post_export_probe.py +++ b/test_support/microcosm_build/us_post_export_probe.py @@ -133,7 +133,10 @@ def fixture_export_probe( serial scorer is given (the log then records nothing).""" log = _EngineLog() log.fail_on = fail_on - if scorer_options is None: + if scorer_options is None and options.get("post_export_pooling") is not None: + # The pool settings name the workers' engine. + scorer_options = {} + elif scorer_options is None: scorer_options = { "microsimulation_cls": float32_engine(log), "dataset_from_frame": lambda batch_frame: batch_frame, From 0ed588af9f59c8a898684f8d2ce7208fa045843a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:28:13 +0400 Subject: [PATCH 06/26] Fix review round 1 of pooled post-export scoring - Each reformed simulation must be opened with the reform the dry run recorded at that place: the smoke check's and reform validation's builders mark each reform with the description they built it from (post_export_requests.described_reform), the dry run keeps every reform it opened, and the pooled scorer refuses a reform with another description, none, or beyond the recorded ones. - A merged baseline unit that fails on every attempt is a failed merged pass: each consumer then scores its own plan in a new pool, as the serial scorer falls back when its merged pass raises MemoryError. - A stopped second pool run refuses only what needs the pool, with PostExportPoolStoppedError (a WorkerPoolError, which the held-out reports pass on); what the merged pass scored is still served. - A failed reform pass asked for again raises its error again, with the serial scorer's counts. - Workers refuse a release tool whose bytes differ from the parent's (_RELEASE_TOOL_SHA256), and the execution record names the environment the workers were given. - The export probe registers the held-out reports' plans as certification does, records a stage the stopped pool could not serve as its own failure, counts each entity's rows once, refuses an engine given alongside pool settings, and says which passes passes.jsonl leaves out. The worker-start test's third check is corrected: a tool found loaded with a record of the bytes it ran is accepted, as those are the code the worker scores with. Co-Authored-By: Claude Opus 5.5 --- .../us-pooled-post-export-scoring.changed.md | 2 +- docs/us-release-build-rule.md | 31 ++- .../build/us_runtime/post_export_pool.py | 48 +++- .../build/us_runtime/post_export_requests.py | 28 +++ .../build/us_runtime/reform_coverage_smoke.py | 12 +- .../build/us_runtime/reform_validation.py | 21 +- .../us/test_us_post_export_pool.py | 10 +- tools/build_us_fiscal_refresh_release.py | 224 ++++++++++++++---- tools/probe_us_post_export.py | 58 ++++- 9 files changed, 366 insertions(+), 68 deletions(-) diff --git a/changelog.d/us-pooled-post-export-scoring.changed.md b/changelog.d/us-pooled-post-export-scoring.changed.md index e9ef8bcbc4..856fbc9e5e 100644 --- a/changelog.d/us-pooled-post-export-scoring.changed.md +++ b/changelog.d/us-pooled-post-export-scoring.changed.md @@ -1 +1 @@ -US certification scores post-export stages in the shared worker pool by default (`_PooledPostExportScorer`), with tracker decision 1.4 · 6's settings: `MICROCOSM_POST_EXPORT_WORKERS` unset or `auto` starts at most min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers and refuses, before the build is placed, a machine with no room for one; a positive number starts that many, and `serial` scores in the certifying process as before; each worker is replaced after 2 units and capped at max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers). In the pool, the merged baseline pass is split into one range of household batches per worker, each reformed simulation's recorded passes are one unit, and each post-export stage then runs in the certifying process over the results, refusing any request its engine-free dry run did not record. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's merged baseline pass instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan (one shared baseline pass, as certification runs), can score in the pool and writes each worker pass's time and memory to `passes.jsonl`; its household row map reads one batch file at a time. +US certification scores post-export stages in the shared worker pool by default (`_PooledPostExportScorer`), with tracker decision 1.4 · 6's settings: `MICROCOSM_POST_EXPORT_WORKERS` unset or `auto` starts at most min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers and refuses, before the build is placed, a machine with no room for one; a positive number starts that many, and `serial` scores in the certifying process as before; each worker is replaced after 2 units and capped at max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers). In the pool, the merged baseline pass is split into one range of household batches per worker, each reformed simulation's recorded passes are one unit, and each post-export stage then runs in the certifying process over the results, refusing any request, or any reform, its engine-free dry run did not record; the smoke check's and reform validation's builders mark each reform with the description it was built from. A merged baseline unit the pool cannot finish falls back to each stage's own pass, as a serial `MemoryError` does, and a worker refuses a release tool whose bytes differ from the certifying process's. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's merged baseline pass instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan and the held-out reports' (certification's shared baseline pass), can score in the pool and writes each worker pass's time and memory to `passes.jsonl`; its household row map reads one batch file at a time. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index c56d706d99..02bea223f0 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -533,7 +533,10 @@ one Microsimulation over the whole file. stages run: a worker builds the reform's rules once per unit, as the serial scorer builds them once per reformed simulation. If the shared pass fails, the second run also holds each stage's own baseline pass before - that stage's reform units. + that stage's reform units. That includes a range of the shared pass that + failed on every attempt (its worker ran out of memory, went over its cap + or died), as the serial scorer falls back when its shared pass raises + `MemoryError`. - A worker reads each batch from the scorer's batch file, refusing one that changed, and scores it with the serial scorer's own code (`_score_post_export_batches`): one engine per batch, keys in ascending @@ -545,15 +548,21 @@ one Microsimulation over the whole file. scorer would have raised, as an error with the worker's exception's class name and message, so a held-out report that records the error records the same text. A changed batch file raises `PostExportBatchFileError`, and a - pool that cannot score (a unit that failed on every attempt, a worker that - could not start) raises `WorkerPoolError`; both stop certification, the - held-out reports included. + pool that cannot score (a unit after the shared pass that failed on every + attempt, a worker that could not start) raises `WorkerPoolError`; both + stop certification, the held-out reports included. After that the pool + serves nothing more that needs its workers + (`PostExportPoolStoppedError`, a `WorkerPoolError`), but a stage served + from the shared pass's values is still served. - Each stage then runs as in the serial path and builds its own reforms (the smoke records each list edit's resolved lists from its own). Its baseline is served its recorded plan, and each reformed simulation its recorded - passes in order. A stage that asks for anything else is refused, so a - stage whose requests depended on the values it got back cannot be served - values scored for a different request. Each key's per-batch values are + passes in order. Each stage's own builders mark every reform they build + with the description they built it from, and each reformed simulation + must be opened with the reform the dry run recorded at that place. A + stage that asks for anything else is refused, so a stage whose requests + depended on the values it got back cannot be served values scored for a + different request or another reform. Each key's per-batch values are joined in batch order, so every output, both manifests' consumer records and the smoke's scoring record are byte-identical to the serial scorer's. - Workers inherit the certifying process's environment, thread variables @@ -563,7 +572,9 @@ one Microsimulation over the whole file. tool skips the lock-file check. A worker spawned from certification runs certification's script again as `__mp_main__`, which imports the release tool; that is the import the worker needs, so it runs once per worker - start. + start. A worker refuses to start with a release tool whose bytes differ + from the certifying process's, so a tool file changed during a run cannot + mix two versions' results (the microcosm packages are not checked). - The manifests' `post_export_scoring` block records how scoring ran under `execution`: `{"mode": "serial"}`, or the pool's settings, how the worker count was chosen, the plan's memory and core readings, unit counts and the @@ -650,8 +661,8 @@ after a probe, spec or engine-lock change before starting a release. R4's existing full-export rehearsal times the smoke and validation baseline plans plus three selected reform passes; it does not cover every reform and does not replace this sweep. `tools/probe_us_post_export.py` -registers every stage's baseline plan, as certification does, so its baseline -is one shared pass. +registers every stage's baseline plan and the two held-out reports', as +certification does, so its baseline is certification's shared pass. `calibration_diagnostics.json` records the plan under `build.post_export_scoring` (method, batch size, batch count, each stage's baseline keys and periods), and diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py index 3a81c70c5c..a205769966 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py @@ -41,10 +41,12 @@ from __future__ import annotations import builtins +import hashlib import importlib.util import os import sys import traceback +import zlib from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path @@ -342,7 +344,31 @@ class PostExportUnitResult: # --------------------------------------------------------------------------- -def release_tool(module_name: str, path: str | Path): +def _source_sha256(module) -> str | None: + """The SHA-256 of the bytes ``module`` ran, or of its file now.""" + recorded = getattr(module, "__loaded_sha256__", None) + if recorded is not None: + return str(recorded) + try: + return hashlib.sha256(Path(module.__file__).read_bytes()).hexdigest() + except OSError: + return None + + +def _refuse_other_bytes(module, path: Path, sha256: str | None) -> None: + if sha256 is None: + return + observed = _source_sha256(module) + if observed != sha256: + raise RuntimeError( + f"The release tool at {path} has SHA-256 {observed}; the scoring " + f"process runs {sha256}. A worker scores only with the code the " + "scoring process runs, so a tool file changed while scoring ran is " + "refused." + ) + + +def release_tool(module_name: str, path: str | Path, *, sha256: str | None = None): """The release tool in this process: loaded already, or from ``path``. A worker spawned from a release run has run the parent's main script again @@ -351,6 +377,11 @@ def release_tool(module_name: str, path: str | Path): loaded already; it is loaded from ``path`` only when it is not (the parent loaded it by path, as the tests and the export probe do). Either way the tool's module body runs once per worker. + + With ``sha256``, the parent's digest of the tool's bytes, a tool whose + bytes differ is refused: the bytes this function executes, or the file of + a tool found loaded already. (The microcosm packages the tool imports are + not checked.) """ path = Path(path).resolve() for candidate in ( @@ -360,28 +391,35 @@ def release_tool(module_name: str, path: str | Path): ): file = getattr(candidate, "__file__", None) if file is not None and Path(file).resolve() == path: + _refuse_other_bytes(candidate, path, sha256) return candidate name = module_name if name in {"__main__", "__mp_main__"} or name in sys.modules: - name = f"_post_export_release_tool_{abs(hash(str(path)))}" + name = f"_post_export_release_tool_{zlib.crc32(str(path).encode()):08x}" spec = importlib.util.spec_from_file_location(name, path) if spec is None or spec.loader is None: raise ImportError(f"cannot load the release tool from {path}") module = importlib.util.module_from_spec(spec) + # Execute the bytes that are checked, not a second read of the file. + source = path.read_bytes() + module.__loaded_sha256__ = hashlib.sha256(source).hexdigest() + _refuse_other_bytes(module, path, sha256) # Registered before it runs, as ``dataclasses`` resolves annotations # through ``sys.modules``. sys.modules[name] = module try: - spec.loader.exec_module(module) + exec(compile(source, str(path), "exec", dont_inherit=True), module.__dict__) except BaseException: sys.modules.pop(name, None) raise return module -def start_post_export_worker(module_name: str, path: str, *arguments: Any): +def start_post_export_worker( + module_name: str, path: str, sha256: str | None, *arguments: Any +): """The pool's initializer: the release tool's worker over its batch files.""" - return release_tool(module_name, path)._PostExportWorker(*arguments) + return release_tool(module_name, path, sha256=sha256)._PostExportWorker(*arguments) def score_post_export_unit(worker, unit: PostExportUnit) -> PostExportUnitResult: diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py index b954240fd1..9a31791621 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py @@ -35,6 +35,12 @@ class defined inside a function, which pickle cannot name. So a consumer whose Neither type can be hashed, because a reform description holds dictionaries; key a request's results by its ``(consumer, position)``. + +Each consumer's own builder also marks every reform it builds with the +description it built it from (:func:`described_reform`), so pooled scoring, +which serves a consumer the results of its recorded requests, can check that +each reformed simulation the consumer opens is the one its dry run recorded +at that place (:func:`reform_description`). """ from __future__ import annotations @@ -50,11 +56,14 @@ class defined inside a function, which pickle cannot name. So a consumer whose __all__ = [ "RECORDS_REQUESTS_ONLY", + "REFORM_DESCRIPTION", "ParameterChangesReform", "PostExportReform", "PostExportRequest", "build_post_export_reform", "check_post_export_reform", + "described_reform", + "reform_description", ] #: Set to ``True`` on a ``simulate`` that only records the requests it is @@ -64,6 +73,25 @@ class defined inside a function, which pickle cannot name. So a consumer whose #: reform, resolves no list edit and needs no engine. RECORDS_REQUESTS_ONLY = "records_requests_only" +#: The attribute a consumer's builder sets on each reform it builds: the +#: description it built the reform from. +REFORM_DESCRIPTION = "microcosm_post_export_reform_description" + + +def described_reform(reform: Any, description: object) -> Any: + """Mark ``reform`` as built from ``description`` and return it. + + The builders return a new reform class on every call (``Reform.from_dict`` + and the classes they define), so the mark is that build's alone. + """ + setattr(reform, REFORM_DESCRIPTION, description) + return reform + + +def reform_description(reform: Any) -> object | None: + """The description ``reform`` was built from, or ``None`` if unmarked.""" + return getattr(reform, REFORM_DESCRIPTION, None) + @dataclass(frozen=True) class ParameterChangesReform: diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/reform_coverage_smoke.py b/packages/microcosm-build/src/microcosm/build/us_runtime/reform_coverage_smoke.py index 067e66c872..cf06619d74 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/reform_coverage_smoke.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/reform_coverage_smoke.py @@ -28,7 +28,10 @@ from typing import Any from microcosm.build.gates import GateResult -from microcosm.build.us_runtime.post_export_requests import RECORDS_REQUESTS_ONLY +from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, + described_reform, +) from microcosm.build.us_runtime.release_input_coverage import ( ListParameterEdit, ReformCoverageProbe, @@ -63,10 +66,17 @@ def _build_reform(probe: ReformCoverageProbe) -> Any: (:func:`check_resolved_list_edit_target`), so the resolved list can only replace the baseline it was derived from. + The reform carries the probe as its description + (:func:`~microcosm.build.us_runtime.post_export_requests.described_reform`). + Raises: ValueError: Naming the probe, if a list edit does not fit the installed baseline. """ + return described_reform(_build_undescribed_reform(probe), probe) + + +def _build_undescribed_reform(probe: ReformCoverageProbe) -> Any: from policyengine_core.reforms import Reform if probe.neutralized_variable: diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/reform_validation.py b/packages/microcosm-build/src/microcosm/build/us_runtime/reform_validation.py index 31eed194a1..1213b00bb2 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/reform_validation.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/reform_validation.py @@ -71,9 +71,20 @@ def _build_parameter_reform(parameter_changes: dict[str, Any]) -> Any: + """The ``Reform.from_dict`` reform, carrying its parameter changes as its + description (``post_export_requests.described_reform``).""" from policyengine_core.reforms import Reform - return Reform.from_dict(parameter_changes, country_id="us") + # Imported here: post_export_requests imports ReformValidationSpec. + from microcosm.build.us_runtime.post_export_requests import ( + ParameterChangesReform, + described_reform, + ) + + reform = Reform.from_dict(parameter_changes, country_id="us") + if not parameter_changes: + return reform + return described_reform(reform, ParameterChangesReform(parameter_changes)) @dataclass(frozen=True) @@ -138,8 +149,14 @@ def build_reform(self) -> Any: """Construct the policyengine reform object for this spec. Imports are lazy so the module (and its unit tests) load without - policyengine-us installed. + policyengine-us installed. The reform carries this spec as its + description (``post_export_requests.described_reform``). """ + from microcosm.build.us_runtime.post_export_requests import described_reform + + return described_reform(self._build_undescribed_reform(), self) + + def _build_undescribed_reform(self) -> Any: if self.neutralized_variable: from policyengine_core.reforms import Reform diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py index 9259728c0e..4931b13008 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py @@ -310,8 +310,16 @@ def test_a_worker_refuses_a_release_tool_other_than_the_parents( assert "fixture_checked_tool" not in sys.modules loaded = pool_module.release_tool("fixture_checked_tool", tool, sha256=digest) assert loaded.VALUE == 1 - # Found loaded already, it is checked against its file too. + # Found loaded already, it is the bytes it ran that count: those are + # the code the worker would score with, whatever the file holds now. tool.write_text("VALUE = 2\n") + assert ( + pool_module.release_tool("fixture_checked_tool", tool, sha256=digest) + is loaded + ) + # A tool imported without a record of its bytes (certification's + # import by name) is checked against its file. + del loaded.__loaded_sha256__ with pytest.raises(RuntimeError, match="SHA-256"): pool_module.release_tool("fixture_checked_tool", tool, sha256=digest) finally: diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 25229b5c8c..65ee80d2f4 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -383,6 +383,7 @@ PostExportRequest, build_post_export_reform, check_post_export_reform, + reform_description, ) from microcosm.build.us_runtime.puf_capital_gains_tail import ( assert_puf_capital_gains_tail_survives_selection, @@ -466,6 +467,7 @@ WorkerPoolError, WorkerPoolReport, WorkerPoolSettings, + WorkerPoolUnitError, process_memory_bytes, ) from microcosm.calibrate import ( @@ -5402,6 +5404,20 @@ def _dry_run_post_export( one per ``calculate`` or ``prefetch`` that asks a reformed simulation for a key not asked of it before, so a ``prefetch`` of several keys is one pass, whose keys are in ascending period order.""" + requests, reform_passes, _ = _dry_run_post_export_with_reforms(consumer) + return requests, reform_passes + + +def _dry_run_post_export_with_reforms( + consumer: Callable[[Callable[[Any], Any]], object], +) -> tuple[ + tuple[tuple[int | None, object, PostExportKey], ...], + tuple[tuple[int, tuple[PostExportKey, ...]], ...], + tuple[object, ...], +]: + """``_dry_run_post_export``'s requests and passes, and the description of + every reform the consumer opened, in the order it opened them (asked or + not).""" asked: dict[tuple[int | None, PostExportKey], None] = {} reforms: list[object] = [] reform_passes: list[tuple[int, tuple[PostExportKey, ...]]] = [] @@ -5428,7 +5444,7 @@ def simulate(reform): if simulation is not None ), ) - return requests, tuple(reform_passes) + return requests, tuple(reform_passes), tuple(reforms) def _record_post_export_request_descriptors( @@ -5504,7 +5520,11 @@ def __init__( name: str, descriptors: Sequence[PostExportRequest], reform_passes: Sequence[tuple[int, tuple[PostExportKey, ...]]], + opened_reforms: Sequence[object] | None = None, ) -> None: + """``opened_reforms`` are the descriptions of every reform the dry run + opened, in order, including any never asked for a key; without them, + those of the reformed simulations that were asked.""" self.name = str(name) self.descriptors = tuple(descriptors) self.baseline_plan = tuple( @@ -5529,6 +5549,21 @@ def __init__( f"{self.name}: the dry run's reform passes do not hold exactly " "its reform requests, in their order." ) + if opened_reforms is None: + opened = {**self.reforms} + opened_reforms = [ + opened.get(number) for number in range(max(opened, default=-1) + 1) + ] + self.opened_reforms = tuple(opened_reforms) + if any( + simulation >= len(self.opened_reforms) + or self.opened_reforms[simulation] is not reform + for simulation, reform in self.reforms.items() + ): + raise ValueError( + f"{self.name}: the dry run's opened reforms do not hold the " + "reform of every reform request." + ) self.simulations = tuple(dict.fromkeys(sim for sim, _ in self.reform_passes)) if list(self.simulations) != sorted(self.simulations): raise ValueError( @@ -5547,7 +5582,7 @@ def _record_post_export_consumer_requests( name: str, consumer: Callable[[Callable[[Any], Any]], object] ) -> _PostExportConsumerRequests: """Every request and reform pass of ``consumer``, from one engine-free dry run.""" - requests, reform_passes = _dry_run_post_export(consumer) + requests, reform_passes, opened = _dry_run_post_export_with_reforms(consumer) descriptors = tuple( PostExportRequest( consumer=name, @@ -5562,7 +5597,7 @@ def _record_post_export_consumer_requests( requests ) ) - return _PostExportConsumerRequests(name, descriptors, reform_passes) + return _PostExportConsumerRequests(name, descriptors, reform_passes, opened) class _AscendingPeriodEngine: @@ -6777,14 +6812,19 @@ def finish(self) -> None: # (``_score_post_export_batches``): ascending periods, the # population-aggregate refusal of a pass over a multi-batch H5, the # baseline-branch refusal and the behavioral-response check of a reform -# pass. A failure is returned with the unit, not raised. +# pass. A failure is returned with the unit, not raised. A merged +# baseline unit that fails on every attempt (out of memory, over its cap) +# is a failed merged pass, as a serial MemoryError is. # * The consumers then run in this process, as in the serial path, and build # their own reforms (the smoke check records each list edit's resolved # lists from its own). Each baseline is served the consumer's recorded -# plan and refuses any other key. Each reformed simulation is served its -# recorded passes in order and refuses any other request, so a consumer -# whose requests depend on the values it gets back cannot be scored with -# values computed for another request. Each key's parts are joined in +# plan and refuses any other key. Each reformed simulation must be opened +# with the reform the dry run recorded at that place (the consumers' +# builders mark each reform with its description) and is served its +# recorded passes in order, refusing any other request, so a consumer whose +# requests depend on the values it gets back cannot be scored with values +# computed for another request or another reform. Each key's parts are +# joined in # batch order (``_concatenate_post_export_parts``), so every value, total # and output is byte-identical to the serial scorer's. A pass that failed # in a worker raises an error with the worker's exception's class name and @@ -6808,6 +6848,26 @@ def _post_export_unit_failure( ) +class PostExportPoolStoppedError(WorkerPoolError): + """Pooled post-export scoring stopped earlier, so this request, which + needs its workers, is not served. The error it stopped on is the cause. + + A ``WorkerPoolError``, so the held-out reports stop certification on it, + as on the pool failure itself, instead of recording a measurement as + unavailable. + """ + + +#: The SHA-256 of the release tool's bytes this process runs. Each pool worker +#: refuses to start with a tool whose bytes differ (``release_tool``), so a +#: file changed while a run is under way cannot mix two versions' results. +#: The export probe executes the bytes it hashed (``__loaded_sha256__``). +_RELEASE_TOOL_SHA256 = ( + globals().get("__loaded_sha256__") + or hashlib.sha256(Path(__file__).read_bytes()).hexdigest() +) + + class _PostExportWorkerTracebackError(Exception): """The traceback of an exception a pool worker returned.""" @@ -7136,12 +7196,20 @@ def __init__( self._stream: Iterator[PostExportUnitResult] | None = None self._stream_units: tuple[PostExportUnit, ...] = () self._next_unit = 0 - # Why the pool stopped serving, once it has. + # Why the pool could not start, or stopped serving its second run. + self._start_failure: BaseException | None = None self._stopped: BaseException | None = None + # The settings the pool was started with. + self._pool_settings: WorkerPoolSettings | None = None self._opened: list[str] = [] self._simulations_opened: dict[str, int] = {} self._passes_asked: dict[tuple[str, int], int] = {} self._rules_counted: set[tuple[str, int]] = set() + # The last pass of each reformed simulation that failed: its keys and + # its failure, raised again if the consumer asks for them again. + self._failed_passes: dict[ + tuple[str, int], tuple[tuple[PostExportKey, ...], PostExportUnitFailure] + ] = {} # The reform unit whose passes are being served: (consumer, # simulation, unit, result). self._serving: tuple[str, int, PostExportUnit, PostExportUnitResult] | None = ( @@ -7192,13 +7260,15 @@ def _reform_units(self, consumer: str) -> tuple[PostExportUnit, ...]: def _start(self) -> None: """Run the merged baseline pass, then start the reform units. - A start that failed is not tried again: every later request names the - failure. + A start that failed is not tried again: every later consumer is + refused with :class:`PostExportPoolStoppedError`. A second run that + stops later refuses only what needs it (:meth:`_take`); what the + merged pass scored is still served. """ - if self._stopped is not None: - raise RuntimeError( - "Pooled post-export scoring stopped earlier; nothing more is served." - ) from self._stopped + if self._start_failure is not None: + raise PostExportPoolStoppedError( + "Pooled post-export scoring could not start; nothing is served." + ) from self._start_failure if self._started: return self._batches() @@ -7206,9 +7276,32 @@ def _start(self) -> None: try: self._start_pool() except BaseException as error: - self._stopped = error + self._start_failure = error raise + def _new_pool(self) -> WorkerPool: + pooling = self._pooling + if self._pool_settings is None: + self._pool_settings = _post_export_worker_settings( + pooling, workers=self._workers + ) + return WorkerPool( + self._pool_settings, + unit_function=score_post_export_unit, + initializer=start_post_export_worker, + initargs=( + __name__, + str(Path(__file__).resolve()), + _RELEASE_TOOL_SHA256, + self._batches().files, + self.n_batches, + pooling.microsimulation_cls, + pooling.dataset_from_frame, + pooling.reform_builder, + ), + describe_unit=_describe_post_export_unit, + ) + def _start_pool(self) -> None: merged = _ascending_period_plan( key for plan in self._unserved_baseline_plans.values() for key in plan @@ -7229,22 +7322,7 @@ def _start_pool(self) -> None: max(len(baseline_units), len(reform_units)), ), ) - pooling = self._pooling - self._pool = WorkerPool( - _post_export_worker_settings(pooling, workers=self._workers), - unit_function=score_post_export_unit, - initializer=start_post_export_worker, - initargs=( - __name__, - str(Path(__file__).resolve()), - self._batches().files, - self.n_batches, - pooling.microsimulation_cls, - pooling.dataset_from_frame, - pooling.reform_builder, - ), - describe_unit=_describe_post_export_unit, - ) + self._pool = self._new_pool() if baseline_units: self._run_merged_baseline(baseline_units, merged) if self._merged_baseline_failed: @@ -7282,6 +7360,7 @@ def _run_merged_baseline( key: [] for key in keys } failure: PostExportUnitFailure | None = None + unfinished: WorkerPoolUnitError | None = None results = self._pool.map(units) try: for unit, result in zip(units, results, strict=True): @@ -7303,19 +7382,32 @@ def _run_merged_baseline( batch=unit.batch_stop, batches=self.n_batches, ) + except WorkerPoolUnitError as error: + # A unit failed on every attempt: its worker ran out of memory, + # went over the cap or died. The serial scorer catches a + # MemoryError of its merged pass and falls back too; each + # consumer's own pass holds fewer keys per engine. + unfinished = error finally: results.close() - if failure is not None: + if failure is not None or unfinished is not None: # As the serial scorer: every consumer then scores its own plan. self._merged_baseline_failed = True del parts + reason = ( + f"{type(unfinished).__name__}: {unfinished}" + if unfinished is not None + else f"{failure.error_name}: {failure.message}" + ) print( - f"Post-export merged baseline plan failed ({failure.error_name}: " - f"{failure.message}); each consumer scores its own baseline plan " - "instead.", + f"Post-export merged baseline plan failed ({reason}); each " + "consumer scores its own baseline plan instead.", flush=True, ) _collect_family_garbage() + if unfinished is not None: + # The stopped run closed the pool; the rest needs another. + self._pool = self._new_pool() return self._merged_baseline = { key: _concatenate_post_export_parts(parts.pop(key)) for key in keys @@ -7354,8 +7446,9 @@ def _take(self, consumer: str, simulation: int | None): consumer asked out of its recorded order, which is refused. """ if self._stopped is not None: - raise RuntimeError( - "Pooled post-export scoring stopped earlier; nothing more is served." + raise PostExportPoolStoppedError( + f"{consumer}: pooled post-export scoring stopped earlier, so " + "nothing more that needs its workers is served." ) from self._stopped taken: list[tuple[PostExportUnit, PostExportUnitResult]] = [] while self._next_unit < len(self._stream_units): @@ -7476,9 +7569,41 @@ def _baseline_for( }, False def _open_reform_for(self, consumer: _PostExportConsumer, reform): + """Hand ``consumer`` its next reformed simulation, if it is the reform + the dry run recorded at that place. + + The consumer builds its reform with its own builder, which marks it + with the description it was built from; served by its place alone, a + consumer that opened its reforms in another order would get the + values of another reform. + """ self._finish_open_reform() - simulation = self._simulations_opened.get(consumer.name, 0) - self._simulations_opened[consumer.name] = simulation + 1 + name = consumer.name + simulation = self._simulations_opened.get(name, 0) + self._simulations_opened[name] = simulation + 1 + opened = self._requests[name].opened_reforms + if simulation >= len(opened): + raise RuntimeError( + f"{name} opened more reformed simulations than its engine-free " + f"dry run recorded ({len(opened)}); pooled post-export scoring " + "serves the recorded requests only." + ) + described = reform_description(reform) + if described is None: + raise RuntimeError( + f"{name} opened reformed simulation {simulation} with a reform that " + "carries no description of what it was built from; pooled " + "post-export scoring checks each reform against the one its " + "dry run recorded, so the consumer's own builder must build it." + ) + if described != opened[simulation]: + raise RuntimeError( + f"{name} opened reformed simulation {simulation} with a reform other " + "than the one its engine-free dry run recorded there; pooled " + "post-export scoring would serve it another reform's values, so " + "a consumer must open the same reforms in the same order whatever " + "values it gets back." + ) self._open_reform = _PooledPostExportReform(consumer, simulation) return self._open_reform @@ -7498,6 +7623,16 @@ def _reform_pass( name = consumer.name recorded = self._requests[name].passes_of(simulation) asked = self._passes_asked.get((name, simulation), 0) + failed = self._failed_passes.get((name, simulation)) + if failed is not None and failed[0] == tuple(keys): + # The serial scorer runs a failed pass again when it is asked + # again, and its rules were built already. + failure = failed[1] + if failure.stage == "rules": + _raise_post_export_worker_failure(failure) + if failure.stage != "responses": + consumer._count_reform_pass() + _raise_post_export_worker_failure(failure) if asked >= len(recorded) or recorded[asked] != tuple(keys): requested = ", ".join( f"{variable}@{period}" for variable, period, _ in keys @@ -7524,6 +7659,8 @@ def _reform_pass( self._serving = None outcome = result.outcomes[asked] failed = isinstance(outcome, PostExportUnitFailure) + if failed: + self._failed_passes[(name, simulation)] = (tuple(keys), outcome) if failed and outcome.stage == "rules": _raise_post_export_worker_failure(outcome) if (name, simulation) not in self._rules_counted: @@ -7557,6 +7694,7 @@ def _reform_pass( def execution_record(self) -> dict[str, object]: """How this scorer ran: run metadata, outside every output comparison.""" settings = self._pooling.settings + started = self._pool_settings record: dict[str, object] = { "mode": "pooled", "chosen_by": self._pooling.chosen_by, @@ -7566,7 +7704,11 @@ def execution_record(self) -> dict[str, object]: "max_units_per_worker": settings.max_units_per_worker, "max_attempts": settings.max_attempts, "max_units_ahead": settings.max_units_ahead, - "worker_environment_variables": sorted(settings.worker_environment or ()), + # The variables each worker was given: the settings' own and this + # process's lock-check record. + "worker_environment_variables": sorted( + (started or settings).worker_environment or () + ), "units": dict(self._units), "resources": self._pooling.resources, "report": None, diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index bf8b3d9a22..16e72d07a2 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -104,7 +104,13 @@ footprint and peak resident memory; each stage records the CPU time of the worker passes whose results reached it (``worker_cpu_seconds``), and the report's ``post_export_scoring.execution`` holds the pool's settings and -report (worker starts, failed attempts, peak worker memory). +report (worker starts, failed attempts, peak worker memory). A line is written +when the pass's results reach this process, so a pass whose results never do +(the stage stopped, or the scorer closed first) has none, and the remaining +passes of a stage that stopped early are written, and counted, under the stage +that passes over them. Once a unit has failed on every attempt the pool stops: +that stage records the failure, and a later stage that needs the pool records +that it could not run as the probe's own failure, not the release's. Usage:: @@ -1007,6 +1013,7 @@ def __init__(self, batch_frames: Sequence[Any], *, sampler) -> None: self._batches = batch_frames self._sampler = sampler self._cache: dict[str, tuple[np.ndarray, np.ndarray]] = {} + self._row_counts: dict[str, int] = {} def _build(self, entity: str) -> tuple[np.ndarray, np.ndarray]: if entity not in self._cache: @@ -1038,7 +1045,12 @@ def weights(self, entity: str) -> np.ndarray: return self._build(entity)[1] def n_rows(self, entity: str) -> int: - return int(sum(batch.n(entity) for batch in self._batches)) + # Each batch is read from its file, so count once per entity. + if entity not in self._row_counts: + self._row_counts[entity] = int( + sum(batch.n(entity) for batch in self._batches) + ) + return self._row_counts[entity] def row_weight_scale(engine_weights, household_weights) -> float | None: @@ -1571,6 +1583,8 @@ def __init__(self, sampler: RssSampler | None) -> None: self.current = "setup" self._worker_cpu = 0.0 self._worker_passes = 0 + #: The exception the last stage raised, if it raised. + self.last_error: Exception | None = None def add_worker_pass(self, cpu_seconds: float) -> None: self._worker_cpu += float(cpu_seconds) @@ -1580,6 +1594,7 @@ def run(self, name: str, fn: Callable[[], Mapping[str, Any]]) -> dict[str, Any]: self.current = name self._worker_cpu = 0.0 self._worker_passes = 0 + self.last_error = None before = self.sampler.reset() if self.sampler else 0 wall = time.perf_counter() cpu = time.process_time() @@ -1587,6 +1602,7 @@ def run(self, name: str, fn: Callable[[], Mapping[str, Any]]) -> dict[str, Any]: try: record = {"status": "completed", **dict(fn() or {})} except Exception as error: # every stage failure is a finding + self.last_error = error record = { "status": "error", "error": f"{type(error).__name__}: {error}", @@ -1926,7 +1942,14 @@ def __init__( self.scorer_options = dict(scorer_options or {}) # The release tool's ``_PostExportPooling``: with it the engine stages # are scored in the shared worker pool, as certification scores them; - # without it every pass runs in this process. + # without it every pass runs in this process. The pool settings name + # the workers' engine, so one given to the scorer as well is refused. + if post_export_pooling is not None and self.scorer_options: + raise ValueError( + "post_export_pooling names the workers' engine; scorer_options " + f"({', '.join(sorted(self.scorer_options))}) would be dropped. " + "Give the engine in the pool settings instead." + ) self.post_export_pooling = post_export_pooling self.load_frame = load_frame self.measure_entity = measure_entity @@ -2029,6 +2052,11 @@ def _write_report(self) -> None: def _stage(self, name: str, fn: Callable[[], Mapping[str, Any]], consequence): record = self.clock.run(name, fn) + stopped = getattr(self.builder, "PostExportPoolStoppedError", None) + if stopped is not None and isinstance(self.clock.last_error, stopped): + # The pool stopped in an earlier stage, whose record names why; + # this stage was not scored, which is not a release failure. + consequence = "probe integrity" self.report["stages"][name] = record if record["status"] == "error": self.verdicts.append( @@ -2499,14 +2527,30 @@ def _take_up(self) -> dict[str, Any]: # ---- the household-batched scorer ---------------------------------------- def _engine_consumers(self) -> dict[str, Callable[[], Any]]: - """The engine stages to run, in ``_main``'s order: for each, a function - that returns its consumer (a function of the ``simulate`` seam).""" + """The consumers whose plans the scorer registers, in ``_main``'s + order: for each, a function that returns its consumer (a function of + the ``simulate`` seam). + + The engine stages to run, and the two held-out reports, which + certification always registers: the probe does not report them, but + their keys are in certification's merged baseline pass, so the + probe's merged pass is that pass (its keys, its time and memory, and + its failure and fallback when a held-out report's key fails). + """ + builder = self.builder makers: dict[str, Callable[[], Any]] = { "reform_coverage_smoke": self._smoke_consumer, "reform_validation": lambda: self._validation_consumer()[0], - "demographics": lambda: self.builder._demographics_consumer, + "demographics": lambda: builder._demographics_consumer, } - return {name: make for name, make in makers.items() if name in self.stages} + consumers = {name: make for name, make in makers.items() if name in self.stages} + consumers["ssi_social_security_holdout"] = lambda: ( + builder._ssi_social_security_holdout_consumer + ) + consumers["medicare_irmaa_holdout"] = lambda: ( + builder._medicare_irmaa_holdout_consumer + ) + return consumers def _record_stage_requests(self) -> dict[str, Any]: """Each engine stage's recorded requests, from its own dry run. From d757040bbed9fd15e3740408264d228bc9f532a3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:30:18 +0400 Subject: [PATCH 07/26] Add a failing test for Route A exporting MICROCOSM_POST_EXPORT_WORKERS Route A sources route_a.env without exporting its values, so a MICROCOSM_POST_EXPORT_WORKERS set there would not reach certification, which reads it from its environment. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_route_a_driver.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py index db35583aea..ea1e5c90c2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py +++ b/packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py @@ -741,6 +741,22 @@ def test_driver_settings_reach_the_emitter_check_and_the_stages(tmp_path: Path) assert exported.stdout.decode().splitlines() == ["1", good] +def test_the_post_export_worker_setting_reaches_certification(tmp_path: Path) -> None: + """A settings-file ``MICROCOSM_POST_EXPORT_WORKERS`` is exported, so the + certify stage (which inherits the driver's environment) scores with the + workers it names, or serially.""" + + main, _ = _tiny_main(tmp_path, {_EMITTER_FLOOR_REL: _FLOOR}) + exported = run_driver_settings( + tmp_path, + {"MAIN": str(main), "MICROCOSM_POST_EXPORT_WORKERS": "serial"}, + "\nprintenv MICROCOSM_POST_EXPORT_WORKERS\n", + ) + assert exported.stdout.decode().splitlines() == ["serial"] + example = (ROUTE_A_TOOLS / "route_a.env.example").read_text(encoding="utf-8") + assert "MICROCOSM_POST_EXPORT_WORKERS" in example + + def test_the_emitter_floor_is_read_at_the_requested_commit(tmp_path: Path) -> None: """``--resolve`` reads the floor of the commit it checks, not of the checkout: an older commit with a lower floor accepts an older emitter.""" From d77e4e4127788e0b55fb231ffef23fb48db1352a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:31:10 +0400 Subject: [PATCH 08/26] Export MICROCOSM_POST_EXPORT_WORKERS from Route A's settings route_a.sh exports a value route_a.env sets, as it does the telemetry settings, so the certify stage, which the supervisor starts with the driver's environment, scores with the workers it names, or serially. The example settings file and the README describe the setting. Co-Authored-By: Claude Opus 5.5 --- tools/route_a/README.md | 6 ++++++ tools/route_a/route_a.env.example | 6 ++++++ tools/route_a/route_a.sh | 2 ++ 3 files changed, 14 insertions(+) diff --git a/tools/route_a/README.md b/tools/route_a/README.md index a1e8d3b971..1245f163ae 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -245,6 +245,12 @@ Every stage runs through the supervisor's admission check and limits: | certify | 110 | `RELEASE_RAM_GIB` (example: 50) | 45 | `CERTIFY_WALL_SECONDS` (default: 345600) | 2000000 | | publisher preflight | 24 | 16 | 22 | 7200 | 14400 | +The certify stage scores the post-export stages in a pool of worker +processes sized from the machine; `MICROCOSM_POST_EXPORT_WORKERS` in +`route_a.env` (a number of workers, or `serial`) overrides it, and the driver +exports it. On a machine under about 10.7 GiB, certification refuses to start +without it. The stage's 110 GiB RSS cap counts the workers too. + The driver waits up to `RESOURCE_WAIT_HOURS` (example: 12) for admission and retries a supervisor admission race every five minutes. Every config includes a 20 GiB disk floor that must persist for 180 seconds before `DISK_FLOOR` kills diff --git a/tools/route_a/route_a.env.example b/tools/route_a/route_a.env.example index 38dfd734ca..85750a263b 100644 --- a/tools/route_a/route_a.env.example +++ b/tools/route_a/route_a.env.example @@ -53,6 +53,12 @@ # meets the floor, but lets the release go on without telemetry when none # does. The driver exports either setting made here. # : "${MICROCOSM_TELEMETRY_REQUIRED:=1}" +# Certification scores the post-export stages in a pool of worker processes, +# sized from this machine: at most min(usable cores - 1, +# floor((0.75 x memory - 3 GiB) / 5 GiB)) workers, refused on a machine with +# no room for one. A positive number sets the workers, and serial scores in +# the certify stage's own process. The driver exports a setting made here. +# : "${MICROCOSM_POST_EXPORT_WORKERS:=auto}" : "${RELEASE_RAM_GIB:=50}" : "${RELEASE_WALL_SECONDS:=345600}" # 0 is the sole opt-out and restores --no-staging without a credential lookup. diff --git a/tools/route_a/route_a.sh b/tools/route_a/route_a.sh index bf063a80f0..41c867b199 100755 --- a/tools/route_a/route_a.sh +++ b/tools/route_a/route_a.sh @@ -88,6 +88,8 @@ esac # value so the stages see what --resolve checked. [ -z "${MICROCOSM_TELEMETRY_REQUIRED+set}" ] || export MICROCOSM_TELEMETRY_REQUIRED [ -z "${MICROCOSM_EMITTER_COMMAND+set}" ] || export MICROCOSM_EMITTER_COMMAND +# Certification reads its post-export scoring workers from its environment. +[ -z "${MICROCOSM_POST_EXPORT_WORKERS+set}" ] || export MICROCOSM_POST_EXPORT_WORKERS # --------------------------------------------------------------------------- # Inputs, resolved and hashed on this machine on 2026-09-23 (see status.md). From 839acb19c67363a4df0e7115946d64409752905f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:07:35 +0400 Subject: [PATCH 09/26] Add failing tests for review round 2 of pooled post-export scoring The tests require pooled scoring to: - raise a unit that fails on every attempt only in the consumer that asks for it, even when it fails while an earlier, slower unit is still running, and go on with the other units in a fresh pool; - refuse every consumer when no worker can start (a release tool digest other than the workers'), naming the refusal; - keep every pool's report in the execution record, with the merged baseline fallback's cause and units; - raise any earlier failed reform pass again when it is asked again. The export probe must read the pool setting only for a run with an engine stage, and record a held-out report whose dry run fails. The certification tests in test_us_fiscal_refresh_builder.py, which stub the scorer or certification's body, score serially whatever the test machine's memory. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_fiscal_refresh_builder.py | 14 +- .../us/test_us_post_export_pooled_scoring.py | 168 +++++++++++++++--- .../us/test_us_post_export_probe.py | 37 ++++ .../microcosm_build/us_post_export_pool.py | 9 +- 4 files changed, 199 insertions(+), 29 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index 49d7ce481e..f4ba0d3d75 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -52,6 +52,17 @@ _TEST_PATHS = paths_for("microcosm-build") +@pytest.fixture(autouse=True) +def _serial_post_export_scoring(monkeypatch): + """Certification here runs with the post-export scorer stood in for, or + with its body stubbed, so none of these tests sizes a worker pool from + the machine it runs on: certification refuses a machine with no room for + one worker unless MICROCOSM_POST_EXPORT_WORKERS names a count or serial, + and the stand-in scorer is the serial one (pooled scoring is the default, + tracker task 1.4 · 7).""" + monkeypatch.setenv("MICROCOSM_POST_EXPORT_WORKERS", "serial") + + def _load_builder_module(): root = _TEST_PATHS.repository path = root / "tools" / "build_us_fiscal_refresh_release.py" @@ -7295,9 +7306,6 @@ def close(self): captured["scorer_closed"] = True monkeypatch.setattr(builder, "_HouseholdBatchedPostExportScorer", WrittenH5Scorer) - # The stand-in is the serial scorer; certification uses it only when the - # operator asks for serial scoring (pooled scoring is the default). - monkeypatch.setenv("MICROCOSM_POST_EXPORT_WORKERS", "serial") read_population_structure = builder.population_structure_holdout_from_h5 def population_structure_from_h5(dataset_path, **kwargs): diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index f0bac32609..6f1452c82d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -47,6 +47,7 @@ ENGINE_LOG, FAIL_ON, MEMORY_KEYS, + SLOW, FakeMicrosimulation, build_fake_parameter_reform, build_fake_reform, @@ -84,7 +85,7 @@ def pooled_reforms(monkeypatch, builder): monkeypatch.setattr( builder, "geography_coverage_payload", lambda path: {"h5": Path(path).name} ) - for name in (FAIL_ON, COMPUTES, ENGINE_LOG, MEMORY_KEYS): + for name in (FAIL_ON, COMPUTES, ENGINE_LOG, MEMORY_KEYS, SLOW): monkeypatch.delenv(name, raising=False) @@ -276,6 +277,7 @@ def run(workers: int): "worker_environment_variables": [], "units": {"baseline": workers, "reform": reform_units}, "resources": None, + "merged_baseline_fallback": None, } assert report["units_completed"] == workers + reform_units assert report["failed_attempts"] == [] @@ -796,10 +798,27 @@ def test_the_probe_command_scores_as_certification_does(builder) -> None: probe_tool = _load_tool("probe_us_post_export", "probe_us_post_export.py") source = inspect.getsource(probe_tool.main) - chosen = source.index( - "post_export_pooling = load_builder()._post_export_pooling_from_environment()" - ) + chosen = source.index("post_export_pooling = post_export_pooling_for(stages)") assert chosen < source.index("report = probe_export(") + # Only a run with an engine stage reads the setting, so a probe of the + # frame-based stages alone runs on any machine. + calls = [] + + class Recording: + def _post_export_pooling_from_environment(self): + calls.append(True) + return "pooling" + + assert ( + probe_tool.post_export_pooling_for( + ("stored_inputs", "qrf_tail_concentration"), Recording() + ) + is None + ) + assert calls == [] + assert probe_tool.post_export_pooling_for(("demographics",), Recording()) == ( + "pooling" + ) (call,) = [ node for node in ast.walk(ast.parse(source)) @@ -919,6 +938,8 @@ def test_a_merged_pass_a_worker_cannot_finish_falls_back_as_the_serial_scorer_do consumers=consumers, ) + executions = [] + def run(scorer): try: outputs = {} @@ -929,7 +950,7 @@ def run(scorer): block = scorer.manifest_record() finally: scorer.close() - block.pop("execution") + executions.append(block.pop("execution")) return outputs, block serial = run(_serial_scorer(builder, plan, tmp_path / "serial")) @@ -937,18 +958,29 @@ def run(scorer): pooled = run(_pooled_scorer(builder, plan, tmp_path / "pooled", 1)) assert "merged baseline plan failed" in capsys.readouterr().out assert canonical_result_bytes(pooled) == canonical_result_bytes(serial) - - -def test_a_stopped_pool_still_serves_what_it_already_scored( + # The record keeps the failed pool's report: the attempts that failed and + # the workers they started, with the fallback's units. + execution = executions[1] + assert execution["merged_baseline_fallback"].startswith("WorkerPoolUnitError") + assert execution["units"] == {"baseline": 1, "reform": 0, "fallback_baseline": 2} + report = execution["report"] + assert report["pools"] == 2 + assert len(report["failed_attempts"]) == 2 + assert report["worker_starts"] >= 3 + assert report["units_completed"] == 2 + + +def test_a_unit_the_pool_cannot_finish_fails_its_own_consumer_alone( builder, pooled_reforms, tmp_path, monkeypatch, ) -> None: - """A reform unit that fails on every attempt stops the pool. A consumer - served from the merged pass's values is still served; one that needs the - pool is refused with a WorkerPoolError, which the held-out reports pass - on instead of recording an unavailable measurement.""" + """A reform unit that fails on every attempt fails the consumer that asks + for it, with the pool's error, which the held-out reports pass on instead + of recording an unavailable measurement. The pool then goes on in fresh + workers: a consumer served from the merged pass and one with a reform + unit of its own are served what the serial scorer serves them.""" monkeypatch.setenv(MEMORY_KEYS, "2") def prefetching(simulate): @@ -974,9 +1006,16 @@ def prefetching(simulate): ) serial = _serial_scorer(builder, plan, tmp_path / "serial") try: - expected = consumers["second"]( - serial.open_consumer("second", plan.baseline_plan("second")).simulate - ) + with pytest.raises(MemoryError): + prefetching( + serial.open_consumer("first", plan.baseline_plan("first")).simulate + ) + expected = { + name: consumers[name]( + serial.open_consumer(name, plan.baseline_plan(name)).simulate + ) + for name in ("second", "third") + } finally: serial.close() scorer = _pooled_scorer(builder, plan, tmp_path / "pooled", 1) @@ -984,13 +1023,92 @@ def prefetching(simulate): first = scorer.open_consumer("first", plan.baseline_plan("first")) with pytest.raises(WorkerPoolUnitError, match="MemoryError"): prefetching(first.simulate) - second = scorer.open_consumer("second", plan.baseline_plan("second")) - assert consumers["second"](second.simulate) == expected - scorer.finish_consumer(second) - third = scorer.open_consumer("third", plan.baseline_plan("third")) - with pytest.raises(builder.PostExportPoolStoppedError) as stopped: - consumers["third"](third.simulate) - assert isinstance(stopped.value, WorkerPoolError) + for name in ("second", "third"): + scoring = scorer.open_consumer(name, plan.baseline_plan(name)) + assert consumers[name](scoring.simulate) == expected[name], name + scorer.finish_consumer(scoring) + report = scorer.execution_record()["report"] + finally: + scorer.close() + assert report["pools"] == 2 + assert len(report["failed_attempts"]) == 2 + + +def test_a_later_units_failure_waits_for_its_own_consumer( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """Workers run ahead of the consumers. A later consumer's unit that fails + on every attempt while an earlier, slower unit is still running is that + later consumer's failure, not the earlier one's.""" + monkeypatch.setenv(MEMORY_KEYS, "2") + monkeypatch.setenv(SLOW, json.dumps({"snap": 15})) + + def prefetching(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + simulate(None).calculate("age", 2024) + reformed = simulate( + OTHER_REFORM if records_only else build_fake_reform(OTHER_REFORM) + ) + reformed.prefetch((("income_tax", 2024), ("ssi", 2024), ("wic", 2024))) + return reformed.calculate("income_tax", 2024).sum() + + consumers = { + "slow": _fixture_consumer(lambda total: [(FIXTURE_REFORM, [("snap", 2024)])]), + "failing": prefetching, + } + plan = builder._post_export_scoring_plan( + n_households=N_HOUSEHOLDS, + maximum_microsim_batch_size=BATCH_SIZE, + consumers=consumers, + ) + monkeypatch.setenv(SLOW, "{}") + serial = _serial_scorer(builder, plan, tmp_path / "serial") + try: + expected = consumers["slow"]( + serial.open_consumer("slow", plan.baseline_plan("slow")).simulate + ) + finally: + serial.close() + monkeypatch.setenv(SLOW, json.dumps({"snap": 15})) + scorer = _pooled_scorer(builder, plan, tmp_path / "pooled", 2) + try: + slow = scorer.open_consumer("slow", plan.baseline_plan("slow")) + assert consumers["slow"](slow.simulate) == expected + scorer.finish_consumer(slow) + failing = scorer.open_consumer("failing", plan.baseline_plan("failing")) + with pytest.raises(WorkerPoolUnitError, match="failing reformed simulation 0"): + prefetching(failing.simulate) + finally: + scorer.close() + + +def test_a_pool_that_cannot_start_refuses_every_consumer( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """Workers start only with the parent's release tool: given another + digest, none starts, and every consumer is refused with a WorkerPoolError + that names the refusal.""" + monkeypatch.setattr(builder, "_RELEASE_TOOL_SHA256", "0" * 64) + plan = builder._post_export_scoring_plan( + n_households=N_HOUSEHOLDS, + maximum_microsim_batch_size=BATCH_SIZE, + consumers={ + "first": _baseline_consumer("age"), + "second": _baseline_consumer("snap"), + }, + ) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + with pytest.raises(WorkerPoolError, match="SHA-256"): + scorer.open_consumer("first", plan.baseline_plan("first")) + with pytest.raises(builder.PostExportPoolStoppedError): + scorer.open_consumer("second", plan.baseline_plan("second")) finally: scorer.close() @@ -1010,9 +1128,9 @@ def consumer(simulate): FIXTURE_REFORM if records_only else build_fake_reform(FIXTURE_REFORM) ) errors = [] - for _ in range(2): + for period in (2024, 2024, 2025, 2024): try: - reformed.calculate("income_tax", 2024) + reformed.calculate("income_tax", period) except RuntimeError as error: errors.append(f"{type(error).__name__}: {error}") return errors @@ -1031,7 +1149,7 @@ def consumer(simulate): observed[mode] = (errors, scoring.reform_systems, scoring.reform_passes) finally: scorer.close() - assert len(observed["serial"][0]) == 2 + assert len(observed["serial"][0]) == 4 assert observed["pooled"] == observed["serial"] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py index 96ccade625..5b6efb6fa4 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py @@ -1501,3 +1501,40 @@ def test_engine_options_and_pool_settings_are_not_given_together( post_export_pooling=pooling, ) assert probe.scorer_options == {} + + +def test_a_held_out_report_whose_dry_run_fails_is_recorded( + probe_tool, builder, fake_reforms, chain, tmp_path, monkeypatch +) -> None: + """The held-out reports have no stage of their own in the probe; one whose + dry run fails leaves the probe's merged pass unlike certification's, which + the open_scorer stage records and a fidelity verdict names.""" + frame, path, receipt, _ = chain + monkeypatch.setattr(builder, "installed_us_engine", lambda: fixture_engine(frame)) + + def broken(simulate): + raise ValueError("fixture held-out dry run refused") + + monkeypatch.setattr(builder, "_ssi_social_security_holdout_consumer", broken) + report, _ = run_fixture_probe( + probe_tool, + builder, + path, + tmp_path / "probe", + receipt=receipt, + stages=("demographics",), + ) + record = report["stages"]["open_scorer"] + assert record["registered_consumers"] == ["demographics", "medicare_irmaa_holdout"] + assert record["unregistered_consumers"] == { + "ssi_social_security_holdout": "ValueError: fixture held-out dry run refused" + } + (verdict,) = [ + row + for row in report["verdicts"] + if row["stage"] == "open_scorer" + and "ssi_social_security_holdout" in row["check"] + ] + assert verdict["verdict"] == "error" + assert verdict["release_consequence"] == "fidelity of this probe to the release" + assert report["stages"]["demographics"]["status"] == "completed" diff --git a/test_support/microcosm_build/us_post_export_pool.py b/test_support/microcosm_build/us_post_export_pool.py index 43984f1ec4..31fe15cd72 100644 --- a/test_support/microcosm_build/us_post_export_pool.py +++ b/test_support/microcosm_build/us_post_export_pool.py @@ -18,7 +18,9 @@ - :data:`ENGINE_LOG`: a directory; each process appends one JSON line per engine construction and per calculation to ``.jsonl`` there; - :data:`MEMORY_KEYS`: the most distinct keys one engine computes before it - raises ``MemoryError``, as an engine that ran out of memory would. + raises ``MemoryError``, as an engine that ran out of memory would; +- :data:`SLOW`: JSON mapping a variable to the seconds each engine sleeps + before it computes that variable. Each fake reform carries the description it was built from, as the consumers' own builders mark the reforms they build. @@ -28,6 +30,7 @@ import json import os +import time from pathlib import Path from types import SimpleNamespace @@ -53,6 +56,7 @@ COMPUTES = "MICROCOSM_TEST_POST_EXPORT_COMPUTES" ENGINE_LOG = "MICROCOSM_TEST_POST_EXPORT_ENGINE_LOG" MEMORY_KEYS = "MICROCOSM_TEST_POST_EXPORT_MEMORY_KEYS" +SLOW = "MICROCOSM_TEST_POST_EXPORT_SLOW" #: Parameter paths a fake reform sets from a ``ParameterChangesReform`` #: payload, so a reform can move a behavioral-response parameter. @@ -185,6 +189,9 @@ def calculate(self, variable, period, map_to=None): limit = os.environ.get(MEMORY_KEYS) if limit and len(self.asked) > int(limit): raise MemoryError(f"fixture engine holds more than {limit} keys") + delay = json.loads(os.environ.get(SLOW) or "{}").get(variable) + if delay: + time.sleep(float(delay)) computes = json.loads(os.environ.get(COMPUTES) or "{}") for computed in (variable, *computes.get(variable, ())): self.known.setdefault(computed, set()).add(period) From 669b00f410e69bd5b16bdf33bbdd2a73fd466491 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:17:07 +0400 Subject: [PATCH 10/26] Fix review round 2 of pooled post-export scoring - Workers run ahead of the consumers, and the pool stops a run as soon as any unit in flight fails on every attempt. That unit's error is now kept and raised in the consumer that asks for it; the units from the one due, without it, go on in a fresh pool (_result_of). A consumer's own failed unit raises WorkerPoolUnitError; a pool whose workers cannot start refuses every later consumer with PostExportPoolStoppedError. - The execution record keeps the report of every pool the scorer ran (worker starts, failed attempts, the largest peak), why the merged baseline pass fell back, and the fallback's units. - Every failed reform pass is kept, so asking for any of them again raises its error, as the serial scorer does. - The export probe reads the pool setting only for a run with an engine stage, records a held-out report whose dry run fails as a fidelity verdict, and its docstring says how a failed unit and a pool that cannot start are recorded. - The release build rule says the merged pass's units and reform validation's own pass are unmeasured against the 5 GiB cap, and the Route A README that the worker count is not sized to the certify stage's 110 GiB RSS limit. Co-Authored-By: Claude Opus 5.5 --- .../us-pooled-post-export-scoring.changed.md | 2 +- docs/us-release-build-rule.md | 28 ++-- tools/build_us_fiscal_refresh_release.py | 121 +++++++++++++++--- tools/probe_us_post_export.py | 58 ++++++++- tools/route_a/README.md | 6 +- 5 files changed, 177 insertions(+), 38 deletions(-) diff --git a/changelog.d/us-pooled-post-export-scoring.changed.md b/changelog.d/us-pooled-post-export-scoring.changed.md index 856fbc9e5e..324ed1e598 100644 --- a/changelog.d/us-pooled-post-export-scoring.changed.md +++ b/changelog.d/us-pooled-post-export-scoring.changed.md @@ -1 +1 @@ -US certification scores post-export stages in the shared worker pool by default (`_PooledPostExportScorer`), with tracker decision 1.4 · 6's settings: `MICROCOSM_POST_EXPORT_WORKERS` unset or `auto` starts at most min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers and refuses, before the build is placed, a machine with no room for one; a positive number starts that many, and `serial` scores in the certifying process as before; each worker is replaced after 2 units and capped at max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers). In the pool, the merged baseline pass is split into one range of household batches per worker, each reformed simulation's recorded passes are one unit, and each post-export stage then runs in the certifying process over the results, refusing any request, or any reform, its engine-free dry run did not record; the smoke check's and reform validation's builders mark each reform with the description it was built from. A merged baseline unit the pool cannot finish falls back to each stage's own pass, as a serial `MemoryError` does, and a worker refuses a release tool whose bytes differ from the certifying process's. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's merged baseline pass instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan and the held-out reports' (certification's shared baseline pass), can score in the pool and writes each worker pass's time and memory to `passes.jsonl`; its household row map reads one batch file at a time. +US certification scores post-export stages in the shared worker pool by default (`_PooledPostExportScorer`), with tracker decision 1.4 · 6's settings: `MICROCOSM_POST_EXPORT_WORKERS` unset or `auto` starts at most min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers and refuses, before the build is placed, a machine with no room for one; a positive number starts that many, and `serial` scores in the certifying process as before; each worker is replaced after 2 units and capped at max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers). In the pool, the merged baseline pass is split into one range of household batches per worker, each reformed simulation's recorded passes are one unit, and each post-export stage then runs in the certifying process over the results, refusing any request, or any reform, its engine-free dry run did not record; the smoke check's and reform validation's builders mark each reform with the description it was built from. A merged baseline unit the pool cannot finish falls back to each stage's own pass, as a serial `MemoryError` does; any other unit that fails on every attempt fails the stage that asks for it, and the pool goes on with the rest in fresh workers; a worker refuses a release tool whose bytes differ from the certifying process's. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's merged baseline pass instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan and the held-out reports' (certification's shared baseline pass), can score in the pool and writes each worker pass's time and memory to `passes.jsonl`; its household row map reads one batch file at a time. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 02bea223f0..462a968c85 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -547,13 +547,16 @@ one Microsimulation over the whole file. process raises it when the stage asks for that pass, where the serial scorer would have raised, as an error with the worker's exception's class name and message, so a held-out report that records the error records the - same text. A changed batch file raises `PostExportBatchFileError`, and a - pool that cannot score (a unit after the shared pass that failed on every - attempt, a worker that could not start) raises `WorkerPoolError`; both - stop certification, the held-out reports included. After that the pool - serves nothing more that needs its workers - (`PostExportPoolStoppedError`, a `WorkerPoolError`), but a stage served - from the shared pass's values is still served. + same text. A changed batch file raises `PostExportBatchFileError`. A unit + after the shared pass that failed on every attempt (its worker ran out of + memory, went over its cap or died) raises `WorkerPoolUnitError` in the + stage that asks for it, even when it failed while workers were still + running an earlier stage's units, and the pool goes on with the other + units in fresh workers. A pool whose workers cannot start refuses every + stage that needs it (`PostExportPoolStoppedError`); a stage served from + the shared pass's values is still served. Each of these is a + `WorkerPoolError` and stops certification, the held-out reports included, + where the serial scorer, which has no memory cap, may have finished. - Each stage then runs as in the serial path and builds its own reforms (the smoke records each list edit's resolved lists from its own). Its baseline is served its recorded plan, and each reformed simulation its recorded @@ -577,9 +580,16 @@ one Microsimulation over the whole file. mix two versions' results (the microcosm packages are not checked). - The manifests' `post_export_scoring` block records how scoring ran under `execution`: `{"mode": "serial"}`, or the pool's settings, how the worker - count was chosen, the plan's memory and core readings, unit counts and the - pool's report (worker starts, failed attempts, peak worker memory). That + count was chosen, the plan's memory and core readings, unit counts, why + the shared pass fell back if it did, and the report of every pool the + scorer ran (worker starts, failed attempts, peak worker memory). That record is run metadata, outside every output comparison (decision 1.1 · 1). + - The 5 GiB per worker comes from reform passes (1.4 · 6's one-batch check + peaked at about 3.5-4.7 GiB over two reform passes of 2,000 households). + The shared pass's units compute about 97 keys per batch engine and + reform validation's own pass 75, which nothing has measured yet; the + pooled export probe on a 5% sample reports each pool's peak worker + memory and every attempt the cap stopped. - Each batch engine keeps policyengine-us's projection of the release year to its last CPI-U year (2035), because the plans request keys in later years (reform validation reaches past 2025). The build's own simulations hold diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 65ee80d2f4..97056ce7be 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -7199,16 +7199,25 @@ def __init__( # Why the pool could not start, or stopped serving its second run. self._start_failure: BaseException | None = None self._stopped: BaseException | None = None - # The settings the pool was started with. + # The settings the pool was started with, and the reports of the pools + # replaced since (a pool closes when a unit fails on every attempt). self._pool_settings: WorkerPoolSettings | None = None + self._replaced_reports: list[WorkerPoolReport] = [] + self._merged_fallback_reason: str | None = None + # The second run's units still to be handed back by the current pool, + # as positions in ``_stream_units``, and the units that failed on + # every attempt, by position, each raised when its consumer asks. + self._stream_positions: list[int] = [] + self._unit_errors: dict[int, WorkerPoolUnitError] = {} self._opened: list[str] = [] self._simulations_opened: dict[str, int] = {} self._passes_asked: dict[tuple[str, int], int] = {} self._rules_counted: set[tuple[str, int]] = set() - # The last pass of each reformed simulation that failed: its keys and - # its failure, raised again if the consumer asks for them again. + # Each pass of a reformed simulation that failed: its keys and its + # failure, raised again if the consumer asks for those keys again. self._failed_passes: dict[ - tuple[str, int], tuple[tuple[PostExportKey, ...], PostExportUnitFailure] + tuple[str, int], + list[tuple[tuple[PostExportKey, ...], PostExportUnitFailure]], ] = {} # The reform unit whose passes are being served: (consumer, # simulation, unit, result). @@ -7280,7 +7289,12 @@ def _start(self) -> None: raise def _new_pool(self) -> WorkerPool: + """A pool with this scorer's settings; a pool it replaces (closed by a + unit that failed on every attempt) leaves its report behind.""" pooling = self._pooling + if self._pool is not None: + self._pool.close() + self._replaced_reports.append(self._pool.report()) if self._pool_settings is None: self._pool_settings = _post_export_worker_settings( pooling, workers=self._workers @@ -7336,10 +7350,12 @@ def _start_pool(self) -> None: ) layout.extend(self._reform_units(name)) stream_units = tuple(layout) + self._units["fallback_baseline"] = len(stream_units) - len(reform_units) else: stream_units = reform_units if stream_units: self._stream_units = stream_units + self._stream_positions = list(range(len(stream_units))) self._stream = self._pool.map(stream_units) def _run_merged_baseline( @@ -7399,6 +7415,7 @@ def _run_merged_baseline( if unfinished is not None else f"{failure.error_name}: {failure.message}" ) + self._merged_fallback_reason = reason print( f"Post-export merged baseline plan failed ({reason}); each " "consumer scores its own baseline plan instead.", @@ -7458,13 +7475,19 @@ def _take(self, consumer: str, simulation: int | None): break if not ours and unit.consumer not in self._opened: break + index = self._next_unit self._next_unit += 1 try: - result = next(self._stream) + result = self._result_of(index) + except WorkerPoolUnitError: + if ours: + # This consumer's own unit failed on every attempt. + raise + # A unit of a consumer that stopped before asking for it. + continue except BaseException as error: - # The pool stopped (a unit failed on every attempt, a worker - # could not start, the scorer closed): nothing after it can - # be served. + # The pool cannot go on (a worker could not start, the scorer + # closed): nothing after this can be served. self._stopped = error raise self._report_timing(unit, result) @@ -7483,6 +7506,34 @@ def _take(self, consumer: str, simulation: int | None): ) return taken + def _result_of(self, index: int) -> PostExportUnitResult: + """The result of the second run's unit at ``index``, the next one due. + + Workers run ahead of the consumers, and the pool stops a run as soon + as any unit in flight has failed on every attempt, which may be a + later consumer's. That unit's error is kept and raised when its own + consumer asks for it; the units from ``index`` on, without it, go on + in a fresh pool, as the serial scorer would score them. + """ + error = self._unit_errors.pop(index, None) + if error is not None: + raise error + try: + return next(self._stream) + except WorkerPoolUnitError as failed_unit: + failed = self._stream_positions[failed_unit.unit_index] + self._unit_errors[failed] = failed_unit + self._stream_positions = [ + position + for position in range(index, len(self._stream_units)) + if position not in self._unit_errors + ] + self._pool = self._new_pool() + self._stream = self._pool.map( + [self._stream_units[position] for position in self._stream_positions] + ) + return self._result_of(index) + # ---- consumers --------------------------------------------------------- def open_consumer( @@ -7623,11 +7674,21 @@ def _reform_pass( name = consumer.name recorded = self._requests[name].passes_of(simulation) asked = self._passes_asked.get((name, simulation), 0) - failed = self._failed_passes.get((name, simulation)) - if failed is not None and failed[0] == tuple(keys): + failure = next( + ( + failed + for failed_keys, failed in self._failed_passes.get( + (name, simulation), () + ) + if failed_keys == tuple(keys) + ), + None, + ) + if failure is not None: # The serial scorer runs a failed pass again when it is asked - # again, and its rules were built already. - failure = failed[1] + # again, and its rules were built already. (A request for some of + # a failed pass's keys is a pass the dry run did not record, and + # is refused below.) if failure.stage == "rules": _raise_post_export_worker_failure(failure) if failure.stage != "responses": @@ -7660,7 +7721,9 @@ def _reform_pass( outcome = result.outcomes[asked] failed = isinstance(outcome, PostExportUnitFailure) if failed: - self._failed_passes[(name, simulation)] = (tuple(keys), outcome) + self._failed_passes.setdefault((name, simulation), []).append( + (tuple(keys), outcome) + ) if failed and outcome.stage == "rules": _raise_post_export_worker_failure(outcome) if (name, simulation) not in self._rules_counted: @@ -7711,10 +7774,16 @@ def execution_record(self) -> dict[str, object]: ), "units": dict(self._units), "resources": self._pooling.resources, + # Why the merged baseline pass fell back to each consumer's own + # pass, if it did. + "merged_baseline_fallback": self._merged_fallback_reason, "report": None, } + reports = [*self._replaced_reports] if self._pool is not None: - record["report"] = _worker_pool_report_record(self._pool.report()) + reports.append(self._pool.report()) + if reports: + record["report"] = _worker_pool_reports_record(reports) return record def close(self) -> None: @@ -7730,19 +7799,31 @@ def close(self) -> None: super().close() -def _worker_pool_report_record(report: WorkerPoolReport) -> dict[str, object]: +def _worker_pool_reports_record( + reports: Sequence[WorkerPoolReport], +) -> dict[str, object]: + """The reports of every pool a scorer ran, in order, as one record.""" + peaks = [ + report.peak_worker_memory_bytes + for report in reports + if report.peak_worker_memory_bytes is not None + ] return { - "worker_starts": report.worker_starts, - "units_completed": report.units_completed, - "max_live_workers": report.max_live_workers, - "peak_worker_memory_bytes": report.peak_worker_memory_bytes, - "workers_stopped_over_cap": report.workers_stopped_over_cap, + "pools": len(reports), + "worker_starts": sum(report.worker_starts for report in reports), + "units_completed": sum(report.units_completed for report in reports), + "max_live_workers": max(report.max_live_workers for report in reports), + "peak_worker_memory_bytes": max(peaks) if peaks else None, + "workers_stopped_over_cap": sum( + report.workers_stopped_over_cap for report in reports + ), "failed_attempts": [ { "unit": attempt.label, "attempt": attempt.attempt, "cause": attempt.cause, } + for report in reports for attempt in report.failed_attempts ], } diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index 16e72d07a2..222ddbb3eb 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -19,8 +19,11 @@ 3. ``take_up_participation``: ``us_take_up_participation_diagnostics`` and the stale count-calibrated check ``_main`` raises on. 4. ``reform_coverage_smoke``: the release's smoke consumer on the - household-batched scorer (``_HouseholdBatchedPostExportScorer``), from the - baseline plan the engine-free dry run records. + household-batched scorer, from the plan the engine-free dry run records: + in the shared worker pool (``_PooledPostExportScorer``), as the command + scores by default, or in this process + (``_HouseholdBatchedPostExportScorer``, with + ``MICROCOSM_POST_EXPORT_WORKERS=serial``). 5. ``reform_validation``: ``_reform_validation_consumer``. With the build's ``calibration_diagnostics.json`` its in-sample JCT rows come from the fit, as in the release; without it they are simulated (one extra reform pass @@ -108,9 +111,12 @@ when the pass's results reach this process, so a pass whose results never do (the stage stopped, or the scorer closed first) has none, and the remaining passes of a stage that stopped early are written, and counted, under the stage -that passes over them. Once a unit has failed on every attempt the pool stops: -that stage records the failure, and a later stage that needs the pool records -that it could not run as the probe's own failure, not the release's. +that passes over them. A unit that fails on every attempt fails the stage that +asks for it (a range of the merged baseline pass instead makes every stage +score its own baseline pass), and the pool goes on with the other units in +fresh workers; if no worker can start, each later stage that needs the pool +records that it could not run as the probe's own failure, not the +release's. Usage:: @@ -2621,6 +2627,25 @@ def _open_scorer(self) -> dict[str, Any]: f"at least {MINIMUM_BATCHES}." ) self.scorer = scorer + # A held-out report has no stage here to raise its dry run's error, so + # the probe's merged pass then differs from certification's (whose + # plan would fail before its export). + unregistered = { + name: f"{type(error).__name__}: {error}" + for name, error in self.stage_request_errors.items() + if name not in self.stages + } + for name, error in unregistered.items(): + self._add( + "open_scorer", + f"{name}'s plan is registered as in certification", + "error", + AUTHORITATIVE, + f"its engine-free dry run failed ({error}), so the probe's merged " + "baseline pass leaves out its keys; the release's plan would " + "fail before its export", + "fidelity of this probe to the release", + ) return { "mode": "serial" if self.post_export_pooling is None else "pooled", "n_households": scorer.n_households, @@ -2628,6 +2653,7 @@ def _open_scorer(self) -> dict[str, Any]: "max_batch_households": scorer.max_batch_households, "maximum_batch_size": scorer.maximum_batch_size, "registered_consumers": list(plan.baseline_plans), + "unregistered_consumers": unregistered, } def _record_worker_pass(self, row: Mapping[str, Any]) -> None: @@ -3340,6 +3366,23 @@ def reference_build_record(release_dir: Path | None) -> Path | None: return None +#: The stages that score the export on the engine, in ``_main``'s order. +ENGINE_STAGES = ("reform_coverage_smoke", "reform_validation", "demographics") + + +def post_export_pooling_for(stages: Sequence[str], builder=None): + """Certification's post-export pool for a run of ``stages``, or ``None``. + + Read from ``MICROCOSM_POST_EXPORT_WORKERS`` and this machine as + certification reads it (``_post_export_pooling_from_environment``), and + only when an engine stage runs: a probe of the frame-based stages alone + starts no pool, so it runs on any machine. + """ + if not any(stage in ENGINE_STAGES for stage in stages): + return None + return (builder or load_builder())._post_export_pooling_from_environment() + + def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--export", type=Path, required=True, help="H5 to score") @@ -3487,7 +3530,8 @@ def main(argv: Sequence[str] | None = None) -> int: # As certification: pooled scoring unless MICROCOSM_POST_EXPORT_WORKERS # says serial; a bad setting, or a machine too small for one worker, # stops here, before the export is loaded. - post_export_pooling = load_builder()._post_export_pooling_from_environment() + stages = tuple(stage.strip() for stage in args.stages.split(",") if stage) + post_export_pooling = post_export_pooling_for(stages) report = probe_export( args.export, args.out, @@ -3495,7 +3539,7 @@ def main(argv: Sequence[str] | None = None) -> int: receipt_path=receipt_path, source_export=args.source_export, source_settlement=not args.no_source_settlement, - stages=tuple(stage.strip() for stage in args.stages.split(",") if stage), + stages=stages, batch_size=args.batch_size, target_surface=surface["mode"], target_surface_source=surface["source"], diff --git a/tools/route_a/README.md b/tools/route_a/README.md index 1245f163ae..8dd8dcc3a8 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -249,7 +249,11 @@ The certify stage scores the post-export stages in a pool of worker processes sized from the machine; `MICROCOSM_POST_EXPORT_WORKERS` in `route_a.env` (a number of workers, or `serial`) overrides it, and the driver exports it. On a machine under about 10.7 GiB, certification refuses to start -without it. The stage's 110 GiB RSS cap counts the workers too. +without it. The stage's 110 GiB RSS cap counts the workers too, and the +worker count is not sized to it: the plan's peak is 3 GiB plus 5 GiB per +worker (88 GiB for 17 workers on the 128 GiB build Mac), so on a machine +where the formula gives more than 21 workers (about 151 GiB and 23 usable +cores or more), set `MICROCOSM_POST_EXPORT_WORKERS` to 21 or fewer. The driver waits up to `RESOURCE_WAIT_HOURS` (example: 12) for admission and retries a supervisor admission race every five minutes. Every config includes From b81cd6cf558c42929e5f51d164e7b9ed5dd13f2a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:39:02 +0400 Subject: [PATCH 11/26] Add failing tests for review round 3 of pooled post-export scoring The tests require that: - a later unit's failure, kept until its consumer asks for it, holds none of the stopped run's frames, and the look-ahead case is exercised every time (the earlier unit's engine waits until the later unit has failed twice); - a consumer that asks again for its own failed unit gets that unit's error again, and each failed attempt in the record names its pool; - a stage's own baseline pass, after the merged pass failed, raises its first problem in batch order, as the serial scorer does, even when a later range also fails on every attempt. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pooled_scoring.py | 99 +++++++++++++++++-- .../microcosm_build/us_post_export_pool.py | 27 ++++- 2 files changed, 117 insertions(+), 9 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index 6f1452c82d..e451d93c58 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -46,8 +46,11 @@ COMPUTES, ENGINE_LOG, FAIL_ON, + FAIL_ON_HOUSEHOLDS, MEMORY_KEYS, + MEMORY_ON_HOUSEHOLDS, SLOW, + WAIT_FOR, FakeMicrosimulation, build_fake_parameter_reform, build_fake_reform, @@ -85,7 +88,16 @@ def pooled_reforms(monkeypatch, builder): monkeypatch.setattr( builder, "geography_coverage_payload", lambda path: {"h5": Path(path).name} ) - for name in (FAIL_ON, COMPUTES, ENGINE_LOG, MEMORY_KEYS, SLOW): + for name in ( + FAIL_ON, + COMPUTES, + ENGINE_LOG, + MEMORY_KEYS, + SLOW, + WAIT_FOR, + FAIL_ON_HOUSEHOLDS, + MEMORY_ON_HOUSEHOLDS, + ): monkeypatch.delenv(name, raising=False) @@ -1021,8 +1033,15 @@ def prefetching(simulate): scorer = _pooled_scorer(builder, plan, tmp_path / "pooled", 1) try: first = scorer.open_consumer("first", plan.baseline_plan("first")) - with pytest.raises(WorkerPoolUnitError, match="MemoryError"): - prefetching(first.simulate) + first.simulate(None).calculate("age", 2024) + reformed = first.simulate(build_fake_reform(FIXTURE_REFORM)) + keys = (("income_tax", 2024), ("snap", 2024), ("ssi", 2024)) + with pytest.raises(WorkerPoolUnitError, match="MemoryError") as failed: + reformed.prefetch(keys) + # Asked again, the unit's own error again, not a refusal of the order. + with pytest.raises(WorkerPoolUnitError) as again: + reformed.prefetch(keys) + assert str(again.value) == str(failed.value) for name in ("second", "third"): scoring = scorer.open_consumer(name, plan.baseline_plan(name)) assert consumers[name](scoring.simulate) == expected[name], name @@ -1032,6 +1051,7 @@ def prefetching(simulate): scorer.close() assert report["pools"] == 2 assert len(report["failed_attempts"]) == 2 + assert [attempt["pool"] for attempt in report["failed_attempts"]] == [0, 0] def test_a_later_units_failure_waits_for_its_own_consumer( @@ -1041,10 +1061,13 @@ def test_a_later_units_failure_waits_for_its_own_consumer( monkeypatch, ) -> None: """Workers run ahead of the consumers. A later consumer's unit that fails - on every attempt while an earlier, slower unit is still running is that - later consumer's failure, not the earlier one's.""" + on every attempt while an earlier unit is still running is that later + consumer's failure, not the earlier one's: the earlier unit's engine + waits until the later unit has failed twice, then runs again in a fresh + pool, and the stored error holds none of the stopped run's frames.""" + import threading + monkeypatch.setenv(MEMORY_KEYS, "2") - monkeypatch.setenv(SLOW, json.dumps({"snap": 15})) def prefetching(simulate): records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True @@ -1064,7 +1087,6 @@ def prefetching(simulate): maximum_microsim_batch_size=BATCH_SIZE, consumers=consumers, ) - monkeypatch.setenv(SLOW, "{}") serial = _serial_scorer(builder, plan, tmp_path / "serial") try: expected = consumers["slow"]( @@ -1072,17 +1094,36 @@ def prefetching(simulate): ) finally: serial.close() - monkeypatch.setenv(SLOW, json.dumps({"snap": 15})) + released = tmp_path / "released" + monkeypatch.setenv(WAIT_FOR, json.dumps({"snap": str(released)})) scorer = _pooled_scorer(builder, plan, tmp_path / "pooled", 2) + stop = threading.Event() try: slow = scorer.open_consumer("slow", plan.baseline_plan("slow")) + first_pool = scorer._pool + + def release_once_the_later_unit_failed(): + while not stop.wait(0.2): + if len(first_pool.report().failed_attempts) >= 2: + released.touch() + return + + watcher = threading.Thread(target=release_once_the_later_unit_failed) + watcher.start() assert consumers["slow"](slow.simulate) == expected scorer.finish_consumer(slow) + assert all( + error.__traceback__ is None for error in scorer._unit_errors.values() + ) failing = scorer.open_consumer("failing", plan.baseline_plan("failing")) with pytest.raises(WorkerPoolUnitError, match="failing reformed simulation 0"): prefetching(failing.simulate) + report = scorer.execution_record()["report"] finally: + stop.set() scorer.close() + assert released.exists() + assert report["pools"] == 2 def test_a_pool_that_cannot_start_refuses_every_consumer( @@ -1231,3 +1272,45 @@ def test_workers_check_they_run_the_parents_release_tool(builder) -> None: tool = Path(builder.__file__) assert builder._RELEASE_TOOL_SHA256 == hashlib.sha256(tool.read_bytes()).hexdigest() + + +def test_a_stage_own_baseline_raises_its_first_problem_in_batch_order( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """After the merged pass fails, a stage's own baseline pass that raises in + its first batch raises that error, as the serial scorer does, even when a + later range of it also fails on every attempt in the pool.""" + monkeypatch.setenv(FAIL_ON_HOUSEHOLDS, json.dumps({"snap": [1]})) + monkeypatch.setenv(MEMORY_ON_HOUSEHOLDS, json.dumps({"snap": [7]})) + consumers = { + "first": _baseline_consumer("age", "income_tax"), + "second": _baseline_consumer("age", "snap"), + } + plan = builder._post_export_scoring_plan( + n_households=N_HOUSEHOLDS, + maximum_microsim_batch_size=BATCH_SIZE, + consumers=consumers, + ) + + def run(scorer): + observed = {} + try: + for name, consumer in consumers.items(): + try: + scoring = scorer.open_consumer(name, plan.baseline_plan(name)) + except (RuntimeError, MemoryError) as error: + observed[name] = f"{type(error).__name__}: {error}" + continue + observed[name] = consumer(scoring.simulate) + finally: + scorer.close() + return observed + + monkeypatch.setenv(MEMORY_ON_HOUSEHOLDS, "{}") + serial = run(_serial_scorer(builder, plan, tmp_path / "serial")) + assert serial["second"] == "RuntimeError: fixture engine refuses snap" + monkeypatch.setenv(MEMORY_ON_HOUSEHOLDS, json.dumps({"snap": [7]})) + assert run(_pooled_scorer(builder, plan, tmp_path / "pooled", 2)) == serial diff --git a/test_support/microcosm_build/us_post_export_pool.py b/test_support/microcosm_build/us_post_export_pool.py index 31fe15cd72..910d3f89cd 100644 --- a/test_support/microcosm_build/us_post_export_pool.py +++ b/test_support/microcosm_build/us_post_export_pool.py @@ -20,7 +20,12 @@ - :data:`MEMORY_KEYS`: the most distinct keys one engine computes before it raises ``MemoryError``, as an engine that ran out of memory would; - :data:`SLOW`: JSON mapping a variable to the seconds each engine sleeps - before it computes that variable. + before it computes that variable; +- :data:`WAIT_FOR`: JSON mapping a variable to a file each engine waits for + (two minutes at most) before it computes that variable; +- :data:`FAIL_ON_HOUSEHOLDS` and :data:`MEMORY_ON_HOUSEHOLDS`: JSON mapping a + variable to household ids; an engine whose batch holds one of them raises + ``RuntimeError`` or ``MemoryError`` for that variable. Each fake reform carries the description it was built from, as the consumers' own builders mark the reforms they build. @@ -57,6 +62,14 @@ ENGINE_LOG = "MICROCOSM_TEST_POST_EXPORT_ENGINE_LOG" MEMORY_KEYS = "MICROCOSM_TEST_POST_EXPORT_MEMORY_KEYS" SLOW = "MICROCOSM_TEST_POST_EXPORT_SLOW" +WAIT_FOR = "MICROCOSM_TEST_POST_EXPORT_WAIT_FOR" +FAIL_ON_HOUSEHOLDS = "MICROCOSM_TEST_POST_EXPORT_FAIL_ON_HOUSEHOLDS" +MEMORY_ON_HOUSEHOLDS = "MICROCOSM_TEST_POST_EXPORT_MEMORY_ON_HOUSEHOLDS" + + +def _households_for(variable: str, name: str) -> set[int]: + return set(json.loads(os.environ.get(name) or "{}").get(variable, ())) + #: Parameter paths a fake reform sets from a ``ParameterChangesReform`` #: payload, so a reform can move a behavioral-response parameter. @@ -192,6 +205,18 @@ def calculate(self, variable, period, map_to=None): delay = json.loads(os.environ.get(SLOW) or "{}").get(variable) if delay: time.sleep(float(delay)) + awaited = json.loads(os.environ.get(WAIT_FOR) or "{}").get(variable) + if awaited: + deadline = time.monotonic() + 120 + while not Path(awaited).exists() and time.monotonic() < deadline: + time.sleep(0.1) + households = set( + int(value) for value in frame.table("household")["household_id"] + ) + if households & _households_for(variable, FAIL_ON_HOUSEHOLDS): + raise RuntimeError(f"fixture engine refuses {variable}") + if households & _households_for(variable, MEMORY_ON_HOUSEHOLDS): + raise MemoryError(f"fixture engine holds too much for {variable}") computes = json.loads(os.environ.get(COMPUTES) or "{}") for computed in (variable, *computes.get(variable, ())): self.known.setdefault(computed, set()).add(period) From bcf9863c83e718af5085dc7f5e08586c0ffc9b12 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:44:31 +0400 Subject: [PATCH 12/26] Fix review round 3 of pooled post-export scoring - A later unit's failure is kept as a copy without its traceback, whose frames held the stopped run's finished results while the fresh pool computed them again, and the fresh pool starts outside the handler. No pool is started when no unit is left. - _take returns a consumer's own failed unit with its error, so a stage's own baseline pass raises its first problem in batch order, as the serial scorer does, and a reformed simulation whose unit failed raises that error again when it is asked again. - Each failed attempt in the execution record names its pool. - The release build rule says the units in flight start again in the fresh pool. Co-Authored-By: Claude Opus 5.5 --- docs/us-release-build-rule.md | 5 +- tools/build_us_fiscal_refresh_release.py | 72 ++++++++++++++++++------ 2 files changed, 60 insertions(+), 17 deletions(-) diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 462a968c85..dd4a86a9a1 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -552,7 +552,10 @@ one Microsimulation over the whole file. memory, went over its cap or died) raises `WorkerPoolUnitError` in the stage that asks for it, even when it failed while workers were still running an earlier stage's units, and the pool goes on with the other - units in fresh workers. A pool whose workers cannot start refuses every + units in fresh workers. The shared pool stops a run at such a failure, + so the units then in flight, the one due among them, start again in the + fresh pool. In a stage's own baseline pass the first range in batch + order that failed, either way, is the error raised. A pool whose workers cannot start refuses every stage that needs it (`PostExportPoolStoppedError`); a stage served from the shared pass's values is still served. Each of these is a `WorkerPoolError` and stops certification, the held-out reports included, diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 97056ce7be..f76f657837 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -7209,6 +7209,8 @@ def __init__( # every attempt, by position, each raised when its consumer asks. self._stream_positions: list[int] = [] self._unit_errors: dict[int, WorkerPoolUnitError] = {} + # Each reformed simulation whose unit failed on every attempt. + self._unfinished_units: dict[tuple[str, int], WorkerPoolUnitError] = {} self._opened: list[str] = [] self._simulations_opened: dict[str, int] = {} self._passes_asked: dict[tuple[str, int], int] = {} @@ -7456,7 +7458,9 @@ def _report_timing( ) def _take(self, consumer: str, simulation: int | None): - """The next run of stream units for ``(consumer, simulation)``. + """The next run of stream units for ``(consumer, simulation)``, each + with its result, or with the ``WorkerPoolUnitError`` of a unit that + failed on every attempt. Units of a consumer opened before this one, which stopped before asking for them, are passed over. Any other unit in the way means the @@ -7479,11 +7483,13 @@ def _take(self, consumer: str, simulation: int | None): self._next_unit += 1 try: result = self._result_of(index) - except WorkerPoolUnitError: + except WorkerPoolUnitError as error: if ours: - # This consumer's own unit failed on every attempt. - raise - # A unit of a consumer that stopped before asking for it. + # This consumer's own unit failed on every attempt: the + # caller raises it in the order the serial scorer would + # have reached it. + taken.append((unit, error)) + # Otherwise a unit of a consumer that stopped before asking. continue except BaseException as error: # The pool cannot go on (a worker could not start, the scorer @@ -7522,17 +7528,32 @@ def _result_of(self, index: int) -> PostExportUnitResult: return next(self._stream) except WorkerPoolUnitError as failed_unit: failed = self._stream_positions[failed_unit.unit_index] - self._unit_errors[failed] = failed_unit - self._stream_positions = [ - position - for position in range(index, len(self._stream_units)) - if position not in self._unit_errors - ] + # A copy without the traceback: the raised error's frames hold + # the stopped run's finished results, which the fresh pool + # computes again. + kept = WorkerPoolUnitError( + str(failed_unit), + unit_index=failed, + label=failed_unit.label, + causes=failed_unit.causes, + ) + kept.__cause__ = failed_unit.__cause__ + self._unit_errors[failed] = kept + del failed_unit + self._stream_positions = [ + position + for position in range(index, len(self._stream_units)) + if position not in self._unit_errors + ] + if self._stream_positions: self._pool = self._new_pool() self._stream = self._pool.map( [self._stream_units[position] for position in self._stream_positions] ) - return self._result_of(index) + else: + # Nothing left to run: an empty generator, which close() accepts. + self._stream = (result for result in ()) + return self._result_of(index) # ---- consumers --------------------------------------------------------- @@ -7604,16 +7625,25 @@ def _baseline_for( parts: dict[PostExportKey, list[tuple[np.ndarray, np.ndarray]]] = { key: [] for key in baseline_plan } - failure: PostExportUnitFailure | None = None + failure: PostExportUnitFailure | WorkerPoolUnitError | None = None for _, result in self._take(name, None): + # The serial scorer stops at the first batch that raises, so the + # first range in batch order that failed, either way, is raised. + if failure is not None: + continue + if isinstance(result, WorkerPoolUnitError): + failure = result + continue outcome = result.outcomes[0] if isinstance(outcome, PostExportUnitFailure): - failure = failure or outcome - elif failure is None: + failure = outcome + else: for key, key_parts in zip(baseline_plan, outcome.parts, strict=True): parts[key].extend(key_parts) if failure is not None: del parts + if isinstance(failure, WorkerPoolUnitError): + raise failure _raise_post_export_worker_failure(failure) return { key: _concatenate_post_export_parts(parts.pop(key)) for key in baseline_plan @@ -7705,8 +7735,15 @@ def _reform_pass( "requests, so a consumer must ask for the same keys whatever " "values it gets back." ) + unfinished = self._unfinished_units.get((name, simulation)) + if unfinished is not None: + raise unfinished if asked == 0: [(unit, result)] = self._take(name, simulation) + if isinstance(result, WorkerPoolUnitError): + # Kept, so asking again raises it again. + self._unfinished_units[(name, simulation)] = result + raise result self._serving = (name, simulation, unit, result) serving = self._serving if serving is None or serving[:2] != (name, simulation): @@ -7817,13 +7854,16 @@ def _worker_pool_reports_record( "workers_stopped_over_cap": sum( report.workers_stopped_over_cap for report in reports ), + # Attempts are numbered within each pool; a unit a stopped run had + # finished and a fresh pool ran again is counted in both. "failed_attempts": [ { + "pool": pool, "unit": attempt.label, "attempt": attempt.attempt, "cause": attempt.cause, } - for report in reports + for pool, report in enumerate(reports) for attempt in report.failed_attempts ], } From 1f9bc17901510d2f2dc4636dfa9b37d6a09cf3f0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:26:32 +0400 Subject: [PATCH 13/26] Re-pin the post-export plan record's digest for the raised method label MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit test_the_release_s_recorded_post_export_outputs_are_unchanged pins the SHA-256 of the plan record in calibration_diagnostics.json, which holds POST_EXPORT_SCORING_METHOD. This branch raises the label to household_batched_written_h5_v2 (decision 1.1 · 1), which moved that one digest in CI's engine-free jobs; every consumer output's digest was unchanged. The test now also checks that the record with the first label still hashes to the earlier pin, so the label stays its only change. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_requests.py | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_requests.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_requests.py index 41335cb7a0..a859435cb2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_requests.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_requests.py @@ -678,10 +678,14 @@ def test_the_reform_alias_names_the_three_descriptions() -> None: #: them too. Re-pin only when such an input or the fixture changed on purpose, #: in the same pull request, by copying the digests this test's failure #: prints. The manifests' ``post_export_scoring`` block, which holds the -#: method label and the batching, is not pinned here. +#: method label and the batching, is not pinned here. The plan's record holds +#: the method label too: it was re-pinned when tracker task 1.4 · 7 raised +#: the label to ``household_batched_written_h5_v2`` (decision 1.1 · 1), and +#: with the earlier label it still hashes to the earlier pin +#: (``_PLAN_SHA256_WITH_THE_FIRST_LABEL``). _RECORDED_OUTPUT_SHA256 = { "calibration_diagnostics.build.post_export_scoring": ( - "7ed2a0dd088cf2d5a65e27e00368819cdf357160a5bdc2e42f079233d1f2f7b1" + "95ac7870f660e5090bbe2f4237eb010ff3746c68dd53dc984df624a59378e045" ), "reform_coverage_smoke": ( "c2e6cbf63b02fc5dbbc1ddd5507edd5e9cfb21a41143469cc737c69279da9842" @@ -727,6 +731,13 @@ def _json_ready(value): return value +#: The plan record's digest at origin/main fcabe4e65, with the first method +#: label, ``household_batched_written_h5``. +_PLAN_SHA256_WITH_THE_FIRST_LABEL = ( + "7ed2a0dd088cf2d5a65e27e00368819cdf357160a5bdc2e42f079233d1f2f7b1" +) + + def _sha256_of(value) -> str: encoded = json.dumps(_json_ready(value), sort_keys=True, allow_nan=False) return hashlib.sha256(encoded.encode()).hexdigest() @@ -786,3 +797,8 @@ def test_the_release_s_recorded_post_export_outputs_are_unchanged( assert { name: _sha256_of(output) for name, output in outputs.items() } == _RECORDED_OUTPUT_SHA256 + # The raised method label is the plan record's only change. + plan = dict(outputs["calibration_diagnostics.build.post_export_scoring"]) + assert plan["method"] == "household_batched_written_h5_v2" + plan["method"] = "household_batched_written_h5" + assert _sha256_of(plan) == _PLAN_SHA256_WITH_THE_FIRST_LABEL From 829c58e64b8520c37766d8d0d745ecdd36ecd7b6 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:30:54 +0400 Subject: [PATCH 14/26] Expect PostExportPoolStoppedError after a pool that could not start test_a_changed_batch_file_stops_pooled_scoring still matched the message the scorer raised before review round 1, "stopped earlier". A pool that could not start now refuses every later consumer with PostExportPoolStoppedError, "could not start", which the held-out reports pass on as a WorkerPoolError. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_post_export_pooled_scoring.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index e451d93c58..c4f07b1675 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -545,8 +545,10 @@ def test_a_changed_batch_file_stops_pooled_scoring( scorer.open_consumer( "reform_coverage_smoke", plan.baseline_plan("reform_coverage_smoke") ) - # Nothing more is served, and no consumer falls back to its own pass. - with pytest.raises(RuntimeError, match="stopped earlier"): + # Nothing more is served, and no consumer falls back to its own pass: + # a pool that could not start refuses every later consumer with a + # WorkerPoolError, which the held-out reports pass on. + with pytest.raises(builder.PostExportPoolStoppedError, match="could not start"): scorer.open_consumer( "reform_validation", plan.baseline_plan("reform_validation") ) From 29cd5da316e0e6bcc798491d33f25120ede1dea5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:11:55 +0400 Subject: [PATCH 15/26] Test that the US export sampler can leave named columns out and keeps the export's given name Failing tests: a --drop-column option that leaves a stored column out of the subsample, checks it is absent after the write, records it in the receipt and refuses an unstored name, the household weight and the id and membership columns; and a default output name taken from the path the export was given rather than the file a link resolves to, refusing to write over that link. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_export_subsample.py | 158 ++++++++++++++++++ 1 file changed, 158 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_export_subsample.py b/packages/microcosm-build/tests/engine_free/us/test_us_export_subsample.py index bc48252b5b..5bd4063aeb 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_export_subsample.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_export_subsample.py @@ -508,6 +508,164 @@ def lossy_writer(sample, path, period): ) +def _sample_written_export(sampler, source: Path, out_dir: Path, **options) -> dict: + """Sample a written synthetic export at half, engine-free; return the receipt.""" + return sampler.sample_export( + source, + out_dir, + fraction=0.5, + seed=0, + probes=fixture_sampler_probes(), + write_dataset=write_table_h5, + refuse_denied=False, + size_certainty_multiplier=0.0, + **options, + ) + + +def test_a_dropped_column_is_left_out_of_the_verified_subsample( + sampler, tmp_path +) -> None: + """A published export can store a column a later export contract refuses + (``has_marketplace_health_coverage``, now formula-owned). ``drop_columns`` + leaves it out of the subsample, the post-write check expects exactly that + column to be absent, and the receipt records it.""" + frame = synthetic_export_frame(30, seed=5) + source = tmp_path / "src" / "populace_us_2024.h5" + source.parent.mkdir() + write_table_h5(frame, source) + receipt = _sample_written_export( + sampler, source, tmp_path / "out", drop_columns=("age",) + ) + written = load_table_h5(Path(receipt["output"]["path"])) + assert "age" not in written.table("person").columns + assert set(written.table("person").columns) == set( + frame.table("person").columns + ) - {"age"} + for entity in ("household", "tax_unit", "spm_unit", "family", "marital_unit"): + assert set(written.table(entity).columns) == set(frame.table(entity).columns) + assert receipt["output"]["dropped_columns"] == {"person": ["age"]} + assert receipt["verification"]["passed"] + + +def test_a_subsample_with_no_dropped_columns_records_none(sampler, tmp_path) -> None: + frame = synthetic_export_frame(12, seed=5) + source = tmp_path / "src" / "populace_us_2024.h5" + source.parent.mkdir() + write_table_h5(frame, source) + receipt = _sample_written_export(sampler, source, tmp_path / "out") + assert receipt["output"]["dropped_columns"] == {} + + +def test_verification_catches_a_writer_that_keeps_a_dropped_column( + sampler, tmp_path +) -> None: + frame = synthetic_export_frame(20, seed=2) + source = tmp_path / "src" / "populace_us_2024.h5" + source.parent.mkdir() + write_table_h5(frame, source) + source_ages = frame.table("person").set_index("person_id")["age"] + + def writer_keeping_age(sample, path, period): + write_table_h5(sample, path, period) + with pd.HDFStore(str(path)) as store: + person = store["person"] + person["age"] = source_ages.reindex(person["person_id"]).to_numpy() + store.put("person", person, format="table", data_columns=True) + + with pytest.raises(AssertionError, match="stored columns differ"): + _sample_written_export( + sampler, + source, + tmp_path / "out", + drop_columns=("age",), + write_dataset=writer_keeping_age, + ) + + +@pytest.mark.parametrize( + ("column", "message"), + [ + ("not_a_stored_column", "no table of .* stores"), + ("household_weight", "the household weight"), + ("household_id", "an id or membership column"), + ("tax_unit_id", "an id or membership column"), + ("person_id", "an id or membership column"), + ("person_spm_unit_id", "an id or membership column"), + ], +) +def test_dropping_an_unstored_weight_or_id_column_is_refused( + sampler, tmp_path, column, message +) -> None: + frame = synthetic_export_frame(10, seed=1) + source = tmp_path / "src" / "populace_us_2024.h5" + source.parent.mkdir() + write_table_h5(frame, source) + out_dir = tmp_path / "out" + with pytest.raises(ValueError, match=message): + _sample_written_export(sampler, source, out_dir, drop_columns=(column,)) + assert not (out_dir / "populace_us_2024.h5").exists() + + +def _linked_export(tmp_path: Path, frame) -> Path: + """A synthetic export laid out as the Hugging Face cache stores one: a + snapshot's ``populace_us_2024.h5`` linked to a blob named by its hash.""" + blob = tmp_path / "blobs" / "5f0c2a9e71d4" + blob.parent.mkdir() + write_table_h5(frame, blob) + link = tmp_path / "snapshot" / "populace_us_2024.h5" + link.parent.mkdir() + link.symlink_to(blob) + return link + + +def test_the_subsample_takes_the_name_its_export_was_given(sampler, tmp_path) -> None: + link = _linked_export(tmp_path, synthetic_export_frame(12, seed=6)) + receipt = _sample_written_export(sampler, link, tmp_path / "out") + assert Path(receipt["output"]["path"]) == ( + (tmp_path / "out").resolve() / "populace_us_2024.h5" + ) + + +def test_a_subsample_written_over_its_exports_link_is_refused( + sampler, tmp_path +) -> None: + link = _linked_export(tmp_path, synthetic_export_frame(12, seed=6)) + with pytest.raises(ValueError, match="overwrite its source"): + _sample_written_export(sampler, link, link.parent) + assert link.is_symlink() + + +class _SampleExportCalledError(Exception): + pass + + +def test_the_cli_passes_every_dropped_column(sampler, tmp_path, monkeypatch) -> None: + passed: dict = {} + + def record_options(*arguments, **options): + passed.update(options) + raise _SampleExportCalledError + + monkeypatch.setattr(sampler, "sample_export", record_options) + with pytest.raises(_SampleExportCalledError): + sampler.main( + [ + "--export", + str(tmp_path / "populace_us_2024.h5"), + "--out", + str(tmp_path / "out"), + "--fraction", + "0.05", + "--drop-column", + "has_marketplace_health_coverage", + "--drop-column", + "age", + ] + ) + assert passed["drop_columns"] == ("has_marketplace_health_coverage", "age") + + # --------------------------------------------------------------------------- # Regression: the lost lane's "hung" dev check (2026-09-28) # --------------------------------------------------------------------------- From bf9d93df63cfc5305a5189072f09b099a662418e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:13:28 +0400 Subject: [PATCH 16/26] Let the US export sampler leave named columns out and keep the export's given name --drop-column NAME (repeatable) leaves a stored column out of the subsample; the sampler refuses an unstored name, the household weight and the id and membership columns, the post-write check expects exactly those columns absent, and the receipt lists them under output.dropped_columns. The default output name now comes from the --export path as given, not the blob a Hugging Face cache link resolves to, and writing over that link is refused. Co-Authored-By: Claude Opus 5.5 --- .../us-export-sampler-drop-column.added.md | 1 + .../us/test_us_export_subsample.py | 3 +- tools/sample_us_export_households.py | 95 +++++++++++++++++-- 3 files changed, 90 insertions(+), 9 deletions(-) create mode 100644 changelog.d/us-export-sampler-drop-column.added.md diff --git a/changelog.d/us-export-sampler-drop-column.added.md b/changelog.d/us-export-sampler-drop-column.added.md new file mode 100644 index 0000000000..c743fec193 --- /dev/null +++ b/changelog.d/us-export-sampler-drop-column.added.md @@ -0,0 +1 @@ +`tools/sample_us_export_households.py --drop-column NAME` (repeatable) leaves a stored column out of the subsample, so the current post-export stages can run on a published export that stores a column a later export contract refuses. It refuses a name no table stores, the household weight and the id and membership columns; the post-write check expects exactly those columns to be absent, and the receipt lists them under `output.dropped_columns`. The subsample now takes the name of the `--export` path as given rather than of the file a link resolves to (a Hugging Face cache snapshot's blob, named by its hash), and a subsample that would replace that link is refused. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_export_subsample.py b/packages/microcosm-build/tests/engine_free/us/test_us_export_subsample.py index 5bd4063aeb..79dd92828c 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_export_subsample.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_export_subsample.py @@ -516,10 +516,9 @@ def _sample_written_export(sampler, source: Path, out_dir: Path, **options) -> d fraction=0.5, seed=0, probes=fixture_sampler_probes(), - write_dataset=write_table_h5, refuse_denied=False, size_certainty_multiplier=0.0, - **options, + **{"write_dataset": write_table_h5, **options}, ) diff --git a/tools/sample_us_export_households.py b/tools/sample_us_export_households.py index aa675e78c6..270f7036d1 100644 --- a/tools/sample_us_export_households.py +++ b/tools/sample_us_export_households.py @@ -67,7 +67,20 @@ .venv/bin/python tools/sample_us_export_households.py \\ --export --fraction 0.05 --seed 0 --out -writes ``/populace_us_2024.h5`` and ``/sample_receipt.json``. +writes ``/populace_us_2024.h5`` and ``/sample_receipt.json``. The +subsample takes the name of the ``--export`` path as given, so an export read +through a link (a Hugging Face cache snapshot links each file to a blob named +by its hash) is written under the snapshot's file name; a subsample that would +replace that link, or the file it links to, is refused. + +``--drop-column NAME`` (repeatable) leaves a stored column out of the +subsample. A published export can store a column that a later export contract +refuses, such as one that has since become formula-owned; dropping it lets the +current post-export stages run on that export's households. The tool refuses +a name no table stores, the household weight, and the id and membership +columns the households are built from; the post-write check expects exactly +the dropped columns to be absent, and the receipt lists them under +``output.dropped_columns``. """ from __future__ import annotations @@ -563,6 +576,38 @@ def membership_column(entity: str) -> str: ) +def dropped_columns_by_table( + names: Iterable[str], + stored_columns: Mapping[str, Sequence[str]], + export_path: Path, +) -> dict[str, list[str]]: + """Each table's columns among ``names``, sorted, after refusing a name no + table stores, the household weight, and an id or membership column.""" + structural = {id_column(entity) for entity in US_ENTITIES} | set( + PERSON_MEMBERSHIP_COLUMNS + ) + dropped: dict[str, set[str]] = {} + for name in dict.fromkeys(names): + if name == HOUSEHOLD_WEIGHT_COLUMN: + raise ValueError( + f"Cannot drop {name!r}: it is the household weight, which the " + "subsample's drawn weights are written to." + ) + if name in structural: + raise ValueError( + f"Cannot drop {name!r}: it is an id or membership column, which " + "the subsample's whole households are selected by." + ) + tables = [entity for entity in US_ENTITIES if name in stored_columns[entity]] + if not tables: + raise ValueError( + f"Cannot drop {name!r}: no table of {export_path} stores it." + ) + for table in tables: + dropped.setdefault(table, set()).add(name) + return {table: sorted(dropped[table]) for table in sorted(dropped)} + + # --------------------------------------------------------------------------- # Pure selection core (no H5, no engine) # --------------------------------------------------------------------------- @@ -1311,8 +1356,13 @@ def sample_export( chunk_rows: int | None = None, dataset_filename: str | None = None, refuse_denied: bool = True, + drop_columns: Sequence[str] = (), ) -> dict[str, object]: - """Write the subsample H5 and its receipt; return the receipt.""" + """Write the subsample H5 and its receipt; return the receipt. + + The subsample is named ``dataset_filename``, or else the name of + ``export_path`` as given (not of a file it links to). ``drop_columns`` + names stored columns left out of it.""" from microcosm.frame import Frame, WeightKind, Weights from microcosm.frame.units import US_SCHEMA @@ -1320,11 +1370,14 @@ def sample_export( seed = validate_seed(seed) if not (math.isfinite(float(certainty_threshold)) and certainty_threshold >= 0): raise ValueError("certainty_threshold must be finite and non-negative.") + given_name = Path(export_path).name export_path = Path(export_path).resolve() out_dir = Path(out_dir).resolve() out_dir.mkdir(parents=True, exist_ok=True) - out_path = out_dir / (dataset_filename or export_path.name) - if out_path == export_path: + out_path = out_dir / (dataset_filename or given_name) + # resolve() follows a link at out_path, so writing over a link to the + # source is refused as writing over the source is. + if out_path == export_path or out_path.resolve() == export_path: raise ValueError("The subsample would overwrite its source export.") clock = _PhaseClock() write = write_dataset or _default_write_dataset @@ -1406,6 +1459,9 @@ def read_selection_inputs(): household = groups["household"] if HOUSEHOLD_WEIGHT_COLUMN not in household.columns: raise ValueError(f"{export_path} stores no {HOUSEHOLD_WEIGHT_COLUMN}.") + dropped_columns = dropped_columns_by_table( + drop_columns, source_columns, export_path + ) unit_counts = assert_units_nest_in_households(person) household_ids = household[id_column("household")].to_numpy() source_weights = household[HOUSEHOLD_WEIGHT_COLUMN].to_numpy(dtype=np.float64) @@ -1475,6 +1531,8 @@ def read_selected_rows() -> dict[str, pd.DataFrame]: } tables = clock.run("read_selected_rows", read_selected_rows) + for entity, columns in dropped_columns.items(): + tables[entity] = tables[entity].drop(columns=columns) if refuse_denied: from microcosm.build.us_runtime.h5_io import assert_h5_unchanged @@ -1514,6 +1572,7 @@ def read_selected_rows() -> dict[str, pd.DataFrame]: source_path=export_path, chunk_bytes=chunk_bytes, chunk_rows=chunk_rows, + dropped_columns=dropped_columns, ), ) output_sha256 = sha256_file(out_path) @@ -1595,6 +1654,7 @@ def read_selected_rows() -> dict[str, pd.DataFrame]: "path": str(out_path), "sha256": output_sha256, "size_bytes": out_path.stat().st_size, + "dropped_columns": dropped_columns, }, "verification": verification, "timing": clock.phases, @@ -1614,8 +1674,12 @@ def _verify_written_subsample( source_path: Path, chunk_bytes: int, chunk_rows: int | None = None, + dropped_columns: Mapping[str, Sequence[str]] | None = None, ) -> dict[str, object]: - """Re-read the written subsample and check it against the selection.""" + """Re-read the written subsample and check it against the selection. + + Its stored tables must hold the source's columns except + ``dropped_columns``, which must be absent.""" from microcosm.data.stored_inputs import h5_stored_tables with pd.HDFStore(str(out_path), mode="r") as store: @@ -1668,7 +1732,13 @@ def _verify_written_subsample( ) if person_households != set(draw.selected_ids.tolist()): failures.append("written persons do not cover exactly the selected households") - source_tables = h5_stored_tables(source_path) + dropped_columns = dropped_columns or {} + source_tables = { + table: tuple( + column for column in columns if column not in dropped_columns.get(table, ()) + ) + for table, columns in h5_stored_tables(source_path).items() + } written_tables = h5_stored_tables(out_path) column_differences = { table: { @@ -1746,7 +1816,17 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument( "--dataset-filename", default=None, - help="output H5 name (default: the source's file name)", + help="output H5 name (default: the name of the --export path as given, " + "not of a file it links to)", + ) + parser.add_argument( + "--drop-column", + action="append", + default=[], + dest="drop_columns", + metavar="NAME", + help="leave this stored column out of the subsample (repeatable); the " + "receipt records it under output.dropped_columns", ) args = parser.parse_args(argv) receipt = sample_export( @@ -1762,6 +1842,7 @@ def main(argv: Sequence[str] | None = None) -> int: chunk_bytes=int(args.chunk_mib) * 2**20, chunk_rows=args.chunk_rows, dataset_filename=args.dataset_filename, + drop_columns=tuple(args.drop_columns), ) selection = receipt["selection"] print( From 879f11ee34bc1f4cb880c774003d779529a3844b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:11:52 +0400 Subject: [PATCH 17/26] Test that the export probe takes the held-out reports from the release tool Failing test: the probe registers the held-out reports that the release tool's _post_export_holdout_consumers lists, the list certification registers, rather than naming them itself. The probe naming the IRMAA holdout module fails test_only_the_release_tool_imports_the_holdout. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_probe.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py index 5b6efb6fa4..9a0c0b330a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py @@ -1503,6 +1503,33 @@ def test_engine_options_and_pool_settings_are_not_given_together( assert probe.scorer_options == {} +def test_the_probe_registers_the_held_out_reports_certification_registers( + probe_tool, builder, fake_reforms, chain, tmp_path, monkeypatch +) -> None: + """The probe takes the held-out reports from the release tool's + ``_post_export_holdout_consumers``, the list certification registers, so + its merged pass follows certification's when a report is added or + removed, and the probe names no held-out module itself.""" + frame, path, receipt, _ = chain + monkeypatch.setattr(builder, "installed_us_engine", lambda: fixture_engine(frame)) + monkeypatch.setattr( + builder, + "_post_export_holdout_consumers", + lambda: {"medicare_irmaa_holdout": builder._medicare_irmaa_holdout_consumer}, + ) + report, _ = run_fixture_probe( + probe_tool, + builder, + path, + tmp_path / "probe", + receipt=receipt, + stages=("demographics",), + ) + record = report["stages"]["open_scorer"] + assert record["registered_consumers"] == ["demographics", "medicare_irmaa_holdout"] + assert record["unregistered_consumers"] == {} + + def test_a_held_out_report_whose_dry_run_fails_is_recorded( probe_tool, builder, fake_reforms, chain, tmp_path, monkeypatch ) -> None: From c366eb36cd5df32b35a671b3b8fd3119fed88eea Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:13:11 +0400 Subject: [PATCH 18/26] Take the export probe's held-out reports from the release tool _post_export_holdout_consumers lists the held-out reports every build registers after its post-export stages; certification's _post_export_consumers and the export probe both read it, so the probe names no held-out module itself and test_only_the_release_tool_imports_the_holdout passes again. Co-Authored-By: Claude Opus 5.5 --- tools/build_us_fiscal_refresh_release.py | 15 +++++++++++++-- tools/probe_us_post_export.py | 13 +++++-------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 862e9a7142..f88308cf73 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -5937,6 +5937,18 @@ def payload_for(simulate) -> dict[str, Any]: return payload_for +def _post_export_holdout_consumers() -> dict[ + str, Callable[[Callable[[Any], Any]], object] +]: + """The held-out reports' consumers, which every build registers after its + post-export stages. Built at each call, so a consumer replaced on this + module is the one returned.""" + return { + "ssi_social_security_holdout": _ssi_social_security_holdout_consumer, + "medicare_irmaa_holdout": _medicare_irmaa_holdout_consumer, + } + + def _post_export_consumers( args: argparse.Namespace, *, result, release_id: str ) -> dict[str, Callable[[Callable[[Any], Any]], object]]: @@ -5950,8 +5962,7 @@ def _post_export_consumers( ) if not args.skip_demographics: consumers["demographics"] = _demographics_consumer - consumers["ssi_social_security_holdout"] = _ssi_social_security_holdout_consumer - consumers["medicare_irmaa_holdout"] = _medicare_irmaa_holdout_consumer + consumers.update(_post_export_holdout_consumers()) return consumers diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index 222ddbb3eb..5c7700cf7e 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -2537,8 +2537,9 @@ def _engine_consumers(self) -> dict[str, Callable[[], Any]]: order: for each, a function that returns its consumer (a function of the ``simulate`` seam). - The engine stages to run, and the two held-out reports, which - certification always registers: the probe does not report them, but + The engine stages to run, and the held-out reports certification + always registers (``_post_export_holdout_consumers``, so the probe + names no held-out module itself): the probe does not report them, but their keys are in certification's merged baseline pass, so the probe's merged pass is that pass (its keys, its time and memory, and its failure and fallback when a held-out report's key fails). @@ -2550,12 +2551,8 @@ def _engine_consumers(self) -> dict[str, Callable[[], Any]]: "demographics": lambda: builder._demographics_consumer, } consumers = {name: make for name, make in makers.items() if name in self.stages} - consumers["ssi_social_security_holdout"] = lambda: ( - builder._ssi_social_security_holdout_consumer - ) - consumers["medicare_irmaa_holdout"] = lambda: ( - builder._medicare_irmaa_holdout_consumer - ) + for name, consumer in builder._post_export_holdout_consumers().items(): + consumers[name] = lambda consumer=consumer: consumer return consumers def _record_stage_requests(self) -> dict[str, Any]: From 98821038217479874f6809fe3ce6898e846f68eb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:16:56 +0400 Subject: [PATCH 19/26] Test that pooled post-export scoring runs every baseline pass in the certifying process Failing tests for Anthony's decision of 27 November: every baseline pass runs in the certifying process with the serial scorer's code before any worker starts, and the pool runs one unit per reformed simulation only. The merged pass runs first; if it raises, every stage's own pass runs next, before the pool, and a stage whose own pass raised gets that error, with its traceback as a note, when it opens. The execution record lists each baseline pass run here; a build with no reform starts no pool; a pool that cannot start fails the first reform request instead of the first stage's opening; the export probe writes the baseline passes as passes of the certifying process. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pooled_scoring.py | 224 +++++++++++++----- .../us/test_us_post_export_probe.py | 19 +- 2 files changed, 183 insertions(+), 60 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index c4f07b1675..446308c3f5 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -9,6 +9,11 @@ be byte-identical to the serial scorer's, at one and at three workers (``assert_identical_across_worker_counts``), with only the block's ``execution`` record (run metadata) apart; +- every baseline pass to run in the certifying process, as the serial scorer + runs it, before the pool starts, and the pool to run only reform passes + (Anthony's decision of 27 November: a worker's memory cap is sized for + reform passes, and a baseline pass over one batch went over it in the 5% + export probe); - the serial scorer's refusals to happen in the workers, with the serial error's class name and text: a population aggregate in a multi-batch pass, a baseline-branch reader in a reform pass, a reform that moves a @@ -42,6 +47,7 @@ WorkerPoolUnitError, ) from microcosm.calibrate import TargetRegistry +from test_support.microcosm_build import us_post_export_pool as fake_engines from test_support.microcosm_build.us_post_export_pool import ( COMPUTES, ENGINE_LOG, @@ -228,6 +234,36 @@ def _reform_unit_count(plan) -> int: ) +def _record_pool_starts(monkeypatch, builder) -> list[dict[str, int]]: + """Each pool the scorer creates, with how many fake engines this process + had built by then and how many of those were not yet released.""" + starts: list[dict[str, int]] = [] + pool_class = builder.WorkerPool + + def recording_pool(*arguments, **options): + starts.append( + { + "built_here": len(fake_engines._ENGINES), + "unreleased_here": sum( + engine.dataset is not None for engine in fake_engines._ENGINES + ), + } + ) + return pool_class(*arguments, **options) + + monkeypatch.setattr(builder, "WorkerPool", recording_pool) + return starts + + +def _baseline_pass_records(execution) -> list[tuple[str, int, str | None]]: + """The execution record's baseline passes: label, keys and error.""" + passes = execution["baseline_passes"] + assert all( + record["wall_seconds"] >= 0 and record["cpu_seconds"] >= 0 for record in passes + ) + return [(record["label"], record["keys"], record["error"]) for record in passes] + + def test_pooled_scoring_writes_the_serial_scorers_bytes_at_any_worker_count( builder, pooled_reforms, @@ -275,8 +311,17 @@ def run(workers: int): assert canonical_result_bytes(pooled) == canonical_result_bytes(serial) reform_units = _reform_unit_count(plan) + merged_keys = len( + builder._ascending_period_plan( + key for keys in plan.baseline_plans.values() for key in keys + ) + ) for workers, execution in executions.items(): report = execution.pop("report") + assert _baseline_pass_records(execution) == [ + ("merged baseline plan", merged_keys, None) + ] + del execution["baseline_passes"] assert execution == { "mode": "pooled", "chosen_by": "test", @@ -287,18 +332,24 @@ def run(workers: int): "max_attempts": 2, "max_units_ahead": None, "worker_environment_variables": [], - "units": {"baseline": workers, "reform": reform_units}, + "units": {"reform": reform_units}, "resources": None, "merged_baseline_fallback": None, } - assert report["units_completed"] == workers + reform_units + assert report["units_completed"] == reform_units assert report["failed_attempts"] == [] assert 1 <= report["max_live_workers"] <= workers events = engine_log(logs[3]) constructions = [event for event in events if event["event"] == "construct"] - assert os.getpid() not in {event["pid"] for event in events} - assert len({event["pid"] for event in constructions}) > 1 + # The merged baseline pass ran here, one engine per batch; the workers + # built reform engines only. + here = [event for event in constructions if event["pid"] == os.getpid()] + assert len(here) == 3 + assert all(event["system_reform"] is None for event in here) + in_workers = [event for event in constructions if event["pid"] != os.getpid()] + assert len({event["pid"] for event in in_workers}) > 1 + assert all(event["system_reform"] is not None for event in in_workers) assert all( event["spm"] == dict(US_RELEASE_SPM_SELECTION) for event in constructions ) @@ -526,9 +577,11 @@ def test_a_failed_merged_pass_falls_back_as_the_serial_scorer_does( assert holdout["status"] == "unavailable" assert holdout["error"] == "RuntimeError: fixture engine refuses medicare_enrolled" planned = [name for name, keys in plan.baseline_plans.items() if keys] - assert execution["report"]["units_completed"] == ( - 2 + 2 * len(planned) + _reform_unit_count(plan) - ) + assert [label for label, _, _ in _baseline_pass_records(execution)] == [ + "merged baseline plan", + *(f"{name} baseline plan" for name in planned), + ] + assert execution["report"]["units_completed"] == _reform_unit_count(plan) def test_a_changed_batch_file_stops_pooled_scoring( @@ -627,11 +680,39 @@ def asks(total): scorer.close() -def test_the_pool_starts_no_more_workers_than_units( +def test_the_pool_starts_no_more_workers_than_reform_units( builder, pooled_reforms, tmp_path, ) -> None: + def asks(total): + return [ + (FIXTURE_REFORM, [("income_tax", 2024)]), + (OTHER_REFORM, [("income_tax", 2024)]), + ] + + consumer = _fixture_consumer(asks) + plan = _fixture_plan(builder, consumer) + scorer = _pooled_scorer(builder, plan, tmp_path, 8) + try: + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + consumer(scoring.simulate) + scorer.finish_consumer(scoring) + execution = scorer.execution_record() + finally: + scorer.close() + assert execution["units"] == {"reform": 2} + assert (execution["requested_workers"], execution["workers"]) == (8, 2) + assert execution["report"]["max_live_workers"] <= 2 + + +def test_a_consumer_without_reforms_starts_no_pool( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + starts = _record_pool_starts(monkeypatch, builder) plan = _fixture_plan(builder, _fixture_consumer(lambda total: [])) scorer = _pooled_scorer(builder, plan, tmp_path, 8) try: @@ -640,9 +721,12 @@ def test_the_pool_starts_no_more_workers_than_units( execution = scorer.execution_record() finally: scorer.close() - assert execution["units"] == {"baseline": 3, "reform": 0} - assert (execution["requested_workers"], execution["workers"]) == (8, 3) - assert execution["report"]["max_live_workers"] <= 3 + assert starts == [] + assert (execution["units"], execution["workers"], execution["report"]) == ( + {"reform": 0}, + 0, + None, + ) def test_workers_get_the_lock_check_record_and_the_set_environment( @@ -697,18 +781,6 @@ def test_the_plan_records_each_consumers_requests_and_passes(builder) -> None: assert "consumer_requests" not in json.dumps(plan.record()) -def test_the_batch_ranges_cover_every_batch_once(builder) -> None: - for n_batches in (1, 2, 3, 7, 177): - for ranges in (1, 2, 4, 17, 200): - split = builder._post_export_batch_ranges(n_batches, ranges) - assert [position for batches in split for position in batches] == list( - range(n_batches) - ) - assert len(split) == min(ranges, n_batches) - sizes = {len(batches) for batches in split} - assert max(sizes) - min(sizes) <= 1 - - # --------------------------------------------------------------------------- # Pooled scoring is certification's default (1.4 · 6's settings, approved by # Anthony on 27 November) @@ -930,7 +1002,7 @@ def consumer(simulate): return consumer -def test_a_merged_pass_a_worker_cannot_finish_falls_back_as_the_serial_scorer_does( +def test_a_merged_pass_that_runs_out_of_memory_falls_back_here_before_the_pool( builder, pooled_reforms, tmp_path, @@ -938,13 +1010,16 @@ def test_a_merged_pass_a_worker_cannot_finish_falls_back_as_the_serial_scorer_do capsys, ) -> None: """An engine runs out of memory on the merged pass's three keys but not - on either consumer's two. The serial scorer catches the MemoryError and - scores each consumer's own plan; so does the pool, once the merged unit - has failed on every attempt.""" + on any consumer's own plan. As the serial scorer does, every consumer then + scores its own plan in this process; all of them are scored before the + pool starts, so no baseline engine is built here while workers run.""" monkeypatch.setenv(MEMORY_KEYS, "2") consumers = { "first": _baseline_consumer("age", "snap"), "second": _baseline_consumer("age", "income_tax"), + "third": _fixture_consumer( + lambda total: [(FIXTURE_REFORM, [("income_tax", 2024)])] + ), } plan = builder._post_export_scoring_plan( n_households=N_HOUSEHOLDS, @@ -969,19 +1044,35 @@ def run(scorer): serial = run(_serial_scorer(builder, plan, tmp_path / "serial")) assert "merged baseline plan failed" in capsys.readouterr().out + starts = _record_pool_starts(monkeypatch, builder) + before = len(fake_engines._ENGINES) pooled = run(_pooled_scorer(builder, plan, tmp_path / "pooled", 1)) assert "merged baseline plan failed" in capsys.readouterr().out assert canonical_result_bytes(pooled) == canonical_result_bytes(serial) - # The record keeps the failed pool's report: the attempts that failed and - # the workers they started, with the fallback's units. + # One engine for the merged pass (it fails in the first batch), then + # three batches for each consumer's own plan, all before the pool starts. + built_here = len(fake_engines._ENGINES) - before + assert built_here == 1 + 3 * 3 + assert [start["built_here"] - before for start in starts] == [built_here] + assert [start["unreleased_here"] for start in starts] == [0] execution = executions[1] - assert execution["merged_baseline_fallback"].startswith("WorkerPoolUnitError") - assert execution["units"] == {"baseline": 1, "reform": 0, "fallback_baseline": 2} + assert execution["merged_baseline_fallback"] == ( + "MemoryError: fixture engine holds more than 2 keys" + ) + assert _baseline_pass_records(execution) == [ + ( + "merged baseline plan", + 3, + "MemoryError: fixture engine holds more than 2 keys", + ), + ("first baseline plan", 2, None), + ("second baseline plan", 2, None), + ("third baseline plan", 1, None), + ] + assert execution["units"] == {"reform": 1} report = execution["report"] - assert report["pools"] == 2 - assert len(report["failed_attempts"]) == 2 - assert report["worker_starts"] >= 3 - assert report["units_completed"] == 2 + assert (report["pools"], report["failed_attempts"]) == (1, []) + assert report["units_completed"] == 1 def test_a_unit_the_pool_cannot_finish_fails_its_own_consumer_alone( @@ -1138,20 +1229,29 @@ def test_a_pool_that_cannot_start_refuses_every_consumer( digest, none starts, and every consumer is refused with a WorkerPoolError that names the refusal.""" monkeypatch.setattr(builder, "_RELEASE_TOOL_SHA256", "0" * 64) + consumers = { + "first": _fixture_consumer( + lambda total: [(FIXTURE_REFORM, [("income_tax", 2024)])] + ), + "second": _fixture_consumer( + lambda total: [(OTHER_REFORM, [("income_tax", 2024)])] + ), + } plan = builder._post_export_scoring_plan( n_households=N_HOUSEHOLDS, maximum_microsim_batch_size=BATCH_SIZE, - consumers={ - "first": _baseline_consumer("age"), - "second": _baseline_consumer("snap"), - }, + consumers=consumers, ) scorer = _pooled_scorer(builder, plan, tmp_path, 1) try: + # The baseline passes run here, so a consumer opens; its first reform + # request needs the workers. + first = scorer.open_consumer("first", plan.baseline_plan("first")) with pytest.raises(WorkerPoolError, match="SHA-256"): - scorer.open_consumer("first", plan.baseline_plan("first")) + consumers["first"](first.simulate) + second = scorer.open_consumer("second", plan.baseline_plan("second")) with pytest.raises(builder.PostExportPoolStoppedError): - scorer.open_consumer("second", plan.baseline_plan("second")) + consumers["second"](second.simulate) finally: scorer.close() @@ -1209,12 +1309,15 @@ def test_the_execution_record_names_the_environment_workers_got( "us_engine_abi_lock_check_environment", lambda: {"MICROCOSM_TEST_HANDED_DOWN": "handed down"}, ) - plan = _fixture_plan(builder, _fixture_consumer(lambda total: [])) + consumer = _fixture_consumer( + lambda total: [(FIXTURE_REFORM, [("income_tax", 2024)])] + ) + plan = _fixture_plan(builder, consumer) scorer = _pooled_scorer(builder, plan, tmp_path, 1) try: - scorer.finish_consumer( - scorer.open_consumer("fixture", plan.baseline_plan("fixture")) - ) + scoring = scorer.open_consumer("fixture", plan.baseline_plan("fixture")) + consumer(scoring.simulate) + scorer.finish_consumer(scoring) execution = scorer.execution_record() finally: scorer.close() @@ -1276,20 +1379,21 @@ def test_workers_check_they_run_the_parents_release_tool(builder) -> None: assert builder._RELEASE_TOOL_SHA256 == hashlib.sha256(tool.read_bytes()).hexdigest() -def test_a_stage_own_baseline_raises_its_first_problem_in_batch_order( +def test_a_stage_whose_own_baseline_failed_raises_that_error_when_it_opens( builder, pooled_reforms, tmp_path, monkeypatch, ) -> None: - """After the merged pass fails, a stage's own baseline pass that raises in - its first batch raises that error, as the serial scorer does, even when a - later range of it also fails on every attempt in the pool.""" + """After the merged pass fails, every stage's own baseline pass runs here + before the pool starts. One that raises is kept, without its traceback's + frames, and raised when that stage opens, with the error the serial + scorer raises then; the original traceback is a note on it.""" monkeypatch.setenv(FAIL_ON_HOUSEHOLDS, json.dumps({"snap": [1]})) - monkeypatch.setenv(MEMORY_ON_HOUSEHOLDS, json.dumps({"snap": [7]})) consumers = { "first": _baseline_consumer("age", "income_tax"), "second": _baseline_consumer("age", "snap"), + "third": _baseline_consumer("age"), } plan = builder._post_export_scoring_plan( n_households=N_HOUSEHOLDS, @@ -1297,22 +1401,32 @@ def test_a_stage_own_baseline_raises_its_first_problem_in_batch_order( consumers=consumers, ) - def run(scorer): + def run(scorer, kept=None): observed = {} try: for name, consumer in consumers.items(): + if kept is not None and name == "second": + kept.extend(scorer._own_baselines.values()) try: scoring = scorer.open_consumer(name, plan.baseline_plan(name)) - except (RuntimeError, MemoryError) as error: + except RuntimeError as error: observed[name] = f"{type(error).__name__}: {error}" + notes = getattr(error, "__notes__", []) + observed[f"{name} notes"] = any( + "Traceback" in note for note in notes + ) continue observed[name] = consumer(scoring.simulate) finally: scorer.close() return observed - monkeypatch.setenv(MEMORY_ON_HOUSEHOLDS, "{}") serial = run(_serial_scorer(builder, plan, tmp_path / "serial")) assert serial["second"] == "RuntimeError: fixture engine refuses snap" - monkeypatch.setenv(MEMORY_ON_HOUSEHOLDS, json.dumps({"snap": [7]})) - assert run(_pooled_scorer(builder, plan, tmp_path / "pooled", 2)) == serial + kept: list = [] + pooled = run(_pooled_scorer(builder, plan, tmp_path / "pooled", 2), kept) + assert pooled.pop("second notes") is True + serial.pop("second notes") + assert pooled == serial + errors = [value for value in kept if isinstance(value, BaseException)] + assert len(errors) == 1 and errors[0].__traceback__ is None diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py index 9a0c0b330a..69e89fcd33 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py @@ -1355,15 +1355,24 @@ def passes(directory): assert {(row["stage"], row["label"]) for row in pooled_passes} == { (row["stage"], row["label"]) for row in serial_passes } - assert all(row["process"] == "pool worker" for row in pooled_passes) - assert os.getpid() not in {row["worker_pid"] for row in pooled_passes} + # The baseline passes ran in this process, as in the serial probe; the + # workers ran the reform passes. + assert all(row["process"] == "certifying process" for row in serial_passes) + in_workers = [row for row in pooled_passes if row["process"] == "pool worker"] + here = [row for row in pooled_passes if row["process"] == "certifying process"] + assert len(in_workers) + len(here) == len(pooled_passes) + assert here and not any(row["reform"] for row in here) + assert in_workers and all(row["reform"] for row in in_workers) + assert [(row["stage"], row["label"]) for row in here] == [ + (row["stage"], row["label"]) for row in serial_passes if not row["reform"] + ] + assert os.getpid() not in {row["worker_pid"] for row in in_workers} assert all( - row["cpu_seconds"] >= 0 and row["worker_peak_rss_gib"] > 0 - for row in pooled_passes + row["cpu_seconds"] >= 0 and row["worker_peak_rss_gib"] > 0 for row in in_workers ) smoke_timing = pooled["stages"]["reform_coverage_smoke"]["timing"] assert smoke_timing["worker_passes"] == sum( - row["stage"] == "reform_coverage_smoke" for row in pooled_passes + row["stage"] == "reform_coverage_smoke" for row in in_workers ) assert smoke_timing["worker_cpu_seconds"] > 0 assert serial["stages"]["reform_coverage_smoke"]["timing"]["worker_passes"] == 0 From 62978a9836c812bfc8d79b6215522d451bc9d182 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:24:39 +0400 Subject: [PATCH 20/26] Run every pooled baseline pass in the certifying process before the pool starts Anthony's decision of 27 November. In the 5% export probe a baseline pass over one 2,000-household batch went over the 5.25 GiB worker cap on every attempt, while reform passes peaked at about 2 GiB. When the first stage opens, _PooledPostExportScorer runs the merged baseline pass with the serial scorer's code (now its own method, _run_merged_baseline_pass, which the serial scorer calls too) and, if it raises, every stage's own baseline pass, all before any worker starts. A stage whose own pass raised gets that error, its traceback kept as a note without its frames, when it opens. The pool then runs one unit per reformed simulation only, and starts no workers when no stage opens a reform. The execution record lists each baseline pass run here, and the export probe writes them to passes.jsonl as passes of the certifying process. The merged baseline's batch-range units are removed. Also fixes the new own-baseline test, which read the kept error's traceback after the error had been raised again. Co-Authored-By: Claude Opus 5.5 --- .../us-pooled-post-export-scoring.changed.md | 2 +- docs/us-release-build-rule.md | 71 +-- .../us/test_us_post_export_pooled_scoring.py | 10 +- tools/build_us_fiscal_refresh_release.py | 437 +++++++++--------- tools/probe_us_post_export.py | 46 +- 5 files changed, 284 insertions(+), 282 deletions(-) diff --git a/changelog.d/us-pooled-post-export-scoring.changed.md b/changelog.d/us-pooled-post-export-scoring.changed.md index 324ed1e598..672ebffe6d 100644 --- a/changelog.d/us-pooled-post-export-scoring.changed.md +++ b/changelog.d/us-pooled-post-export-scoring.changed.md @@ -1 +1 @@ -US certification scores post-export stages in the shared worker pool by default (`_PooledPostExportScorer`), with tracker decision 1.4 · 6's settings: `MICROCOSM_POST_EXPORT_WORKERS` unset or `auto` starts at most min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers and refuses, before the build is placed, a machine with no room for one; a positive number starts that many, and `serial` scores in the certifying process as before; each worker is replaced after 2 units and capped at max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers). In the pool, the merged baseline pass is split into one range of household batches per worker, each reformed simulation's recorded passes are one unit, and each post-export stage then runs in the certifying process over the results, refusing any request, or any reform, its engine-free dry run did not record; the smoke check's and reform validation's builders mark each reform with the description it was built from. A merged baseline unit the pool cannot finish falls back to each stage's own pass, as a serial `MemoryError` does; any other unit that fails on every attempt fails the stage that asks for it, and the pool goes on with the rest in fresh workers; a worker refuses a release tool whose bytes differ from the certifying process's. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's merged baseline pass instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan and the held-out reports' (certification's shared baseline pass), can score in the pool and writes each worker pass's time and memory to `passes.jsonl`; its household row map reads one batch file at a time. +US certification scores post-export stages in the shared worker pool by default (`_PooledPostExportScorer`), with tracker decision 1.4 · 6's settings: `MICROCOSM_POST_EXPORT_WORKERS` unset or `auto` starts at most min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers and refuses, before the build is placed, a machine with no room for one; a positive number starts that many, and `serial` scores in the certifying process as before; each worker is replaced after 2 units and capped at max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers). Every baseline pass runs in the certifying process with the serial scorer's code, when the first stage opens and before any worker starts: the merged pass, and, if it raises, every stage's own pass, each stage then served its values or its error (Anthony's decision of 27 November, after the 5% export probe showed one 2,000-household batch's baseline pass going over the 5.25 GiB worker cap). The pool then runs one unit per reformed simulation, holding its recorded passes, and each post-export stage runs in the certifying process over the results, refusing any request, or any reform, its engine-free dry run did not record; the smoke check's and reform validation's builders mark each reform with the description it was built from. A unit that fails on every attempt fails the stage that asks for it, and the pool goes on with the rest in fresh workers; a worker refuses a release tool whose bytes differ from the certifying process's. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's baseline passes instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan and the held-out reports' (certification's shared baseline pass), taking the held-out reports from the release tool's `_post_export_holdout_consumers`, can score in the pool and writes each pass's time and memory to `passes.jsonl`, naming the process that ran it; its household row map reads one batch file at a time. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 67c40283e9..ef141b3c4e 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -530,37 +530,46 @@ one Microsimulation over the whole file. - Certification prints the plan: the workers, the planned peak beside the budget and each worker's cap. `tools/probe_us_post_export.py` reads the same setting the same way. - - The pool runs twice. First the shared baseline pass, split into one range - of batches per worker. Then one unit per reformed simulation, holding all - of that simulation's recorded passes over every batch, in the order the - stages run: a worker builds the reform's rules once per unit, as the - serial scorer builds them once per reformed simulation. If the shared pass - fails, the second run also holds each stage's own baseline pass before - that stage's reform units. That includes a range of the shared pass that - failed on every attempt (its worker ran out of memory, went over its cap - or died), as the serial scorer falls back when its shared pass raises - `MemoryError`. + - Every baseline pass runs in the certifying process, with the serial + scorer's own code, when the first stage opens and before any worker + starts (Anthony's decision of 27 November). First the shared baseline + pass. If it raises (`MemoryError` included), every stage's own baseline + pass runs next, in the order the stages run, where the serial scorer runs + each one when its stage opens; a stage whose own pass raised gets that + error when it opens. A changed batch file stops scoring at once. Each + batch engine is released before the next is built, so no baseline engine + is held in the certifying process while workers run. + - The pool then runs one unit per reformed simulation, holding all of that + simulation's recorded passes over every batch, in the order the stages + run: a worker builds the reform's rules once per unit, as the serial + scorer builds them once per reformed simulation. A build whose stages + open no reform starts no pool. + - Why: the worker cap is sized for reform passes. In the pooled export + probe on a 5% sample of a published file (27 November), a baseline pass + over one batch of 2,000 households went over the 5.25 GiB cap on every + attempt, the shared pass at 5.37 and 5.38 GiB and the smoke's own pass + at 5.43 and 5.34 GiB, while the reform passes peaked at 1.35 to 2.00 + GiB. Certification's batches are up to 5,000 households. - A worker reads each batch from the scorer's batch file, refusing one that changed, and scores it with the serial scorer's own code (`_score_post_export_batches`): one engine per batch, keys in ascending period order, the population-aggregate refusal in a pass over more than - one batch, the baseline-branch refusal and the behavioral-response check - of a reform pass. + one batch, and the baseline-branch refusal and the behavioral-response + check of a reform pass. - A failure in a worker comes back with the unit's results. The certifying process raises it when the stage asks for that pass, where the serial scorer would have raised, as an error with the worker's exception's class name and message, so a held-out report that records the error records the same text. A changed batch file raises `PostExportBatchFileError`. A unit - after the shared pass that failed on every attempt (its worker ran out of - memory, went over its cap or died) raises `WorkerPoolUnitError` in the - stage that asks for it, even when it failed while workers were still - running an earlier stage's units, and the pool goes on with the other - units in fresh workers. The shared pool stops a run at such a failure, - so the units then in flight, the one due among them, start again in the - fresh pool. In a stage's own baseline pass the first range in batch - order that failed, either way, is the error raised. A pool whose workers cannot start refuses every - stage that needs it (`PostExportPoolStoppedError`); a stage served from - the shared pass's values is still served. Each of these is a + that failed on every attempt (its worker ran out of memory, went over its + cap or died) raises `WorkerPoolUnitError` in the stage that asks for it, + even when it failed while workers were still running an earlier stage's + units, and the pool goes on with the other units in fresh workers. The + shared pool stops a run at such a failure, so the units then in flight, + the one due among them, start again in the fresh pool. A pool whose + workers cannot start refuses every request that needs it + (`PostExportPoolStoppedError`); a stage's baseline values, scored in the + certifying process, are still served. Each of these is a `WorkerPoolError` and stops certification, the held-out reports included, where the serial scorer, which has no memory cap, may have finished. - Each stage then runs as in the serial path and builds its own reforms (the @@ -586,16 +595,18 @@ one Microsimulation over the whole file. mix two versions' results (the microcosm packages are not checked). - The manifests' `post_export_scoring` block records how scoring ran under `execution`: `{"mode": "serial"}`, or the pool's settings, how the worker - count was chosen, the plan's memory and core readings, unit counts, why - the shared pass fell back if it did, and the report of every pool the - scorer ran (worker starts, failed attempts, peak worker memory). That - record is run metadata, outside every output comparison (decision 1.1 · 1). + count was chosen, the plan's memory and core readings, the number of + reform units, each baseline pass run in the certifying process (its + label, keys, wall and CPU time, and error if it raised), why the shared + pass fell back if it did, and the report of every pool the scorer ran + (worker starts, failed attempts, peak worker memory). That record is run + metadata, outside every output comparison (decision 1.1 · 1). - The 5 GiB per worker comes from reform passes (1.4 · 6's one-batch check peaked at about 3.5-4.7 GiB over two reform passes of 2,000 households). - The shared pass's units compute about 97 keys per batch engine and - reform validation's own pass 75, which nothing has measured yet; the - pooled export probe on a 5% sample reports each pool's peak worker - memory and every attempt the cap stopped. + The plan's 3 GiB for the certifying process applies while workers run, + after its baseline engines are released; its peak during the baseline + passes is the serial scorer's, with no worker running. Neither figure + has been measured at certification's 5,000-household batches. - Each batch engine keeps policyengine-us's projection of the release year to its last CPI-U year (2035), because the plans request keys in later years (reform validation reaches past 2025). The build's own simulations hold diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index 446308c3f5..4bb1c0a86e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -1406,7 +1406,12 @@ def run(scorer, kept=None): try: for name, consumer in consumers.items(): if kept is not None and name == "second": - kept.extend(scorer._own_baselines.values()) + # Before it is raised again, which gives it a traceback. + kept.extend( + value.__traceback__ + for value in scorer._own_baselines.values() + if isinstance(value, BaseException) + ) try: scoring = scorer.open_consumer(name, plan.baseline_plan(name)) except RuntimeError as error: @@ -1428,5 +1433,4 @@ def run(scorer, kept=None): assert pooled.pop("second notes") is True serial.pop("second notes") assert pooled == serial - errors = [value for value in kept if isinstance(value, BaseException)] - assert len(errors) == 1 and errors[0].__traceback__ is None + assert kept == [None] diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 2aec153974..d7c0a01f4f 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -6192,6 +6192,8 @@ def __init__( } self._merged_baseline: dict[PostExportKey, _PostExportValues] | None = None self._merged_baseline_failed = False + # Why the merged pass fell back to each consumer's own pass, if it did. + self._merged_fallback_reason: str | None = None # 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 @@ -6329,31 +6331,8 @@ def _baseline_for( if name not in self._unserved_baseline_plans or self._merged_baseline_failed: return self._score(baseline_plan, label=f"{name} baseline plan"), False if self._merged_baseline is None: - union = _ascending_period_plan( - key for plan in self._unserved_baseline_plans.values() for key in plan - ) - try: - self._merged_baseline = self._score(union, label="merged baseline plan") - except PostExportBatchFileError: - # The scored file's integrity, not a key one consumer planned: - # it stops certification. - raise - except Exception as error: - self._merged_baseline_failed = True - try: - reason = f"{type(error).__name__}: {error}" - except Exception: - reason = type(error).__name__ - print( - f"Post-export merged baseline plan failed ({reason}); each " - "consumer scores its own baseline plan instead.", - flush=True, - ) + self._run_merged_baseline_pass() if self._merged_baseline_failed: - # Outside the handler, so the failed pass's traceback and the - # per-batch values its frame collected are no longer - # referenced; a full collection frees any held in a cycle. - collect_pass_garbage() return self._score(baseline_plan, label=f"{name} baseline plan"), False del self._unserved_baseline_plans[name] served = {key: self._merged_baseline[key] for key in baseline_plan} @@ -6365,6 +6344,38 @@ def _baseline_for( del self._merged_baseline[key] return served, True + def _run_merged_baseline_pass(self) -> None: + """Score the union of every unserved registered plan in one + batch-outer pass, in ascending period order, into ``_merged_baseline``. + + If the pass raises, ``_merged_baseline_failed`` is set and every + registered consumer then scores its own plan. A refused batch file + (:class:`PostExportBatchFileError`) propagates instead. + """ + union = _ascending_period_plan( + key for plan in self._unserved_baseline_plans.values() for key in plan + ) + try: + self._merged_baseline = self._score(union, label="merged baseline plan") + except PostExportBatchFileError: + # The scored file's integrity, not a key one consumer planned: + # it stops certification. + raise + except Exception as error: + self._merged_baseline_failed = True + self._merged_fallback_reason = _post_export_error_text(error) + print( + "Post-export merged baseline plan failed " + f"({self._merged_fallback_reason}); each consumer scores its own " + "baseline plan instead.", + flush=True, + ) + if self._merged_baseline_failed: + # Outside the handler, so the failed pass's traceback and the + # per-batch values its frame collected are no longer referenced; a + # full collection frees any held in a cycle. + collect_pass_garbage() + def _construct(self, batch_frame: Frame, *, reform_system): return _construct_post_export_engine( self._microsimulation_cls, @@ -6430,6 +6441,36 @@ def _score( } +def _post_export_error_text(error: BaseException) -> str: + """``": "``, or the class name alone when the + message cannot be formatted.""" + try: + return f"{type(error).__name__}: {error}" + except Exception: + return type(error).__name__ + + +def _without_traceback_frames(error: BaseException, *, note: str) -> BaseException: + """``error``, kept to raise later: its formatted traceback is added as a + note after ``note``, and its frames, with those of every exception it was + raised from or while handling, are dropped, so it holds no failed pass's + per-batch values.""" + error.add_note(note + "\n" + "".join(traceback.format_exception(error))) + pending, seen = [error], set() + while pending: + linked = pending.pop() + if id(linked) in seen: + continue + seen.add(id(linked)) + linked.__traceback__ = None + pending.extend( + chained + for chained in (linked.__cause__, linked.__context__) + if chained is not None + ) + return error + + def _construct_post_export_engine(microsimulation_cls, dataset, *, reform_system): """One batch engine, for the serial scorer and pool workers alike. @@ -6815,29 +6856,32 @@ def finish(self) -> None: # --------------------------------------------------------------------------- # # The serial scorer runs every pass in its own process, one after another. -# The pooled scorer (``_PooledPostExportScorer``) runs the same passes in the -# shared worker pool (``microcosm.build.worker_pool``) and serves each -# consumer from their results: +# The pooled scorer (``_PooledPostExportScorer``) runs the baseline passes +# the same way, then the reform passes in the shared worker pool +# (``microcosm.build.worker_pool``), and serves each consumer from their +# results: # # * The plan's engine-free dry run recorded every request of every consumer # and the reform passes the serial scorer runs for them # (``_PostExportConsumerRequests``). -# * The pool runs twice. First the merged baseline plan, split into ranges of -# batches, one unit per range. Then one unit per reformed simulation, with -# every recorded pass of it over every batch, in the order the consumers -# run: a worker builds the reform's rules once for the unit, as the serial -# scorer builds them once per reformed simulation. If the merged baseline -# pass failed, the second run also holds each consumer's own baseline plan -# before its reform units, as the serial scorer then scores it. +# * When the first consumer opens, every baseline pass runs in this process +# with the serial scorer's code: the merged baseline plan, and, if that +# raises, each consumer's own plan, all before any worker starts +# (Anthony's decision of 27 November: each worker's memory cap is sized for +# reform passes, and in the 5% export probe a baseline pass over one batch +# of 2,000 households went over it on every attempt). Each batch engine is +# released before the next, so none is held here while workers run. +# * The pool then runs one unit per reformed simulation, with every recorded +# pass of it over every batch, in the order the consumers run: a worker +# builds the reform's rules once for the unit, as the serial scorer builds +# them once per reformed simulation. # * A worker reads each batch from the scorer's batch file (refusing one # whose bytes changed), builds one engine per batch and scores the pass's # keys on it exactly as the serial scorer does # (``_score_post_export_batches``): ascending periods, the # population-aggregate refusal of a pass over a multi-batch H5, the -# baseline-branch refusal and the behavioral-response check of a reform -# pass. A failure is returned with the unit, not raised. A merged -# baseline unit that fails on every attempt (out of memory, over its cap) -# is a failed merged pass, as a serial MemoryError is. +# baseline-branch refusal and the behavioral-response check. A failure is +# returned with the unit, not raised. # * The consumers then run in this process, as in the serial path, and build # their own reforms (the smoke check records each list edit's resolved # lists from its own). Each baseline is served the consumer's recorded @@ -7153,30 +7197,20 @@ def _post_export_worker_settings( ) -def _post_export_batch_ranges(n_batches: int, ranges: int) -> tuple[range, ...]: - """``n_batches`` split into at most ``ranges`` contiguous, near-equal ranges.""" - count = max(1, min(int(ranges), int(n_batches))) - bounds = [index * n_batches // count for index in range(count + 1)] - return tuple( - range(start, stop) - for start, stop in zip(bounds, bounds[1:], strict=False) - if start < stop - ) - - class _PooledPostExportScorer(_HouseholdBatchedPostExportScorer): - """Scores the recorded requests in the shared worker pool and serves each - consumer, when it runs again in this process, from the results (see the - block comment above). + """Scores every baseline pass in this process and the recorded reform + passes in the shared worker pool, and serves each consumer, when it runs + again in this process, from the results (see the block comment above). ``consumer_requests`` are the plan's records of each consumer's dry run (``_PostExportScoringPlan.consumer_requests``), in the order the consumers run; every one is registered, so the merged baseline pass holds every plan. Only those consumers may be opened, each once, in that order - (one that stops early is passed over when the next opens). The pool - starts when the first consumer opens and stops when the scorer closes. - ``pass_timing_listener``, if set, is called with one row per pass a worker - ran, as its results arrive (the export probe writes them out). + (one that stops early is passed over when the next opens). When the first + consumer opens, every baseline pass runs here (:meth:`_score_baselines`) + and the pool then starts on the reform units; it stops when the scorer + closes. ``pass_timing_listener``, if set, is called with one row per pass + a worker ran, as its results arrive (the export probe writes them out). """ def __init__( @@ -7215,7 +7249,14 @@ def __init__( self._pool: WorkerPool | None = None self._started = False self._workers = 0 - self._units = {"baseline": 0, "reform": 0} + self._units = {"reform": 0} + # Each baseline pass run in this process: label, keys, time, error. + self._baseline_passes: list[dict[str, object]] = [] + # After a failed merged pass, each consumer's own baseline values, or + # the error its pass raised, until that consumer opens. + self._own_baselines: dict[ + str, dict[PostExportKey, _PostExportValues] | BaseException + ] = {} self._stream: Iterator[PostExportUnitResult] | None = None self._stream_units: tuple[PostExportUnit, ...] = () self._next_unit = 0 @@ -7226,10 +7267,9 @@ def __init__( # replaced since (a pool closes when a unit fails on every attempt). self._pool_settings: WorkerPoolSettings | None = None self._replaced_reports: list[WorkerPoolReport] = [] - self._merged_fallback_reason: str | None = None - # The second run's units still to be handed back by the current pool, - # as positions in ``_stream_units``, and the units that failed on - # every attempt, by position, each raised when its consumer asks. + # The reform units still to be handed back by the current pool, as + # positions in ``_stream_units``, and the units that failed on every + # attempt, by position, each raised when its consumer asks. self._stream_positions: list[int] = [] self._unit_errors: dict[int, WorkerPoolUnitError] = {} # Each reformed simulation whose unit failed on every attempt. @@ -7250,26 +7290,77 @@ def __init__( None ) - # ---- the pool ---------------------------------------------------------- + # ---- the baseline passes, in this process ------------------------------- - def _baseline_units( - self, consumer: str | None, label: str, keys: Sequence[PostExportKey] - ) -> tuple[PostExportUnit, ...]: - scoring_pass = PostExportPass(label=label, keys=tuple(keys)) - return tuple( - PostExportUnit( - consumer=consumer, - reformed_simulation=None, - reform=None, - passes=(scoring_pass,), - batch_start=batches.start, - batch_stop=batches.stop, - n_batches=self.n_batches, + def _score( + self, + keys: Sequence[PostExportKey], + *, + label: str, + reform_system=None, + outer: OuterProgress | None = None, + ) -> dict[PostExportKey, _PostExportValues]: + """The serial scorer's pass, which pooled scoring runs here for its + baseline passes alone; each is recorded for the execution record.""" + if reform_system is not None: + raise RuntimeError( + f"{label}: pooled post-export scoring runs reform passes in its " + "workers only." ) - for batches in _post_export_batch_ranges( - self.n_batches, self._pooling.settings.workers + wall, cpu = time.perf_counter(), time.process_time() + error_text: str | None = None + try: + return super()._score(keys, label=label, outer=outer) + except BaseException as error: + error_text = _post_export_error_text(error) + raise + finally: + self._baseline_passes.append( + { + "label": label, + "keys": len(keys), + "wall_seconds": round(time.perf_counter() - wall, 3), + "cpu_seconds": round(time.process_time() - cpu, 3), + "error": error_text, + } ) - ) + + def _score_baselines(self) -> None: + """Score every registered baseline plan here, before any worker starts. + + As the serial scorer does: one merged pass over every registered + plan, and if it raises, each consumer's own pass. The serial scorer + runs a consumer's own pass when that consumer opens; here every one + runs now, in the consumers' order, so no baseline engine is built in + this process while workers run (each worker's cap, and the plan's + 3 GiB for this process, are sized for reform passes). A consumer's own + pass that raises is kept, with its traceback as a note and without + its frames, and raised when that consumer opens; a refused batch file + propagates at once. + """ + if not self._unserved_baseline_plans: + return + self._run_merged_baseline_pass() + if not self._merged_baseline_failed: + return + for name, plan in self._unserved_baseline_plans.items(): + try: + self._own_baselines[name] = self._score( + plan, label=f"{name} baseline plan" + ) + except PostExportBatchFileError: + raise + except Exception as error: + self._own_baselines[name] = _without_traceback_frames( + error, + note="Raised by its own baseline pass in the certifying " + "process, before the worker pool started:", + ) + # After a failed pass, outside the handler: a full collection + # frees what its frames held in a cycle. + collect_pass_garbage() + + # ---- the pool ---------------------------------------------------------- def _reform_units(self, consumer: str) -> tuple[PostExportUnit, ...]: recorded = self._requests[consumer] @@ -7292,12 +7383,13 @@ def _reform_units(self, consumer: str) -> tuple[PostExportUnit, ...]: ) def _start(self) -> None: - """Run the merged baseline pass, then start the reform units. + """Score every baseline pass here, then start the pool on the reform + units. A start that failed is not tried again: every later consumer is - refused with :class:`PostExportPoolStoppedError`. A second run that - stops later refuses only what needs it (:meth:`_take`); what the - merged pass scored is still served. + refused with :class:`PostExportPoolStoppedError`. A pool that stops + later refuses only what needs it (:meth:`_take`); the baseline values + scored here are still served. """ if self._start_failure is not None: raise PostExportPoolStoppedError( @@ -7308,6 +7400,7 @@ def _start(self) -> None: self._batches() self._started = True try: + self._score_baselines() self._start_pool() except BaseException as error: self._start_failure = error @@ -7342,118 +7435,19 @@ def _new_pool(self) -> WorkerPool: ) def _start_pool(self) -> None: - merged = _ascending_period_plan( - key for plan in self._unserved_baseline_plans.values() for key in plan - ) - baseline_units = ( - self._baseline_units(None, "merged baseline plan", merged) if merged else () - ) + """Start the pool on one unit per reformed simulation, in the order + the consumers run; a plan that opens no reform starts no pool.""" reform_units = tuple( unit for name in self._requests for unit in self._reform_units(name) ) - self._units = {"baseline": len(baseline_units), "reform": len(reform_units)} - if not baseline_units and not reform_units: + self._units = {"reform": len(reform_units)} + if not reform_units: return - self._workers = max( - 1, - min( - self._pooling.settings.workers, - max(len(baseline_units), len(reform_units)), - ), - ) + self._workers = min(self._pooling.settings.workers, len(reform_units)) self._pool = self._new_pool() - if baseline_units: - self._run_merged_baseline(baseline_units, merged) - if self._merged_baseline_failed: - layout = [] - for name, recorded in self._requests.items(): - if recorded.baseline_plan: - layout.extend( - self._baseline_units( - name, f"{name} baseline plan", recorded.baseline_plan - ) - ) - layout.extend(self._reform_units(name)) - stream_units = tuple(layout) - self._units["fallback_baseline"] = len(stream_units) - len(reform_units) - else: - stream_units = reform_units - if stream_units: - self._stream_units = stream_units - self._stream_positions = list(range(len(stream_units))) - self._stream = self._pool.map(stream_units) - - def _run_merged_baseline( - self, units: Sequence[PostExportUnit], keys: Sequence[PostExportKey] - ) -> None: - label = units[0].passes[0].label - print( - f"Scoring post-export {label} ({len(keys)} key(s)) in " - f"{self.n_batches} batches of up to {self.max_batch_households:,} " - f"households, in {len(units)} pool unit(s) on up to {self._workers} " - "worker(s).", - flush=True, - ) - sweep = _WorkCounter( - stage_id="post_export_scoring", unit="scoring_batch", total=self.n_batches - ) - parts: dict[PostExportKey, list[tuple[np.ndarray, np.ndarray]]] = { - key: [] for key in keys - } - failure: PostExportUnitFailure | None = None - unfinished: WorkerPoolUnitError | None = None - results = self._pool.map(units) - try: - for unit, result in zip(units, results, strict=True): - self._report_timing(unit, result) - outcome = result.outcomes[0] - if isinstance(outcome, PostExportUnitFailure): - if outcome.batch_file_error: - # The scored file's integrity: no consumer's own - # pass could read the batch either. - _raise_post_export_worker_failure(outcome) - failure = failure or outcome - continue - if failure is None: - for key, key_parts in zip(keys, outcome.parts, strict=True): - parts[key].extend(key_parts) - sweep.advance( - unit.batch_stop - unit.batch_start, - pass_name=label, - batch=unit.batch_stop, - batches=self.n_batches, - ) - except WorkerPoolUnitError as error: - # A unit failed on every attempt: its worker ran out of memory, - # went over the cap or died. The serial scorer catches a - # MemoryError of its merged pass and falls back too; each - # consumer's own pass holds fewer keys per engine. - unfinished = error - finally: - results.close() - if failure is not None or unfinished is not None: - # As the serial scorer: every consumer then scores its own plan. - self._merged_baseline_failed = True - del parts - reason = ( - f"{type(unfinished).__name__}: {unfinished}" - if unfinished is not None - else f"{failure.error_name}: {failure.message}" - ) - self._merged_fallback_reason = reason - print( - f"Post-export merged baseline plan failed ({reason}); each " - "consumer scores its own baseline plan instead.", - flush=True, - ) - collect_pass_garbage() - if unfinished is not None: - # The stopped run closed the pool; the rest needs another. - self._pool = self._new_pool() - return - self._merged_baseline = { - key: _concatenate_post_export_parts(parts.pop(key)) for key in keys - } + self._stream_units = reform_units + self._stream_positions = list(range(len(reform_units))) + self._stream = self._pool.map(reform_units) def _report_timing( self, unit: PostExportUnit, result: PostExportUnitResult @@ -7480,8 +7474,8 @@ def _report_timing( } ) - def _take(self, consumer: str, simulation: int | None): - """The next run of stream units for ``(consumer, simulation)``, each + def _take(self, consumer: str, simulation: int): + """The next run of reform units for ``(consumer, simulation)``, each with its result, or with the ``WorkerPoolUnitError`` of a unit that failed on every attempt. @@ -7523,20 +7517,16 @@ def _take(self, consumer: str, simulation: int | None): if ours: taken.append((unit, result)) if not taken: - asked = ( - "baseline plan" - if simulation is None - else (f"reformed simulation {simulation}") - ) raise RuntimeError( - f"{consumer} asked for its {asked} out of the order its " - "engine-free dry run recorded; pooled post-export scoring " - "serves each consumer its recorded requests in that order." + f"{consumer} asked for its reformed simulation {simulation} out " + "of the order its engine-free dry run recorded; pooled " + "post-export scoring serves each consumer its recorded requests " + "in that order." ) return taken def _result_of(self, index: int) -> PostExportUnitResult: - """The result of the second run's unit at ``index``, the next one due. + """The result of the reform unit at ``index``, the next one due. Workers run ahead of the consumers, and the pool stops a run as soon as any unit in flight has failed on every attempt, which may be a @@ -7638,39 +7628,24 @@ def _baseline_for( or name not in self._unserved_baseline_plans ): raise RuntimeError( - f"{name}: the pool's merged baseline pass holds no values " - "for it; pooled post-export scoring scores nothing in this " - "process." + f"{name}: the merged baseline pass holds no values for it; " + "pooled post-export scoring scores no baseline pass after " + "its workers start." ) # The merged pass's values, served as the serial scorer serves them. return super()._baseline_for(name, baseline_plan) - # The merged pass failed: the consumer's own pass, from the stream. - parts: dict[PostExportKey, list[tuple[np.ndarray, np.ndarray]]] = { - key: [] for key in baseline_plan - } - failure: PostExportUnitFailure | WorkerPoolUnitError | None = None - for _, result in self._take(name, None): - # The serial scorer stops at the first batch that raises, so the - # first range in batch order that failed, either way, is raised. - if failure is not None: - continue - if isinstance(result, WorkerPoolUnitError): - failure = result - continue - outcome = result.outcomes[0] - if isinstance(outcome, PostExportUnitFailure): - failure = outcome - else: - for key, key_parts in zip(baseline_plan, outcome.parts, strict=True): - parts[key].extend(key_parts) - if failure is not None: - del parts - if isinstance(failure, WorkerPoolUnitError): - raise failure - _raise_post_export_worker_failure(failure) - return { - key: _concatenate_post_export_parts(parts.pop(key)) for key in baseline_plan - }, False + # The merged pass failed: the consumer's own pass, scored before the + # pool started. + if name not in self._own_baselines: + raise RuntimeError( + f"{name}: no baseline pass of its own was scored before the pool " + "started; pooled post-export scoring scores no baseline pass " + "after its workers start." + ) + outcome = self._own_baselines.pop(name) + if isinstance(outcome, BaseException): + raise outcome + return outcome, False def _open_reform_for(self, consumer: _PostExportConsumer, reform): """Hand ``consumer`` its next reformed simulation, if it is the reform @@ -7833,6 +7808,8 @@ def execution_record(self) -> dict[str, object]: (started or settings).worker_environment or () ), "units": dict(self._units), + # The baseline passes run in this process, before the pool. + "baseline_passes": [dict(record) for record in self._baseline_passes], "resources": self._pooling.resources, # Why the merged baseline pass fell back to each consumer's own # pass, if it did. diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index f71c745368..e3f01fc64d 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -101,22 +101,22 @@ Every stage records wall time, CPU time and peak resident memory (sampled every 0.5 s with psutil, else the process peak); every batch-outer scoring -pass is one line of ``passes.jsonl``. With pooled scoring, a line is one pass -a pool worker ran (a range of the shared baseline pass, or one reform pass), -with the worker's process ID, its wall and CPU time, and the worker's memory -footprint and peak resident memory; each stage records the CPU time of the -worker passes whose results reached it (``worker_cpu_seconds``), and the -report's ``post_export_scoring.execution`` holds the pool's settings and -report (worker starts, failed attempts, peak worker memory). A line is written +pass is one line of ``passes.jsonl``, naming the process that ran it. With +pooled scoring the baseline passes run in this process, before the pool +starts, and are written as in the serial path; a reform pass is one pass a +pool worker ran, with the worker's process ID, its wall and CPU time, and the +worker's memory footprint and peak resident memory. Each stage records the +CPU time of the worker passes whose results reached it +(``worker_cpu_seconds``), and the report's ``post_export_scoring.execution`` +holds the pool's settings and report (worker starts, failed attempts, peak +worker memory) and each baseline pass run here. A worker's line is written when the pass's results reach this process, so a pass whose results never do (the stage stopped, or the scorer closed first) has none, and the remaining passes of a stage that stopped early are written, and counted, under the stage that passes over them. A unit that fails on every attempt fails the stage that -asks for it (a range of the merged baseline pass instead makes every stage -score its own baseline pass), and the pool goes on with the other units in -fresh workers; if no worker can start, each later stage that needs the pool -records that it could not run as the probe's own failure, not the -release's. +asks for it, and the pool goes on with the other units in fresh workers; if +no worker can start, each later stage that needs the pool records that it +could not run as the probe's own failure, not the release's. Usage:: @@ -1630,10 +1630,11 @@ def run(self, name: str, fn: Callable[[], Mapping[str, Any]]) -> dict[str, Any]: return record -def _timed_scorer_class(builder, passes_path: Path, clock: StageClock): - """The release scorer, with one ``passes.jsonl`` line per scoring pass.""" +def _timed_scorer_class(builder, passes_path: Path, clock: StageClock, base=None): + """The release scorer (``base``, the serial one unless given), with one + ``passes.jsonl`` line per scoring pass it runs in this process.""" - base = builder._HouseholdBatchedPostExportScorer + base = base or builder._HouseholdBatchedPostExportScorer class TimedScorer(base): def _score(self, keys, *, label, reform_system=None, **options): @@ -1654,6 +1655,7 @@ def _score(self, keys, *, label, reform_system=None, **options): "keys": len(keys), "reform": reform_system is not None, "batches": self.n_batches, + "process": "certifying process", "wall_seconds": round(time.perf_counter() - wall, 3), "cpu_seconds": round(time.process_time() - cpu, 3), "rss_before_gib": _gib(before), @@ -2579,8 +2581,9 @@ def _open_scorer(self) -> dict[str, Any]: As in certification, every stage's baseline plan is registered, so one merged baseline pass serves them all; with ``post_export_pooling`` - the recorded requests are scored in the shared worker pool, and each - pass a worker ran is one line of ``passes.jsonl``. + the baseline passes run here and the recorded reform passes in the + shared worker pool, and each pass a worker ran is one line of + ``passes.jsonl``, as is each pass run here. """ builder = self.builder requests = self._record_stage_requests() @@ -2597,7 +2600,14 @@ def _open_scorer(self) -> dict[str, Any]: ) self.scoring_plan = plan if self.post_export_pooling is not None: - scorer = builder._PooledPostExportScorer( + # Its baseline passes run here, each timed as in the serial path. + scorer_cls = _timed_scorer_class( + builder, + self.passes_path, + self.clock, + base=builder._PooledPostExportScorer, + ) + scorer = scorer_cls( self.export_path, maximum_microsim_batch_size=self.batch_size, consumer_requests=plan.consumer_requests, From 6eed915268955e9f769c115e20248fd6fb0f8619 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:39:03 +0400 Subject: [PATCH 21/26] Test review round 1's findings on baseline passes in the certifying process Failing tests: a post-export pool unit refuses a baseline unit; the execution record holds the certifying process's memory footprint when the workers start (None when no pool starts); closing the scorer drops the baseline values of stages that never opened; a kept baseline error is cut from the exceptions it was raised from or while handling, so a caller's own handled exception keeps its traceback. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pool.py | 24 +++--- .../us/test_us_post_export_pooled_scoring.py | 86 +++++++++++++++++++ 2 files changed, 98 insertions(+), 12 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py index 4931b13008..9b20e6c6a2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pool.py @@ -70,21 +70,21 @@ def test_a_unit_names_its_batches_and_its_reform(pool_module) -> None: "post-export reform_validation reformed simulation 2 (1 pass(es), first " "'reform_validation reform x'), all 4 batch(es)" ) - baseline = _unit( - pool_module, - consumer=None, - reformed_simulation=None, - reform=None, - passes=(pool_module.PostExportPass("merged baseline plan", (KEY,)),), - batch_start=1, - batch_stop=3, - ) - assert baseline.describe() == "post-export merged baseline plan, batches 2-3 of 4" + part = _unit(pool_module, batch_start=1, batch_stop=3) + assert part.describe().endswith(", batches 2-3 of 4") for start, stop in ((0, 0), (3, 2), (-1, 2), (0, 5)): with pytest.raises(ValueError, match="non-empty range"): _unit(pool_module, batch_start=start, batch_stop=stop) - with pytest.raises(ValueError, match="names no reformed simulation"): - _unit(pool_module, reform=None) + # Baseline passes run in the certifying process, never in a worker. + for consumer in (None, "reform_validation"): + with pytest.raises(ValueError, match="baseline passes run in the certifying"): + _unit( + pool_module, + consumer=consumer, + reformed_simulation=None, + reform=None, + passes=(pool_module.PostExportPass("merged baseline plan", (KEY,)),), + ) with pytest.raises(ValueError, match="names the consumer"): _unit(pool_module, consumer=None) with pytest.raises(TypeError, match="reformed simulation's number"): diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index 4bb1c0a86e..82ab515d1f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -704,6 +704,8 @@ def asks(total): assert execution["units"] == {"reform": 2} assert (execution["requested_workers"], execution["workers"]) == (8, 2) assert execution["report"]["max_live_workers"] <= 2 + # What this process held when the workers started, after its baselines. + assert execution["certifying_process_footprint_bytes_at_pool_start"] > 0 def test_a_consumer_without_reforms_starts_no_pool( @@ -727,6 +729,7 @@ def test_a_consumer_without_reforms_starts_no_pool( 0, None, ) + assert execution["certifying_process_footprint_bytes_at_pool_start"] is None def test_workers_get_the_lock_check_record_and_the_set_environment( @@ -1434,3 +1437,86 @@ def run(scorer, kept=None): serial.pop("second notes") assert pooled == serial assert kept == [None] + + +# --------------------------------------------------------------------------- +# Baseline passes in the certifying process: review round 1 +# --------------------------------------------------------------------------- + + +def _fallback_plan(builder): + """Two consumers whose merged plan (three keys) runs out of memory under + ``MEMORY_KEYS=2`` while each one's own plan (two keys) fits.""" + consumers = { + "first": _baseline_consumer("age", "snap"), + "second": _baseline_consumer("age", "income_tax"), + } + plan = builder._post_export_scoring_plan( + n_households=N_HOUSEHOLDS, + maximum_microsim_batch_size=BATCH_SIZE, + consumers=consumers, + ) + return consumers, plan + + +def test_closing_drops_the_baselines_of_stages_that_never_opened( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """After a failed merged pass every stage's own baseline is scored when + the first stage opens; a stage that never opens (the probe's held-out + reports, or every stage after one that stopped certification) must not + keep its values alive once the scorer closes.""" + monkeypatch.setenv(MEMORY_KEYS, "2") + consumers, plan = _fallback_plan(builder) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + scoring = scorer.open_consumer("first", plan.baseline_plan("first")) + consumers["first"](scoring.simulate) + assert set(scorer._own_baselines) == {"second"} + finally: + scorer.close() + assert scorer._own_baselines == {} + + +def test_a_kept_baseline_error_leaves_the_callers_exception_alone( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """A stage's own baseline error is kept until that stage opens. It is cut + from the exceptions it was raised from or while handling, whose text stays + in its note, so it holds none of them and changes none of them: here the + first stage opens while its caller handles an exception of its own.""" + monkeypatch.setenv(FAIL_ON_HOUSEHOLDS, json.dumps({"snap": [1]})) + consumers = { + "first": _baseline_consumer("age"), + "second": _baseline_consumer("age", "snap"), + } + plan = builder._post_export_scoring_plan( + n_households=N_HOUSEHOLDS, + maximum_microsim_batch_size=BATCH_SIZE, + consumers=consumers, + ) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + try: + raise LookupError("the caller's own exception") + except LookupError as handled: + scorer.open_consumer("first", plan.baseline_plan("first")) + assert handled.__traceback__ is not None + kept = scorer._own_baselines["second"] + assert (kept.__traceback__, kept.__context__, kept.__cause__) == ( + None, + None, + None, + ) + (note,) = kept.__notes__ + assert "Traceback" in note and "fixture engine refuses snap" in note + with pytest.raises(RuntimeError, match="fixture engine refuses snap"): + scorer.open_consumer("second", plan.baseline_plan("second")) + finally: + scorer.close() From 3ad85e789c314b71e9c771346bbee41b9082d9e5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:46:07 +0400 Subject: [PATCH 22/26] Fix review round 1 on baseline passes in the certifying process - A post-export pool unit refuses a unit without a reform: baseline passes run in the certifying process, never in a worker. - The execution record holds the certifying process's memory footprint when the workers start, the check on the plan's 3 GiB for it. - Closing the scorer drops the baseline values of stages that never opened. - A kept baseline error is cut from the exceptions it was raised from or while handling (their text stays in its note), so it holds none of them and leaves a caller's handled exception unchanged. - PostExportPoolStoppedError's docstring, the release build rule and the probe's description now say what a failure to start and a fallback do: which request raises which error, and that after a failed merged pass every stage's own pass runs when the first stage opens and is held until its stage opens. The planned-peak comment names what is not measured. - The byte-identity test reads the new footprint field. Co-Authored-By: Claude Opus 5.5 --- docs/us-release-build-rule.md | 40 ++++++++---- .../build/us_runtime/post_export_pool.py | 64 ++++++++++--------- .../us/test_us_post_export_pooled_scoring.py | 6 +- tools/build_us_fiscal_refresh_release.py | 50 +++++++++------ tools/probe_us_post_export.py | 10 +-- 5 files changed, 103 insertions(+), 67 deletions(-) diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index ef141b3c4e..fa899574f3 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -536,9 +536,18 @@ one Microsimulation over the whole file. pass. If it raises (`MemoryError` included), every stage's own baseline pass runs next, in the order the stages run, where the serial scorer runs each one when its stage opens; a stage whose own pass raised gets that - error when it opens. A changed batch file stops scoring at once. Each - batch engine is released before the next is built, so no baseline engine - is held in the certifying process while workers run. + error when it opens, with the original traceback as a note. A changed + batch file stops scoring at once. Each batch engine is released before + the next is built, so no baseline engine is held in the certifying + process while workers run. + - After a failed shared pass this differs from the serial scorer in time + and memory, not in values: every stage's own pass runs when the first + stage opens (the export probe's held-out reports' too, which it never + opens), so the build telemetry and the probe count them all under that + stage, and a stage whose own pass failed gets its error only after the + other stages' own passes have run. Every stage's own values are held + until that stage opens or the scorer closes; a key several stages plan + is held once per stage. - The pool then runs one unit per reformed simulation, holding all of that simulation's recorded passes over every batch, in the order the stages run: a worker builds the reform's rules once per unit, as the serial @@ -566,12 +575,16 @@ one Microsimulation over the whole file. even when it failed while workers were still running an earlier stage's units, and the pool goes on with the other units in fresh workers. The shared pool stops a run at such a failure, so the units then in flight, - the one due among them, start again in the fresh pool. A pool whose - workers cannot start refuses every request that needs it - (`PostExportPoolStoppedError`); a stage's baseline values, scored in the - certifying process, are still served. Each of these is a - `WorkerPoolError` and stops certification, the held-out reports included, - where the serial scorer, which has no memory cap, may have finished. + the one due among them, start again in the fresh pool. When the pool's + workers cannot start, the first request that needs them raises the + pool's `WorkerPoolError` and every later one `PostExportPoolStoppedError`; + a stage's baseline values, scored in the certifying process, are still + served. When the pool cannot be built at all, the first stage's opening + raises that error and every later stage is refused with + `PostExportPoolStoppedError`, as after a changed batch file. Each of + these is a `WorkerPoolError` and stops certification, the held-out + reports included, where the serial scorer, which has no memory cap, may + have finished. - Each stage then runs as in the serial path and builds its own reforms (the smoke records each list edit's resolved lists from its own). Its baseline is served its recorded plan, and each reformed simulation its recorded @@ -597,8 +610,9 @@ one Microsimulation over the whole file. `execution`: `{"mode": "serial"}`, or the pool's settings, how the worker count was chosen, the plan's memory and core readings, the number of reform units, each baseline pass run in the certifying process (its - label, keys, wall and CPU time, and error if it raised), why the shared - pass fell back if it did, and the report of every pool the scorer ran + label, keys, wall and CPU time, and error if it raised), that process's + memory footprint when the workers started, why the shared pass fell back + if it did, and the report of every pool the scorer ran (worker starts, failed attempts, peak worker memory). That record is run metadata, outside every output comparison (decision 1.1 · 1). - The 5 GiB per worker comes from reform passes (1.4 · 6's one-batch check @@ -606,7 +620,9 @@ one Microsimulation over the whole file. The plan's 3 GiB for the certifying process applies while workers run, after its baseline engines are released; its peak during the baseline passes is the serial scorer's, with no worker running. Neither figure - has been measured at certification's 5,000-household batches. + has been measured at certification's 5,000-household batches, and freed + memory is not always returned to the system, so the footprint recorded + when the workers start is the check on the 3 GiB. - Each batch engine keeps policyengine-us's projection of the release year to its last CPI-U year (2035), because the plans request keys in later years (reform validation reaches past 2025). The build's own simulations hold diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py index a205769966..3509a870ef 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_pool.py @@ -1,18 +1,18 @@ """The units, results and worker entry points of pooled US post-export scoring. The release tool (``tools/build_us_fiscal_refresh_release.py``) scores the -written release H5 in household batches. With pooled scoring it sends the -scoring to worker processes of the shared pool -(:mod:`microcosm.build.worker_pool`) and runs each post-export consumer again -in its own process over the results: +written release H5 in household batches. With pooled scoring it runs every +baseline pass in its own process, then sends the reform passes to worker +processes of the shared pool (:mod:`microcosm.build.worker_pool`) and runs +each post-export consumer again in its own process over the results: - the engine-free dry run records every request each consumer makes (:mod:`microcosm.build.us_runtime.post_export_requests`), and which of a reformed simulation's requests the serial scorer scores together in one pass; -- each :class:`PostExportUnit` is a run of one or more such passes over a range - of the H5's household batches: the merged baseline plan over a range of - batches, or every pass of one reformed simulation over all of them; +- each :class:`PostExportUnit` is every pass of one reformed simulation over + the H5's household batches (a baseline unit is refused: each worker's + memory cap is sized for reform passes); - a worker reads each batch from the file the release tool's scorer wrote it to, builds one engine per batch, scores the pass's keys on it in ascending period order, applies the same refusals as the serial scorer, and returns @@ -110,8 +110,7 @@ class PostExportPass: Attributes: label: The pass's name in errors and progress, as the serial scorer - names it (``"merged baseline plan"``, ``" baseline - plan"``, ``" reform @, ..."``). + names it (``" reform @, ..."``). keys: Unique keys in ascending period order. """ @@ -140,16 +139,19 @@ def __post_init__(self) -> None: @dataclass(frozen=True) class PostExportUnit: - """Passes a worker runs over the household batches ``[batch_start, batch_stop)``. + """A reformed simulation's passes, which a worker runs over the household + batches ``[batch_start, batch_stop)``. + + Baseline passes run in the certifying process, never in a worker (a + worker's memory cap is sized for reform passes; in the 5% export probe a + baseline pass over one 2,000-household batch went over it), so a unit + without a reform is refused. Attributes: - consumer: The consumer whose passes these are, or ``None`` for the - merged baseline plan of every consumer. - reformed_simulation: For a reform unit, which of the consumer's - ``simulate(reform)`` calls made the simulation, numbered from 0; - ``None`` for a baseline unit. - reform: ``None`` for a baseline unit; otherwise the description the - worker rebuilds the reform from + consumer: The consumer whose passes these are. + reformed_simulation: Which of the consumer's ``simulate(reform)`` + calls made the simulation, numbered from 0. + reform: The description the worker rebuilds the reform from (:func:`~microcosm.build.us_runtime.post_export_requests.build_post_export_reform`). The worker builds the reform's rules once and scores every pass with them, as the serial scorer does for one reformed simulation. @@ -161,9 +163,9 @@ class PostExportUnit: simulation, whatever part of the H5 this unit scores. """ - consumer: str | None - reformed_simulation: int | None - reform: PostExportReform | None + consumer: str + reformed_simulation: int + reform: PostExportReform passes: tuple[PostExportPass, ...] batch_start: int batch_stop: int @@ -190,11 +192,12 @@ def __post_init__(self) -> None: if self.consumer is not None and ( not isinstance(self.consumer, str) or not self.consumer ): - raise ValueError("PostExportUnit.consumer must be a name or None.") + raise ValueError("PostExportUnit.consumer must be a name.") if self.reform is None: - if self.reformed_simulation is not None: - raise ValueError("A baseline unit names no reformed simulation.") - return + raise ValueError( + "A post-export pool unit needs a reform: baseline passes run in " + "the certifying process, never in a worker." + ) check_post_export_reform(self.reform) if self.consumer is None: raise ValueError("A reform unit names the consumer that asked for it.") @@ -212,8 +215,6 @@ def describe(self) -> str: batches = ( f"batches {self.batch_start + 1}-{self.batch_stop} of {self.n_batches}" ) - if self.reform is None: - return f"post-export {self.passes[0].label}, {batches}" return ( f"post-export {self.consumer} reformed simulation " f"{self.reformed_simulation} ({len(self.passes)} pass(es), first " @@ -441,9 +442,14 @@ def score_post_export_unit(worker, unit: PostExportUnit) -> PostExportUnitResult #: The share of the machine's memory a build may plan to use (decision 1.1 · 2). MEMORY_BUDGET_FRACTION = 0.75 -#: The certifying process's planned peak while workers score: the release -#: tool's imports (about 1.1-1.2 GiB) and the baseline arrays it holds (up to -#: about 1.1 GiB at national size). +#: The certifying process's planned peak while workers score, after its +#: baseline passes: the release tool's imports (about 1.1-1.2 GiB) and the +#: merged baseline arrays it holds (up to about 1.1 GiB at national size). +#: Not measured: what its baseline passes leave resident (freed memory is not +#: always returned to the system), and, after a failed merged pass, every +#: stage's own baseline arrays, held at once (a key several stages plan is +#: held once per stage). The execution record reports the process's footprint +#: when the workers start. PARENT_PEAK_BYTES = 3 * _GIB #: One worker's planned peak over its replacement interval (1.4 · 6's one-batch diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index 82ab515d1f..cd9ad16501 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -322,6 +322,7 @@ def run(workers: int): ("merged baseline plan", merged_keys, None) ] del execution["baseline_passes"] + assert execution.pop("certifying_process_footprint_bytes_at_pool_start") > 0 assert execution == { "mode": "pooled", "chosen_by": "test", @@ -599,8 +600,9 @@ def test_a_changed_batch_file_stops_pooled_scoring( "reform_coverage_smoke", plan.baseline_plan("reform_coverage_smoke") ) # Nothing more is served, and no consumer falls back to its own pass: - # a pool that could not start refuses every later consumer with a - # WorkerPoolError, which the held-out reports pass on. + # scoring that could not start (here its merged baseline pass, run in + # this process) refuses every later consumer with a WorkerPoolError, + # which the held-out reports pass on. with pytest.raises(builder.PostExportPoolStoppedError, match="could not start"): scorer.open_consumer( "reform_validation", plan.baseline_plan("reform_validation") diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index d7c0a01f4f..74ce6f6612 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -6451,23 +6451,15 @@ def _post_export_error_text(error: BaseException) -> str: def _without_traceback_frames(error: BaseException, *, note: str) -> BaseException: - """``error``, kept to raise later: its formatted traceback is added as a - note after ``note``, and its frames, with those of every exception it was - raised from or while handling, are dropped, so it holds no failed pass's - per-batch values.""" + """``error``, kept to raise later, holding no frames: its formatted + traceback, with those of the exceptions it was raised from or while + handling, is added as a note after ``note``; then its traceback and its + links to those exceptions are dropped (each of them is left unchanged), so + it holds no failed pass's per-batch values and no caller's exception.""" error.add_note(note + "\n" + "".join(traceback.format_exception(error))) - pending, seen = [error], set() - while pending: - linked = pending.pop() - if id(linked) in seen: - continue - seen.add(id(linked)) - linked.__traceback__ = None - pending.extend( - chained - for chained in (linked.__cause__, linked.__context__) - if chained is not None - ) + error.__traceback__ = None + error.__cause__ = None + error.__context__ = None return error @@ -6916,8 +6908,15 @@ def _post_export_unit_failure( class PostExportPoolStoppedError(WorkerPoolError): - """Pooled post-export scoring stopped earlier, so this request, which - needs its workers, is not served. The error it stopped on is the cause. + """Pooled post-export scoring stopped earlier, so this request is not + served. The error it stopped on is the cause. + + Either scoring could not start, and every later stage is refused: a + baseline pass in the certifying process stopped (a changed batch file, + an interrupt) or the pool could not be built. Or the pool's workers + stopped serving (none could start, or the scorer closed), and every later + request that needs them is refused; baseline values scored in the + certifying process are still served. A ``WorkerPoolError``, so the held-out reports stop certification on it, as on the pool failure itself, instead of recording a measurement as @@ -7260,9 +7259,13 @@ def __init__( self._stream: Iterator[PostExportUnitResult] | None = None self._stream_units: tuple[PostExportUnit, ...] = () self._next_unit = 0 - # Why the pool could not start, or stopped serving its second run. + # Why scoring could not start (a baseline pass here, or building the + # pool), or why the pool's workers stopped serving. self._start_failure: BaseException | None = None self._stopped: BaseException | None = None + # This process's memory footprint when the pool started, after its + # baseline passes (None until then). + self._footprint_at_pool_start: int | None = None # The settings the pool was started with, and the reports of the pools # replaced since (a pool closes when a unit fails on every attempt). self._pool_settings: WorkerPoolSettings | None = None @@ -7444,6 +7447,7 @@ def _start_pool(self) -> None: if not reform_units: return self._workers = min(self._pooling.settings.workers, len(reform_units)) + self._footprint_at_pool_start = process_memory_bytes(os.getpid()) self._pool = self._new_pool() self._stream_units = reform_units self._stream_positions = list(range(len(reform_units))) @@ -7808,8 +7812,12 @@ def execution_record(self) -> dict[str, object]: (started or settings).worker_environment or () ), "units": dict(self._units), - # The baseline passes run in this process, before the pool. + # The baseline passes run in this process, before the pool, and + # this process's footprint once they had run and the pool started. "baseline_passes": [dict(record) for record in self._baseline_passes], + "certifying_process_footprint_bytes_at_pool_start": ( + self._footprint_at_pool_start + ), "resources": self._pooling.resources, # Why the merged baseline pass fell back to each consumer's own # pass, if it did. @@ -7826,6 +7834,8 @@ def execution_record(self) -> dict[str, object]: def close(self) -> None: stream, self._stream = self._stream, None self._serving = None + # The baselines of stages that never opened. + self._own_baselines.clear() try: if stream is not None: # An unfinished run closes the pool, stopping its workers. diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index e3f01fc64d..09ff51b05c 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -103,10 +103,12 @@ every 0.5 s with psutil, else the process peak); every batch-outer scoring pass is one line of ``passes.jsonl``, naming the process that ran it. With pooled scoring the baseline passes run in this process, before the pool -starts, and are written as in the serial path; a reform pass is one pass a -pool worker ran, with the worker's process ID, its wall and CPU time, and the -worker's memory footprint and peak resident memory. Each stage records the -CPU time of the worker passes whose results reached it +starts, and are written as in the serial path; after a failed merged pass, +though, every registered stage's own pass runs then (the held-out reports' +too, which the probe never opens), all under the first stage. A reform pass +is one pass a pool worker ran, with the worker's process ID, its wall and CPU +time, and the worker's memory footprint and peak resident memory. Each stage +records the CPU time of the worker passes whose results reached it (``worker_cpu_seconds``), and the report's ``post_export_scoring.execution`` holds the pool's settings and report (worker starts, failed attempts, peak worker memory) and each baseline pass run here. A worker's line is written From b0cd785753518fcee33ec4f38930d80f94d0596a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:08:36 +0400 Subject: [PATCH 23/26] Test review round 2's findings on kept baseline errors and probe rows Failing tests: a kept own-baseline error keeps the cause chain the run outcome reads (a failure raised while a MemoryError unwinds stays out of memory), with its tracebacks dropped and a caller's handled exception left unchanged; an error raised while a termination unwinds stops scoring at once, before later stages' own passes; an error whose traceback cannot be formatted is still kept for its stage; the probe's passes.jsonl rows say whether each pass failed. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pooled_scoring.py | 172 +++++++++++++++++- .../us/test_us_post_export_probe.py | 1 + 2 files changed, 163 insertions(+), 10 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index cd9ad16501..2d60c0e33d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -1489,10 +1489,10 @@ def test_a_kept_baseline_error_leaves_the_callers_exception_alone( tmp_path, monkeypatch, ) -> None: - """A stage's own baseline error is kept until that stage opens. It is cut - from the exceptions it was raised from or while handling, whose text stays - in its note, so it holds none of them and changes none of them: here the - first stage opens while its caller handles an exception of its own.""" + """A stage's own baseline error is kept until that stage opens, with its + traceback as a note. The tracebacks raised inside its pass are dropped; a + caller's own exception, which it was raised while handling, keeps its + traceback: here the first stage opens while its caller handles one.""" monkeypatch.setenv(FAIL_ON_HOUSEHOLDS, json.dumps({"snap": [1]})) consumers = { "first": _baseline_consumer("age"), @@ -1508,17 +1508,169 @@ def test_a_kept_baseline_error_leaves_the_callers_exception_alone( try: raise LookupError("the caller's own exception") except LookupError as handled: + callers_exception = handled scorer.open_consumer("first", plan.baseline_plan("first")) - assert handled.__traceback__ is not None kept = scorer._own_baselines["second"] - assert (kept.__traceback__, kept.__context__, kept.__cause__) == ( - None, - None, - None, - ) + assert kept.__traceback__ is None + assert kept.__context__ is callers_exception + assert callers_exception.__traceback__ is not None (note,) = kept.__notes__ assert "Traceback" in note and "fixture engine refuses snap" in note with pytest.raises(RuntimeError, match="fixture engine refuses snap"): scorer.open_consumer("second", plan.baseline_plan("second")) finally: scorer.close() + + +# --------------------------------------------------------------------------- +# Baseline passes in the certifying process: review round 2 +# --------------------------------------------------------------------------- + + +def _three_baseline_consumers(builder): + consumers = { + "first": _baseline_consumer("age"), + "second": _baseline_consumer("age", "snap"), + "third": _baseline_consumer("age", "income_tax"), + } + plan = builder._post_export_scoring_plan( + n_households=N_HOUSEHOLDS, + maximum_microsim_batch_size=BATCH_SIZE, + consumers=consumers, + ) + return consumers, plan + + +def _failing_passes(monkeypatch, builder, failures): + """Make ``_score_post_export_batches`` raise for some pass labels: + ``failures`` maps a label to a function that raises. Returns every label + scored, in order.""" + original = builder._score_post_export_batches + labels: list[str] = [] + + def scoring(*arguments, label, **options): + labels.append(label) + if label in failures: + failures[label]() + return original(*arguments, label=label, **options) + + monkeypatch.setattr(builder, "_score_post_export_batches", scoring) + return labels + + +def _raise_merged_out_of_memory(): + raise MemoryError("fixture merged pass out of memory") + + +def test_a_kept_baseline_error_keeps_what_the_run_outcome_reads( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """The build's run outcome reads an error's cause chain: a failure raised + while a MemoryError unwinds is out of memory. A kept own-baseline error + keeps that chain, without its tracebacks, as the serial scorer raises it.""" + from microcosm.build.run_outcome import classify_failure + + def raise_during_out_of_memory(): + try: + raise MemoryError("fixture batch engine out of memory") + except MemoryError: + # Raised while handling it, so the MemoryError is its context. + raise RuntimeError("fixture release after the engine failed") # noqa: B904 + + consumers, plan = _three_baseline_consumers(builder) + _failing_passes( + monkeypatch, + builder, + { + "merged baseline plan": _raise_merged_out_of_memory, + "second baseline plan": raise_during_out_of_memory, + }, + ) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + scorer.open_consumer("first", plan.baseline_plan("first")) + kept = scorer._own_baselines["second"] + assert isinstance(kept.__context__, MemoryError) + assert (kept.__traceback__, kept.__context__.__traceback__) == (None, None) + assert classify_failure(kept).error_code == "OUT_OF_MEMORY" + with pytest.raises(RuntimeError, match="fixture release") as raised: + scorer.open_consumer("second", plan.baseline_plan("second")) + assert classify_failure(raised.value).error_code == "OUT_OF_MEMORY" + finally: + scorer.close() + + +def test_a_baseline_pass_stopped_by_a_termination_stops_scoring_at_once( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """An error raised while SIGTERM (``BuildTerminatedError``) or an + interrupt unwinds is not kept for its stage: it stops scoring at once, + before any later stage's own pass runs, as the build must stop.""" + from microcosm.build.run_outcome import classify_failure + from microcosm.build.termination import BuildTerminatedError + + def raise_while_terminated(): + try: + raise BuildTerminatedError() + except BuildTerminatedError: + # Raised while handling it, so the termination is its context. + raise RuntimeError("fixture cleanup failed while stopping") # noqa: B904 + + consumers, plan = _three_baseline_consumers(builder) + labels = _failing_passes( + monkeypatch, + builder, + { + "merged baseline plan": _raise_merged_out_of_memory, + "second baseline plan": raise_while_terminated, + }, + ) + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + with pytest.raises(RuntimeError, match="fixture cleanup") as raised: + scorer.open_consumer("first", plan.baseline_plan("first")) + assert classify_failure(raised.value).error_code == "TERMINATED" + assert labels == [ + "merged baseline plan", + "first baseline plan", + "second baseline plan", + ] + finally: + scorer.close() + + +def test_a_kept_baseline_error_whose_traceback_cannot_be_formatted_is_kept( + builder, + pooled_reforms, + tmp_path, + monkeypatch, +) -> None: + """Formatting the kept error's traceback can itself run out of memory; + the error is then kept with a note that says so, and its stage gets it + as the serial scorer raises it, instead of every stage being refused.""" + import traceback + + monkeypatch.setenv(FAIL_ON_HOUSEHOLDS, json.dumps({"snap": [1]})) + consumers, plan = _three_baseline_consumers(builder) + + def out_of_memory(*arguments, **options): + raise MemoryError("fixture formatting out of memory") + + scorer = _pooled_scorer(builder, plan, tmp_path, 1) + try: + monkeypatch.setattr(traceback, "format_exception", out_of_memory) + scorer.open_consumer("first", plan.baseline_plan("first")) + monkeypatch.undo() + (note,) = scorer._own_baselines["second"].__notes__ + assert "could not be formatted" in note + with pytest.raises(RuntimeError, match="fixture engine refuses snap"): + scorer.open_consumer("second", plan.baseline_plan("second")) + scorer.open_consumer("third", plan.baseline_plan("third")) + finally: + scorer.close() diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py index 69e89fcd33..ec6bec92ee 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_probe.py @@ -1358,6 +1358,7 @@ def passes(directory): # The baseline passes ran in this process, as in the serial probe; the # workers ran the reform passes. assert all(row["process"] == "certifying process" for row in serial_passes) + assert all(row["failed"] is False for row in [*serial_passes, *pooled_passes]) in_workers = [row for row in pooled_passes if row["process"] == "pool worker"] here = [row for row in pooled_passes if row["process"] == "certifying process"] assert len(in_workers) + len(here) == len(pooled_passes) From a47632877ab4695bd193e349b77d5f5ebca908ce Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:20:12 +0400 Subject: [PATCH 24/26] Fix review round 2 on kept baseline errors, probe rows and docs - A kept own-baseline error keeps the exceptions it was raised from or while handling, so the build's run outcome still reads them (out of memory, terminated); only the tracebacks raised inside its pass are dropped, and the exception the caller was handling is left unchanged. - An error raised while the build is being interrupted or terminated stops scoring at once instead of waiting for later stages' own passes. - A kept error whose traceback cannot be formatted (out of memory) is kept with a short note instead of stopping every stage. - The export probe's passes.jsonl rows for passes in the certifying process say whether the pass failed, as worker rows do. - The release build rule, the agent guide, the probe's description, the plan's docstring and the Route A README now say that only reform passes go to the pool, and that the recorded footprint at pool start is reported, not checked. Co-Authored-By: Claude Opus 5.5 --- docs/agent-guide.md | 3 +- docs/us-release-build-rule.md | 19 ++++-- tools/build_us_fiscal_refresh_release.py | 83 ++++++++++++++++++++---- tools/probe_us_post_export.py | 12 ++-- tools/route_a/README.md | 7 +- 5 files changed, 97 insertions(+), 27 deletions(-) diff --git a/docs/agent-guide.md b/docs/agent-guide.md index e797bfbfb2..b3e0582565 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -435,7 +435,8 @@ tier's `releases//`, runs only offline, and leaves publication to Max. The US fiscal-refresh builder scores its written H5 in household batches, -in the shared worker pool unless `MICROCOSM_POST_EXPORT_WORKERS=serial` +with the reform passes in the shared worker pool unless +`MICROCOSM_POST_EXPORT_WORKERS=serial` (see [the release build rule](us-release-build-rule.md#post-export-scoring)). Alongside its out-of-sample reports, it writes `us_ssi_social_security_holdout.json`: the household-weighted share of SSI diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index fa899574f3..2b40ed6ca1 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -504,9 +504,10 @@ one Microsimulation over the whole file. Nothing records the descriptors in a file; pooled scoring (next item) and the guard sweep below rebuild each reform from its descriptor in the worker that scores it. -- Certification scores in the shared worker pool by default - (`_PooledPostExportScorer`, `microcosm.build.worker_pool`), and the stages - run afterwards in the certifying process, over the results. The worker +- Certification scores the reform passes in the shared worker pool by + default (`_PooledPostExportScorer`, `microcosm.build.worker_pool`), after + running the baseline passes itself, and the stages run afterwards in the + certifying process, over the results. The worker settings are tracker decision 1.4 · 6's, until task 2.6 · 2's planner replaces them (`plan_post_export_workers` in `microcosm.build.us_runtime.post_export_pool`): @@ -536,8 +537,11 @@ one Microsimulation over the whole file. pass. If it raises (`MemoryError` included), every stage's own baseline pass runs next, in the order the stages run, where the serial scorer runs each one when its stage opens; a stage whose own pass raised gets that - error when it opens, with the original traceback as a note. A changed - batch file stops scoring at once. Each batch engine is released before + error when it opens, with the original traceback as a note, and the + exceptions it was raised from or while handling, so the build's run + outcome still reads them (out of memory, terminated). A changed batch + file, or an error raised while the build is being interrupted or + terminated, stops scoring at once. Each batch engine is released before the next is built, so no baseline engine is held in the certifying process while workers run. - After a failed shared pass this differs from the serial scorer in time @@ -621,8 +625,9 @@ one Microsimulation over the whole file. after its baseline engines are released; its peak during the baseline passes is the serial scorer's, with no worker running. Neither figure has been measured at certification's 5,000-household batches, and freed - memory is not always returned to the system, so the footprint recorded - when the workers start is the check on the 3 GiB. + memory is not always returned to the system. The execution record + reports the process's footprint when the workers start, so a run shows + how it compares with the 3 GiB; nothing checks it or changes the plan. - Each batch engine keeps policyengine-us's projection of the release year to its last CPI-U year (2035), because the plans request keys in later years (reform validation reaches past 2025). The build's own simulations hold diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 74ce6f6612..0ec51069ed 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -5772,8 +5772,8 @@ def __init__( error: str | None = None, ) -> None: """``consumer_requests`` holds every request of each consumer's dry - run, which pooled scoring sends to workers; the record of the plan - leaves it out, as it does the reform pass counts.""" + run, whose reform passes pooled scoring sends to workers; the record + of the plan leaves it out, as it does the reform pass counts.""" self.n_households = int(n_households) self.maximum_batch_size = maximum_batch_size self.baseline_plans = { @@ -6450,16 +6450,64 @@ def _post_export_error_text(error: BaseException) -> str: return type(error).__name__ -def _without_traceback_frames(error: BaseException, *, note: str) -> BaseException: - """``error``, kept to raise later, holding no frames: its formatted - traceback, with those of the exceptions it was raised from or while - handling, is added as a note after ``note``; then its traceback and its - links to those exceptions are dropped (each of them is left unchanged), so - it holds no failed pass's per-batch values and no caller's exception.""" - error.add_note(note + "\n" + "".join(traceback.format_exception(error))) - error.__traceback__ = None - error.__cause__ = None - error.__context__ = None +def _exception_chain(error: BaseException) -> Iterator[BaseException]: + """``error`` and every exception it was raised from or while handling, + each once.""" + pending, seen = [error], set() + while pending: + linked = pending.pop() + if id(linked) in seen: + continue + seen.add(id(linked)) + yield linked + pending.extend( + chained + for chained in (linked.__cause__, linked.__context__) + if chained is not None + ) + + +def _raised_while_interrupted(error: BaseException) -> bool: + """Whether ``error`` was raised from, or while handling, an interrupt + (``KeyboardInterrupt``, or SIGTERM's ``BuildTerminatedError``).""" + return any( + isinstance(linked, KeyboardInterrupt) for linked in _exception_chain(error) + ) + + +def _without_traceback_frames( + error: BaseException, + *, + note: str, + callers_exception: BaseException | None = None, +) -> BaseException: + """``error``, kept to raise later, holding no frames of the pass it ended. + + Its formatted traceback, with those of the exceptions it was raised from + or while handling, is added as a note after ``note`` (a short note says + so if formatting runs out of memory). Then the traceback of ``error`` and + of each exception in its chain is dropped, except ``callers_exception``, + the exception the caller was handling when the pass ran, and that + exception's own chain, which are left unchanged. The links stay, so the + build's run outcome still reads the chain (a MemoryError, a termination). + """ + try: + formatted = "".join(traceback.format_exception(error)) + except MemoryError: + formatted = "(Its traceback could not be formatted: out of memory.)\n" + error.add_note(note + "\n" + formatted) + pending, seen = [error], set() + while pending: + linked = pending.pop() + if linked is callers_exception or id(linked) in seen: + continue + seen.add(id(linked)) + linked.__traceback__ = None + pending.extend( + chained + for chained in (linked.__cause__, linked.__context__) + if chained is not None + ) return error @@ -7338,11 +7386,14 @@ def _score_baselines(self) -> None: this process while workers run (each worker's cap, and the plan's 3 GiB for this process, are sized for reform passes). A consumer's own pass that raises is kept, with its traceback as a note and without - its frames, and raised when that consumer opens; a refused batch file - propagates at once. + its frames, and raised when that consumer opens; a refused batch file, + or an error raised while the build is being interrupted or + terminated, propagates at once. """ if not self._unserved_baseline_plans: return + # What the caller is handling, if anything: left as it is. + callers_exception = sys.exception() self._run_merged_baseline_pass() if not self._merged_baseline_failed: return @@ -7354,10 +7405,14 @@ def _score_baselines(self) -> None: except PostExportBatchFileError: raise except Exception as error: + if _raised_while_interrupted(error): + # The build is stopping: no later stage's pass runs. + raise self._own_baselines[name] = _without_traceback_frames( error, note="Raised by its own baseline pass in the certifying " "process, before the worker pool started:", + callers_exception=callers_exception, ) # After a failed pass, outside the handler: a full collection # frees what its frames held in a cycle. diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index 09ff51b05c..23835dfec1 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -37,9 +37,9 @@ one scorer, then source coverage). As in certification, the scorer registers every engine stage's recorded baseline plan, so one shared baseline pass, run when the first stage opens, serves them all; with the release tool's -``_PostExportPooling`` (``ExportProbe(post_export_pooling=...)``) the stages' -recorded requests are scored in the shared worker pool, as certification -scores them. The command does so by default, with certification's worker +``_PostExportPooling`` (``ExportProbe(post_export_pooling=...)``) the baseline +passes run in this process and the stages' recorded reform passes in the +shared worker pool, as certification scores them. The command does so by default, with certification's worker settings, unless ``MICROCOSM_POST_EXPORT_WORKERS=serial``. The frame-based stages (1-3) run first, while the loaded frame is held, instead of after the scorer as in ``_main``: they read only the frame, so the order changes no verdict. Unlike the @@ -1646,10 +1646,13 @@ def _score(self, keys, *, label, reform_system=None, **options): before = sampler.reset() if sampler else 0 wall = time.perf_counter() cpu = time.process_time() + failed = True try: - return super()._score( + values = super()._score( keys, label=label, reform_system=reform_system, **options ) + failed = False + return values finally: row = { "stage": clock.current, @@ -1658,6 +1661,7 @@ def _score(self, keys, *, label, reform_system=None, **options): "reform": reform_system is not None, "batches": self.n_batches, "process": "certifying process", + "failed": failed, "wall_seconds": round(time.perf_counter() - wall, 3), "cpu_seconds": round(time.process_time() - cpu, 3), "rss_before_gib": _gib(before), diff --git a/tools/route_a/README.md b/tools/route_a/README.md index 8dd8dcc3a8..07d0bac55c 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -253,7 +253,12 @@ without it. The stage's 110 GiB RSS cap counts the workers too, and the worker count is not sized to it: the plan's peak is 3 GiB plus 5 GiB per worker (88 GiB for 17 workers on the 128 GiB build Mac), so on a machine where the formula gives more than 21 workers (about 151 GiB and 23 usable -cores or more), set `MICROCOSM_POST_EXPORT_WORKERS` to 21 or fewer. +cores or more), set `MICROCOSM_POST_EXPORT_WORKERS` to 21 or fewer. The +3 GiB is a plan, not a measurement: the certifying process runs every +baseline pass before the workers start, and what those passes leave +resident is not measured (after a failed shared baseline pass it also holds +every stage's own baseline values). The manifests' `post_export_scoring` +`execution` record reports its footprint when the workers start. The driver waits up to `RESOURCE_WAIT_HOURS` (example: 12) for admission and retries a supervisor admission race every five minutes. Every config includes From 620e6afb9d83e6b34023cbdbc5bc46c6395b78b7 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:38:12 +0400 Subject: [PATCH 25/26] Test that a merged baseline pass stopped by a termination stops scoring Failing test (review round 3): an error raised while SIGTERM unwinds the merged baseline pass stops scoring at once in the serial and the pooled scorer, instead of falling back to every stage's own pass, and the run outcome reads it as a termination. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_pooled_scoring.py | 57 ++++++++++++++++--- 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py index 2d60c0e33d..a555aba8f4 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_pooled_scoring.py @@ -1562,6 +1562,16 @@ def _raise_merged_out_of_memory(): raise MemoryError("fixture merged pass out of memory") +def _raise_while_terminated(): + from microcosm.build.termination import BuildTerminatedError + + try: + raise BuildTerminatedError() + except BuildTerminatedError: + # Raised while handling it, so the termination is its context. + raise RuntimeError("fixture cleanup failed while stopping") # noqa: B904 + + def test_a_kept_baseline_error_keeps_what_the_run_outcome_reads( builder, pooled_reforms, @@ -1613,14 +1623,6 @@ def test_a_baseline_pass_stopped_by_a_termination_stops_scoring_at_once( interrupt unwinds is not kept for its stage: it stops scoring at once, before any later stage's own pass runs, as the build must stop.""" from microcosm.build.run_outcome import classify_failure - from microcosm.build.termination import BuildTerminatedError - - def raise_while_terminated(): - try: - raise BuildTerminatedError() - except BuildTerminatedError: - # Raised while handling it, so the termination is its context. - raise RuntimeError("fixture cleanup failed while stopping") # noqa: B904 consumers, plan = _three_baseline_consumers(builder) labels = _failing_passes( @@ -1628,7 +1630,7 @@ def raise_while_terminated(): builder, { "merged baseline plan": _raise_merged_out_of_memory, - "second baseline plan": raise_while_terminated, + "second baseline plan": _raise_while_terminated, }, ) scorer = _pooled_scorer(builder, plan, tmp_path, 1) @@ -1674,3 +1676,40 @@ def out_of_memory(*arguments, **options): scorer.open_consumer("third", plan.baseline_plan("third")) finally: scorer.close() + + +# --------------------------------------------------------------------------- +# Baseline passes in the certifying process: review round 3 +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("mode", ["serial", "pooled"]) +def test_a_merged_pass_stopped_by_a_termination_stops_scoring_at_once( + builder, + pooled_reforms, + tmp_path, + monkeypatch, + mode, +) -> None: + """An error raised while SIGTERM unwinds the merged baseline pass is not a + failed merged pass to fall back from: in either scorer it stops scoring + at once, and the run outcome reads it as a termination.""" + from microcosm.build.run_outcome import classify_failure + + consumers, plan = _three_baseline_consumers(builder) + labels = _failing_passes( + monkeypatch, builder, {"merged baseline plan": _raise_while_terminated} + ) + scorer = ( + _serial_scorer(builder, plan, tmp_path) + if mode == "serial" + else _pooled_scorer(builder, plan, tmp_path, 1) + ) + try: + with pytest.raises(RuntimeError, match="fixture cleanup") as raised: + scorer.open_consumer("first", plan.baseline_plan("first")) + assert classify_failure(raised.value).error_code == "TERMINATED" + assert labels == ["merged baseline plan"] + assert not scorer._merged_baseline_failed + finally: + scorer.close() From ce2c33c912be690ed73de6a78f1e3eec25f3960a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:54:25 +0400 Subject: [PATCH 26/26] Fix review round 3: stop at once when a termination ends the merged pass - An error raised while the build is being interrupted or terminated stops the merged baseline pass at once instead of falling back to every stage's own pass, in the serial and the pooled scorer (the serial gap predates this branch; a build being stopped has no outputs to compare). - The kept-error docstring says what it keeps (exception attributes) and what Python changes when it is raised inside a handler. - The release build rule, the Route A README, the scorer's and certification's docstrings and the probe's description say that the baseline passes run in the certifying process and only the reform passes in the pool, which error the first stage gets, and that the footprint at pool start is recorded by each run but not yet measured at full size. Co-Authored-By: Claude Opus 5.5 --- docs/us-release-build-rule.md | 13 +++++----- tools/build_us_fiscal_refresh_release.py | 33 ++++++++++++++++-------- tools/probe_us_post_export.py | 11 ++++---- tools/route_a/README.md | 13 +++++----- 4 files changed, 42 insertions(+), 28 deletions(-) diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 2b40ed6ca1..c6c78e4a23 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -539,9 +539,9 @@ one Microsimulation over the whole file. each one when its stage opens; a stage whose own pass raised gets that error when it opens, with the original traceback as a note, and the exceptions it was raised from or while handling, so the build's run - outcome still reads them (out of memory, terminated). A changed batch - file, or an error raised while the build is being interrupted or - terminated, stops scoring at once. Each batch engine is released before + outcome still reads them (out of memory). A changed batch file, or an + error raised while the build is being interrupted or terminated, in the + shared pass or a stage's own, stops scoring at once. Each batch engine is released before the next is built, so no baseline engine is held in the certifying process while workers run. - After a failed shared pass this differs from the serial scorer in time @@ -586,9 +586,10 @@ one Microsimulation over the whole file. served. When the pool cannot be built at all, the first stage's opening raises that error and every later stage is refused with `PostExportPoolStoppedError`, as after a changed batch file. Each of - these is a `WorkerPoolError` and stops certification, the held-out - reports included, where the serial scorer, which has no memory cap, may - have finished. + these stops certification, the held-out reports included, where the + serial scorer, which has no memory cap, may have finished: the first + stage's error is the pool's or the batch file's own, and every later one + is a `WorkerPoolError`. - Each stage then runs as in the serial path and builds its own reforms (the smoke records each list edit's resolved lists from its own). Its baseline is served its recorded plan, and each reformed simulation its recorded diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 0ec51069ed..8693d74bc1 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -6350,7 +6350,8 @@ def _run_merged_baseline_pass(self) -> None: If the pass raises, ``_merged_baseline_failed`` is set and every registered consumer then scores its own plan. A refused batch file - (:class:`PostExportBatchFileError`) propagates instead. + (:class:`PostExportBatchFileError`), or an error raised while the + build is being interrupted or terminated, propagates instead. """ union = _ascending_period_plan( key for plan in self._unserved_baseline_plans.values() for key in plan @@ -6362,6 +6363,9 @@ def _run_merged_baseline_pass(self) -> None: # it stops certification. raise except Exception as error: + if _raised_while_interrupted(error): + # The build is stopping: no consumer's own pass runs. + raise self._merged_baseline_failed = True self._merged_fallback_reason = _post_export_error_text(error) print( @@ -6489,7 +6493,10 @@ def _without_traceback_frames( of each exception in its chain is dropped, except ``callers_exception``, the exception the caller was handling when the pass ran, and that exception's own chain, which are left unchanged. The links stay, so the - build's run outcome still reads the chain (a MemoryError, a termination). + build's run outcome still reads the chain (a MemoryError). An error raised + later inside a handler gets that handler's exception as its context in + place of its own, as Python sets it; no stage is opened inside one. + Exception attributes, such as ``AttributeError.obj``, are kept. """ try: formatted = "".join(traceback.format_exception(error)) @@ -6651,9 +6658,10 @@ def _open_post_export_scorer( ) -> _HouseholdBatchedPostExportScorer | None: """Open the scorer the plan recorded before export, or None if no stage runs. - With ``pooling`` the scorer scores the plan's recorded requests in the - shared worker pool (``_PooledPostExportScorer``); without it, every pass - runs in this process. The scorer keeps its household batch files in a new + With ``pooling`` the scorer runs the baseline passes in this process and + the plan's recorded reform passes in the shared worker pool + (``_PooledPostExportScorer``); without it, every pass runs in this + process. The scorer keeps its household batch files in a new directory of its own inside ``batch_parent`` (the system's temporary directory without one). """ @@ -7414,7 +7422,7 @@ def _score_baselines(self) -> None: "process, before the worker pool started:", callers_exception=callers_exception, ) - # After a failed pass, outside the handler: a full collection + # Outside the handler: after a failed pass, a full collection # frees what its frames held in a cycle. collect_pass_garbage() @@ -21259,8 +21267,10 @@ def _certify_us_build( ``certification`` is the tier certification chose, the release directory it placed the build's files in and the ID it publishes the build under, and both manifests record it beside the build's provenance. With - ``post_export_pooling`` the post-export stages are scored in the shared - worker pool (``_PooledPostExportScorer``); without it, in this process. + ``post_export_pooling`` the post-export stages' baseline passes run in + this process and their reform passes in the shared worker pool + (``_PooledPostExportScorer``); without it, every pass runs in this + process. """ certify_started = time.perf_counter() @@ -21329,9 +21339,10 @@ def _certify_us_build( # household-batched scorer instead of one whole-pool Microsimulation each. # It loads the written H5 once, binds its sha256 (the manifest must pin # the same bytes), and serves the baseline plans recorded above from one - # merged baseline pass (microcosm#1595). With pooling, the plan's - # recorded requests are scored in the shared worker pool and each stage - # is served from the results, byte-identically. + # merged baseline pass (microcosm#1595). With pooling, the baseline + # passes run here first, the plan's recorded reform passes in the shared + # worker pool, and each stage is served from the results, + # byte-identically. post_export_scorer = _open_post_export_scorer( post_export_scoring_plan, dataset_path, diff --git a/tools/probe_us_post_export.py b/tools/probe_us_post_export.py index 23835dfec1..0f1fc41c36 100644 --- a/tools/probe_us_post_export.py +++ b/tools/probe_us_post_export.py @@ -20,8 +20,9 @@ stale count-calibrated check ``_main`` raises on. 4. ``reform_coverage_smoke``: the release's smoke consumer on the household-batched scorer, from the plan the engine-free dry run records: - in the shared worker pool (``_PooledPostExportScorer``), as the command - scores by default, or in this process + with the reform passes in the shared worker pool and the baseline passes + in this process (``_PooledPostExportScorer``), as the command scores by + default, or every pass in this process (``_HouseholdBatchedPostExportScorer``, with ``MICROCOSM_POST_EXPORT_WORKERS=serial``). 5. ``reform_validation``: ``_reform_validation_consumer``. With the build's @@ -1954,9 +1955,9 @@ def __init__( probes = us_release_reform_coverage_probes() self.probes = tuple(probes) self.scorer_options = dict(scorer_options or {}) - # The release tool's ``_PostExportPooling``: with it the engine stages - # are scored in the shared worker pool, as certification scores them; - # without it every pass runs in this process. The pool settings name + # The release tool's ``_PostExportPooling``: with it the engine + # stages' reform passes run in the shared worker pool, as + # certification runs them; without it every pass runs in this process. The pool settings name # the workers' engine, so one given to the scorer as well is refused. if post_export_pooling is not None and self.scorer_options: raise ValueError( diff --git a/tools/route_a/README.md b/tools/route_a/README.md index 07d0bac55c..dd360e66b0 100644 --- a/tools/route_a/README.md +++ b/tools/route_a/README.md @@ -245,8 +245,8 @@ Every stage runs through the supervisor's admission check and limits: | certify | 110 | `RELEASE_RAM_GIB` (example: 50) | 45 | `CERTIFY_WALL_SECONDS` (default: 345600) | 2000000 | | publisher preflight | 24 | 16 | 22 | 7200 | 14400 | -The certify stage scores the post-export stages in a pool of worker -processes sized from the machine; `MICROCOSM_POST_EXPORT_WORKERS` in +The certify stage runs the post-export stages' baseline passes itself and +their reform passes in a pool of worker processes sized from the machine; `MICROCOSM_POST_EXPORT_WORKERS` in `route_a.env` (a number of workers, or `serial`) overrides it, and the driver exports it. On a machine under about 10.7 GiB, certification refuses to start without it. The stage's 110 GiB RSS cap counts the workers too, and the @@ -255,10 +255,11 @@ worker (88 GiB for 17 workers on the 128 GiB build Mac), so on a machine where the formula gives more than 21 workers (about 151 GiB and 23 usable cores or more), set `MICROCOSM_POST_EXPORT_WORKERS` to 21 or fewer. The 3 GiB is a plan, not a measurement: the certifying process runs every -baseline pass before the workers start, and what those passes leave -resident is not measured (after a failed shared baseline pass it also holds -every stage's own baseline values). The manifests' `post_export_scoring` -`execution` record reports its footprint when the workers start. +baseline pass before the workers start, and nothing has yet measured what +those passes leave resident at full size (after a failed shared baseline +pass it also holds every stage's own baseline values). Each run's +manifests record it: the `post_export_scoring` `execution` record holds the +process's footprint when the workers started. The driver waits up to `RESOURCE_WAIT_HOURS` (example: 12) for admission and retries a supervisor admission race every five minutes. Every config includes