From bac1097c8cd94b84427df429e4fa97e7bd38bc5e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:41:24 +0400 Subject: [PATCH 01/13] Test post-export requests as picklable descriptors Failing tests for the engine-free dry run returning every post-export request as a PostExportRequest: one per request of each shipped consumer, in the serial scorer's order, with no engine importable and no reform built; a pickle round trip through a spawned process; the refusal of a reform the dry run cannot describe; and the guard sweep recording descriptors. The new module these tests import does not exist yet, so every test in the three changed files fails at import here. The test of the release's recorded outputs pins digests taken by running it on origin/main (fcabe4e65), before the descriptor imports were added to its file. Co-Authored-By: Claude Opus 5.5 --- .../shared/test_release_input_coverage.py | 3 +- .../us/test_us_post_export_requests.py | 513 ++++++++++++++++++ .../us/test_us_post_export_scoring.py | 34 +- .../post_export_request_worker.py | 26 + 4 files changed, 563 insertions(+), 13 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_post_export_requests.py create mode 100644 test_support/microcosm_build/post_export_request_worker.py diff --git a/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py b/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py index fda192239a..5cd1fc0b84 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py @@ -8,6 +8,7 @@ from hypothesis import strategies as st import microcosm.build.us_runtime.release_input_coverage as coverage_module +from microcosm.build.us_runtime.post_export_requests import RECORDS_REQUESTS_ONLY from microcosm.build.us_runtime.release_input_coverage import ( US_RELEASE_INPUT_COVERAGE_SCHEMA_VERSION, ListParameterEdit, @@ -394,7 +395,7 @@ def simulate(reform): return _Sim(4.16e10 if reform is not None else 4.0e10) if flag: - setattr(simulate, smoke_module.RECORDS_REQUESTS_ONLY, True) + setattr(simulate, RECORDS_REQUESTS_ONLY, True) probes = [_probe(), _list_edit_probe()] result = us_reform_coverage_smoke_gate( simulate=simulate, probes=probes, period=2024 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 new file mode 100644 index 0000000000..449d62c212 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_requests.py @@ -0,0 +1,513 @@ +"""Post-export requests recorded as picklable descriptors. + +The engine-free dry run that learns each post-export consumer's baseline plan +also returns every request the consumer makes as a ``PostExportRequest``, so +that later work can send the requests to spawned worker processes and rebuild +each consumer's output from their results. These tests check that: + +- the dry run returns one descriptor per request of every shipped consumer, + with no engine importable, and builds no reform: each reform is recorded as + the description its consumer builds it from; +- the descriptors list the requests in the order the serial scorer runs them + (the baseline plan, then each reform pass), name the reformed simulation + that asked for each, and rebuild the reform that simulation was given; +- every descriptor survives a pickle round trip through a spawned process; +- the dry run refuses a reform it cannot describe; +- the recorded outputs of the release stay byte-identical on the fixture. +""" + +# ruff: noqa: F403, F405 +from __future__ import annotations + +import hashlib +import itertools +import json +import multiprocessing +import os +from collections.abc import Mapping +from concurrent.futures import ProcessPoolExecutor + +import microcosm.build.us_runtime.release_input_coverage as coverage_module +from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, + ParameterChangesReform, + PostExportRequest, + build_post_export_reform, +) +from test_support.microcosm_build.post_export_request_worker import ( + requests_as_a_spawned_worker_receives_them, +) +from test_support.microcosm_build.us_post_export_scoring import * + +_RELEASE_ID = "fixture-release" + + +def _shipped_consumers(builder): + """The five post-export consumers a release runs, in run order.""" + return builder._post_export_consumers( + _plan_args(), + result=_calibration_result_with_in_sample_fit(builder.PERIOD), + release_id=_RELEASE_ID, + ) + + +@pytest.fixture +def no_engine(monkeypatch): + """No engine package importable, no list edit resolvable, no reform built.""" + for module in ("policyengine_us", "policyengine_core", "policyengine_core.reforms"): + monkeypatch.setitem(sys.modules, module, None) + + def refused(*args, **kwargs): + raise AssertionError("the engine-free dry run built a reform") + + # The installed-engine reader is cached per process, so blocking the + # imports alone would not catch a resolution served from an earlier test. + monkeypatch.setattr(coverage_module, "_installed_parameter_stages", refused) + monkeypatch.setattr(smoke_module, "_build_reform", refused) + monkeypatch.setattr(reform_validation_module, "_build_parameter_reform", refused) + monkeypatch.setattr(ReformValidationSpec, "build_reform", refused) + + +def test_the_dry_run_returns_every_request_as_a_descriptor(builder, no_engine) -> None: + probes = us_release_reform_coverage_probes() + specs = reform_validation_module.load_default_reform_specs(period=builder.PERIOD) + fitted = { + spec.id + for spec in reform_validation_module.in_sample_reform_specs( + period=builder.PERIOD + )[:2] + } + recorded: dict[str, tuple[PostExportRequest, ...]] = {} + for name, consumer in _shipped_consumers(builder).items(): + requests = builder._record_post_export_request_descriptors(name, consumer) + assert all(isinstance(request, PostExportRequest) for request in requests) + assert {request.consumer for request in requests} <= {name} + assert [request.position for request in requests] == list(range(len(requests))) + baseline = tuple(request for request in requests if request.reform is None) + reformed = tuple(request for request in requests if request.reform is not None) + # The baseline plan first, as the serial scorer scores it. + assert requests == (*baseline, *reformed) + assert all(request.reformed_simulation is None for request in baseline) + assert all(isinstance(request.reformed_simulation, int) for request in reformed) + # The plan and the pass count the release records are the same dry + # run's. + plan, passes = builder._record_post_export_requests(consumer) + assert tuple(request.key for request in baseline) == plan + assert len(reformed) == passes + recorded[name] = requests + assert list(recorded) == [ + "reform_coverage_smoke", + "reform_validation", + "demographics", + "ssi_social_security_holdout", + "medicare_irmaa_holdout", + ] + + smoke = [ + request + for request in recorded["reform_coverage_smoke"] + if request.reform is not None + ] + assert [request.reform for request in smoke] == list(probes) + assert [request.reformed_simulation for request in smoke] == list( + range(len(probes)) + ) + assert [request.key for request in smoke] == [ + (probe.budget_measure, int(probe.period or builder.PERIOD), None) + for probe in probes + ] + + validation = [ + request + for request in recorded["reform_validation"] + if request.reform is not None + ] + assert {type(request.reform) for request in validation} == { + ReformValidationSpec, + ParameterChangesReform, + } + # Every spec simulated on its own: the out-of-sample ones outside OBBBA's + # stacks, and the in-sample ones the calibration fit does not cover. + assert [ + request.reform.id + for request in validation + if isinstance(request.reform, ReformValidationSpec) + ] == [ + spec.id + for spec in specs + if not reform_validation_module._is_obbba_spec(spec) + and not (spec.in_sample and spec.id in fitted) + ] + # OBBBA: each (measure, period) group scores the pre-OBBBA state, then one + # stacked state per provision. + obbba = [spec for spec in specs if reform_validation_module._is_obbba_spec(spec)] + states = [ + request + for request in validation + if isinstance(request.reform, ParameterChangesReform) + ] + groups = {(spec.budget_measure, spec.period) for spec in obbba} + assert len(states) == len(obbba) + len(groups) + pre_obbba = ParameterChangesReform( + reform_validation_module._merged_parameter_changes(obbba) + ) + assert [request.key[:2] for request in states if request.reform == pre_obbba] == [ + (measure, period) + for measure, period in dict.fromkeys( + (spec.budget_measure, spec.period) for spec in obbba + ) + ] + assert len({request.reformed_simulation for request in validation}) == len( + validation + ) + + for name in ( + "demographics", + "ssi_social_security_holdout", + "medicare_irmaa_holdout", + ): + assert all(request.reform is None for request in recorded[name]), name + + +def test_every_request_round_trips_through_a_spawned_process( + builder, no_engine +) -> None: + """A worker started with the ``spawn`` method, which has never run the + release tool, unpickles every shipped request and sends it back equal.""" + requests = tuple( + request + for name, consumer in _shipped_consumers(builder).items() + for request in builder._record_post_export_request_descriptors(name, consumer) + ) + assert any(request.reform is not None for request in requests) + with ProcessPoolExecutor( + max_workers=1, mp_context=multiprocessing.get_context("spawn") + ) as executor: + received = executor.submit( + requests_as_a_spawned_worker_receives_them, requests + ).result() + assert received["start_method"] == "spawn" + assert received["process_id"] != os.getpid() + assert received["requests"] == requests + assert received["type_modules"] == [ + "microcosm.build.us_runtime.post_export_requests", + "microcosm.build.us_runtime.reform_validation", + "microcosm.build.us_runtime.release_input_coverage", + ] + + +def _watched_simulate(builder, simulate, asked: list): + """``simulate``, logging each reformed simulation's first ask per key. + + Each entry is (the reformed simulation's number among the consumer's + ``simulate(reform)`` calls, the reform's label, the key). + """ + numbers = itertools.count() + + def watched(reform): + simulation = simulate(reform) + if reform is None: + return simulation + number = next(numbers) + + class Watched: + def calculate(self, variable, period=None, map_to=None): + entry = ( + number, + reform.label, + builder._post_export_key(variable, period, map_to), + ) + if entry not in asked: + asked.append(entry) + return simulation.calculate(variable, period, map_to) + + return Watched() + + return watched + + +def test_the_descriptors_list_the_passes_the_serial_scorer_runs( + builder, fake_reforms, tmp_path +) -> None: + """Each consumer, scored as ``_main`` scores it, runs its baseline plan and + then one reform pass per reform descriptor, in descriptor order, on the + reformed simulation each descriptor names, with the reform it rebuilds.""" + scorer = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path) + try: + for name, consumer in _shipped_consumers(builder).items(): + requests = builder._record_post_export_request_descriptors(name, consumer) + baseline = tuple(r.key for r in requests if r.reform is None) + reformed = [r for r in requests if r.reform is not None] + scoring = scorer.open_consumer( + name, baseline, planned_reform_passes=len(reformed) + ) + assert scoring.baseline_plan == baseline + asked: list = [] + consumer(_watched_simulate(builder, scoring.simulate, asked)) + assert asked == [ + (request.reformed_simulation, request.build_reform().label, request.key) + for request in reformed + ], name + assert scorer.finish_consumer(scoring)["reform_passes"] == len(reformed) + finally: + scorer.close() + + +def test_reform_requests_follow_the_order_of_first_asks( + builder, fake_reforms, tmp_path +) -> None: + """A reform pass runs when a reformed simulation is first asked for a key, + so the descriptors follow those first asks across simulations; a + simulation never asked makes no request but keeps its number.""" + first = ParameterChangesReform({"gov.fixture.first": {"2024-01-01": 1}}) + second = ParameterChangesReform({"gov.fixture.second": {"2024-01-01": 2}}) + unasked = ParameterChangesReform({"gov.fixture.unasked": {"2024-01-01": 3}}) + + def consumer(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + + def reformed(source): + return simulate( + source if records_only else build_post_export_reform(source) + ) + + first_simulation = reformed(first) + second_simulation = reformed(second) + reformed(unasked) + simulate(None).calculate("income_tax", 2025) + second_simulation.calculate("income_tax", 2024) + first_simulation.calculate("income_tax", 2024) + first_simulation.calculate("income_tax", 2024) + simulate(None).calculate("age", 2024, map_to="household") + first_simulation.calculate("age", 2024, map_to="household") + + requests = builder._record_post_export_request_descriptors("fixture", consumer) + assert [(r.position, r.reformed_simulation, r.reform, r.key) for r in requests] == [ + (0, None, None, ("age", 2024, "household")), + (1, None, None, ("income_tax", 2025, None)), + (2, 1, second, ("income_tax", 2024, None)), + (3, 0, first, ("income_tax", 2024, None)), + (4, 0, first, ("age", 2024, "household")), + ] + assert builder._record_post_export_requests(consumer) == ( + (("age", 2024, "household"), ("income_tax", 2025, None)), + 3, + ) + + scorer = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path) + try: + baseline = tuple(r.key for r in requests if r.reform is None) + scoring = scorer.open_consumer("fixture", baseline) + asked: list = [] + consumer(_watched_simulate(builder, scoring.simulate, asked)) + assert asked == [ + (r.reformed_simulation, r.build_reform().label, r.key) + for r in requests + if r.reform is not None + ] + finally: + scorer.close() + + +def test_the_dry_run_refuses_a_reform_it_cannot_describe( + builder, no_engine, monkeypatch +) -> None: + """A worker rebuilds each reform from its description, so a consumer that + hands the dry run a built reform fails the plan, which the release records + and refuses before the export, instead of recording a request no worker + could run.""" + + class BuiltReform: + pass + + def consumer(simulate): + simulate(BuiltReform()).calculate("income_tax", 2024) + + with pytest.raises(TypeError, match="BuiltReform"): + builder._record_post_export_requests(consumer) + with pytest.raises(TypeError, match="BuiltReform"): + builder._record_post_export_request_descriptors("fixture", consumer) + monkeypatch.setattr( + builder, + "_post_export_consumers", + lambda args, *, result, release_id: {"fixture": consumer}, + ) + plan = builder._record_post_export_scoring_plan( + _plan_args(), + n_households=7, + result=_empty_calibration_result(), + release_id=_RELEASE_ID, + ) + assert plan.error is not None + assert plan.error.startswith("TypeError") and "BuiltReform" in plan.error + assert plan.terminal_failures() + + +def test_a_request_rebuilds_its_reform_with_its_consumer_s_builder( + monkeypatch, +) -> None: + built: list[tuple[str, object]] = [] + monkeypatch.setattr( + smoke_module, "_build_reform", lambda probe: built.append(("probe", probe)) + ) + monkeypatch.setattr( + ReformValidationSpec, + "build_reform", + lambda spec: built.append(("spec", spec)), + ) + monkeypatch.setattr( + reform_validation_module, + "_build_parameter_reform", + lambda changes: built.append(("changes", changes)), + ) + probe = us_release_reform_coverage_probes()[0] + spec = reform_validation_module.load_default_reform_specs(period=2024)[0] + changes = {"gov.fixture.parameter": {"2026-01-01": 0}} + for reform in (probe, spec, ParameterChangesReform(changes)): + PostExportRequest( + consumer="fixture", + position=0, + variable="income_tax", + period=2026, + reform=reform, + reformed_simulation=0, + ).build_reform() + assert built == [("probe", probe), ("spec", spec), ("changes", changes)] + baseline = PostExportRequest( + consumer="fixture", position=0, variable="age", period=2024 + ) + assert baseline.build_reform() is None + assert baseline.key == ("age", 2024, None) + + +@pytest.mark.parametrize( + "fields, message", + [ + ({"reform": None, "reformed_simulation": 0}, "reformed simulation"), + ({"reformed_simulation": None}, "reformed simulation"), + ({"reform": object()}, "object"), + ({"position": -1}, "position"), + ({"period": "2024"}, "period"), + ({"map_to": ""}, "map_to"), + ({"consumer": ""}, "consumer"), + ({"variable": ""}, "variable"), + ], +) +def test_a_request_refuses_inconsistent_fields(fields, message) -> None: + valid = { + "consumer": "fixture", + "position": 0, + "variable": "income_tax", + "period": 2026, + "map_to": None, + "reform": ParameterChangesReform({"gov.fixture": {"2026-01-01": 0}}), + "reformed_simulation": 0, + } + PostExportRequest(**valid) + with pytest.raises((TypeError, ValueError), match=message): + PostExportRequest(**{**valid, **fields}) + + +@pytest.mark.parametrize("changes", [{}, None, [("gov.fixture", 1)]]) +def test_parameter_changes_must_name_a_reform(changes) -> None: + """No changes is the baseline, which consumers ask for as ``None``.""" + with pytest.raises((TypeError, ValueError), match="parameter changes"): + ParameterChangesReform(changes) + + +#: SHA-256 of each output the post-export stages record, on the fixture frame +#: and fake engine below, with a calibration fit covering two in-sample JCT +#: reforms. Pinned from origin/main at fcabe4e65, before the dry run returned +#: descriptors. A change that moves one of them changes what a release records: +#: re-pin only when a probe, spec, baseline level or the fixture changed on +#: purpose, in the same pull request. +_RECORDED_OUTPUT_SHA256 = { + "calibration_diagnostics.build.post_export_scoring": ( + "7ed2a0dd088cf2d5a65e27e00368819cdf357160a5bdc2e42f079233d1f2f7b1" + ), + "reform_coverage_smoke": ( + "c2e6cbf63b02fc5dbbc1ddd5507edd5e9cfb21a41143469cc737c69279da9842" + ), + "reform_validation": ( + "e84481d7051f60570f7ba7bfafd0c631c4de5f19fb27ec2d50e8d7802689910e" + ), + "demographics": ( + "081adcc03922e4e3a7cf288f337fa28bd32511d4ca6626b3afed896edfa0d4c2" + ), + "ssi_social_security_holdout": ( + "b3d2db968bb3b10d004783ab7c080d6b4e376e4441e6753c05712bbd35c1a4b4" + ), + "medicare_irmaa_holdout": ( + "1962831f0fb368fdadd222e42310ca45a70effe214fe520c11a7f1f60d75337f" + ), +} + + +def _json_ready(value): + if isinstance(value, Mapping): + return {str(key): _json_ready(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_ready(item) for item in value] + if isinstance(value, np.ndarray): + return [_json_ready(item) for item in value.tolist()] + if isinstance(value, np.generic): + return value.item() + return value + + +def _sha256_of(value) -> str: + encoded = json.dumps(_json_ready(value), sort_keys=True, allow_nan=False) + return hashlib.sha256(encoded.encode()).hexdigest() + + +def _recorded_post_export_outputs(builder, tmp_path) -> dict[str, object]: + """What ``_main`` records: the plan, then each consumer through one scorer.""" + fit = _calibration_result_with_in_sample_fit(builder.PERIOD) + args = _plan_args() + plan = builder._record_post_export_scoring_plan( + args, n_households=7, result=fit, release_id=_RELEASE_ID + ) + assert plan.error is None + outputs: dict[str, object] = { + "calibration_diagnostics.build.post_export_scoring": plan.record() + } + scorer = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path) + try: + for name, consumer in builder._post_export_consumers( + args, result=fit, release_id=_RELEASE_ID + ).items(): + outputs[name] = builder._score_post_export_consumer( + name, + consumer, + dataset_path=scorer.dataset_path, + post_export_scorer=scorer, + baseline_plan=plan.baseline_plan(name), + maximum_microsim_batch_size=args.maximum_microsim_batch_size, + planned_reform_passes=plan.planned_reform_passes(name), + ) + finally: + scorer.close() + smoke = outputs["reform_coverage_smoke"] + outputs["reform_coverage_smoke"] = { + "name": smoke.name, + "passed": smoke.passed, + "failures": list(smoke.failures), + "details": smoke.details, + } + ages, weights = outputs["demographics"] + outputs["demographics"] = demographics_payload( + ages, weights, period=builder.PERIOD, release_id=_RELEASE_ID + ) + return outputs + + +def test_the_release_s_recorded_post_export_outputs_are_unchanged( + builder, fake_reforms, tmp_path +) -> None: + """The plan in ``calibration_diagnostics.json`` and every consumer's output + keep their bytes: the descriptors are returned, never recorded.""" + outputs = _recorded_post_export_outputs(builder, tmp_path) + assert list(outputs) == list(_RECORDED_OUTPUT_SHA256) + assert { + name: _sha256_of(output) for name, output in outputs.items() + } == _RECORDED_OUTPUT_SHA256 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index deeeb97a7f..295a4b75d2 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 @@ -1,6 +1,10 @@ """Tests split from packages/microcosm-build/tests/test_us_post_export_scoring.py.""" # ruff: noqa: F403, F405 +from microcosm.build.us_runtime.post_export_requests import ( + ParameterChangesReform, + PostExportRequest, +) from test_support.microcosm_build.us_post_export_scoring import * @@ -1581,29 +1585,35 @@ def test_guard_sweep_records_and_scores_shipped_reform_passes( "reform_validation": 75, "demographics": 1, } + # The sweep records the release's descriptors: each names its consumer and + # rebuilds its reform from the description the consumer recorded. + assert all(isinstance(request, PostExportRequest) for request in requests) + assert all(request.reform is not None for request in requests) smoke_requests = [ - request for request in requests if request[0] == "reform_coverage_smoke" - ] - assert [reform.label for _, reform, _ in smoke_requests] == [ - probe.id for probe in us_release_reform_coverage_probes() + request for request in requests if request.consumer == "reform_coverage_smoke" ] + assert [request.reform for request in smoke_requests] == list( + us_release_reform_coverage_probes() + ) validation_requests = [ - request for request in requests if request[0] == "reform_validation" + request for request in requests if request.consumer == "reform_validation" ] ordinary_specs = [ spec for spec in specs if not reform_validation_module._is_obbba_spec(spec) ] - assert {spec.id for spec in ordinary_specs}.issubset( - {reform.label for _, reform, _ in validation_requests} - ) + assert [ + request.reform + for request in validation_requests + if isinstance(request.reform, ReformValidationSpec) + ] == ordinary_specs obbba_specs = [ spec for spec in specs if reform_validation_module._is_obbba_spec(spec) ] - pre_baseline = reform_validation_module._merged_parameter_changes(obbba_specs) + pre_baseline = ParameterChangesReform( + reform_validation_module._merged_parameter_changes(obbba_specs) + ) pre_baseline_requests = [ - key - for _, reform, key in validation_requests - if reform.label == json.dumps(pre_baseline, sort_keys=True, default=str) + request.key for request in validation_requests if request.reform == pre_baseline ] obbba_groups = {(spec.budget_measure, spec.period) for spec in obbba_specs} assert {(key[0], key[1]) for key in pre_baseline_requests} == obbba_groups diff --git a/test_support/microcosm_build/post_export_request_worker.py b/test_support/microcosm_build/post_export_request_worker.py new file mode 100644 index 0000000000..2ac0dced09 --- /dev/null +++ b/test_support/microcosm_build/post_export_request_worker.py @@ -0,0 +1,26 @@ +"""What a spawned pool worker receives of the post-export requests sent to it. + +This module imports nothing beyond the standard library, so a spawned process +that runs it loads only what unpickling the requests needs. The release tool +(``tools/build_us_fiscal_refresh_release.py``) is loaded by file path, outside +``sys.modules``; a type defined there cannot be unpickled in such a process. +""" + +from __future__ import annotations + +import multiprocessing +import os + + +def requests_as_a_spawned_worker_receives_them(requests): + """Return the unpickled requests with where this process got their types.""" + types = {type(request) for request in requests} + types |= { + type(request.reform) for request in requests if request.reform is not None + } + return { + "requests": requests, + "process_id": os.getpid(), + "start_method": multiprocessing.get_start_method(), + "type_modules": sorted({kind.__module__ for kind in types}), + } From 7a01164de3b3c31a584a9281431caf4f3d35efbe Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:41:24 +0400 Subject: [PATCH 02/13] Return every post-export request as a picklable descriptor The release tool's engine-free dry run now returns each request a post-export consumer makes as a PostExportRequest, defined in the new microcosm.build.us_runtime.post_export_requests module so that a spawned process can unpickle it (the tool itself is loaded by file path, outside sys.modules). A descriptor holds the consumer, its place in the order the serial scorer runs the consumer's requests (the baseline plan, then each reform pass in the order of first asks), the variable, period and map_to, and for a reform request the description its reform is rebuilt from and which reformed simulation asked for it. Reform validation, like the smoke check, now hands a simulate that carries RECORDS_REQUESTS_ONLY the spec or a ParameterChangesReform instead of a built reform, because Reform.from_dict returns a class pickle cannot name. The dry run therefore builds no reform, and it refuses a reform it cannot describe. RECORDS_REQUESTS_ONLY moves to the new module. The plan and pass count the release records come from the same dry run, and nothing records the descriptors, so every recorded output keeps its bytes. The guard sweep records through the descriptors and rebuilds each reform in the worker that scores it. Co-Authored-By: Claude Opus 5.5 --- ...s-post-export-request-descriptors.added.md | 1 + docs/us-release-build-rule.md | 8 + .../build/us_runtime/post_export_requests.py | 218 ++++++++++++++++++ .../build/us_runtime/reform_coverage_smoke.py | 15 +- .../build/us_runtime/reform_validation.py | 23 +- tools/build_us_fiscal_refresh_release.py | 131 ++++++++--- tools/sweep_us_post_export_scoring.py | 48 ++-- 7 files changed, 374 insertions(+), 70 deletions(-) create mode 100644 changelog.d/us-post-export-request-descriptors.added.md create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py diff --git a/changelog.d/us-post-export-request-descriptors.added.md b/changelog.d/us-post-export-request-descriptors.added.md new file mode 100644 index 0000000000..aa0e554302 --- /dev/null +++ b/changelog.d/us-post-export-request-descriptors.added.md @@ -0,0 +1 @@ +The US release's engine-free post-export dry run now returns every request each post-export stage makes as a picklable `PostExportRequest` (`microcosm.build.us_runtime.post_export_requests`): the stage, the request's place in the order the serial scorer runs it, the variable, period and `map_to`, and for a reform request the description its reform is rebuilt from (the smoke probe, the reform-validation spec, or a cumulative OBBBA state's parameter changes) and which of the stage's reformed simulations asked for it. Reform validation, like the smoke check, now hands the dry run those descriptions instead of building reforms, so the dry run needs no policyengine-core, and it refuses a reform it cannot describe. Nothing records the descriptors: `calibration_diagnostics.json` and every post-export output keep their bytes, which a test pins on a fixture. `RECORDS_REQUESTS_ONLY` moves from `reform_coverage_smoke` to the new module. `tools/sweep_us_post_export_scoring.py` records through the descriptors and rebuilds each reform in the worker that scores it. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 3736f31b7f..8eaf71221b 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -445,6 +445,14 @@ one Microsimulation over the whole file. - Each stage's baseline requests are learned before export by an engine-free dry run and scored in one pass over the batches, in ascending period order. One engine refuses a period earlier than one it has already computed. + The same dry run 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. 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 one it cannot describe. Nothing records + the descriptors; the guard sweep below rebuilds each reform from its + descriptor in the worker that scores it. The real-engine test probes the MD CCS request-order premise by requesting 2025 state taxes after 2027 keys. It checks for the `md.msde.ccs.payment.informal.rates` error and warns if that error is absent; 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 new file mode 100644 index 0000000000..7b752ef21f --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py @@ -0,0 +1,218 @@ +"""Picklable descriptions of the US release's post-export scoring requests. + +The release tool (``tools/build_us_fiscal_refresh_release.py``) learns what +each post-export consumer will ask policyengine-us for by running the consumer +once against engine-free recorders (its "dry run"). The consumers call +``simulate(None)`` for the baseline simulation and ``simulate(reform)`` for a +reformed one, then ``.calculate(variable, period, map_to=...)`` on each. The +dry run returns every such request as a :class:`PostExportRequest`, which a +process started with the ``spawn`` method can unpickle and run. + +A built reform cannot cross a process boundary: ``Reform.from_dict`` returns a +class defined inside a function, which pickle cannot name. So a consumer whose +``simulate`` carries :data:`RECORDS_REQUESTS_ONLY` hands it the description it +builds the reform from instead, and :func:`build_post_export_reform` rebuilds +the reform from that description with the consumer's own builder: + +- a :class:`~microcosm.build.us_runtime.release_input_coverage.ReformCoverageProbe` + (the reform-coverage smoke check), rebuilt by + ``reform_coverage_smoke._build_reform``; +- a :class:`~microcosm.build.us_runtime.reform_validation.ReformValidationSpec` + (a reform-validation row simulated on its own), rebuilt by its + ``build_reform``; +- a :class:`ParameterChangesReform` (one of reform validation's cumulative + OBBBA states), rebuilt by ``reform_validation._build_parameter_reform``. + +These types live here, in an importable package, because the release tool is +loaded by file path, outside ``sys.modules``: a spawned process could not +unpickle a type defined in it. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from microcosm.build.us_runtime.release_input_coverage import ReformCoverageProbe + +if TYPE_CHECKING: + from microcosm.build.us_runtime.reform_validation import ReformValidationSpec + +__all__ = [ + "RECORDS_REQUESTS_ONLY", + "ParameterChangesReform", + "PostExportReform", + "PostExportRequest", + "build_post_export_reform", + "check_post_export_reform", +] + +#: Set to ``True`` on a ``simulate`` that only records the requests it is +#: asked for and never applies a reform (the release tool's engine-free dry +#: run). A consumer then hands it the description of each reform (see the +#: module docstring) in place of the built reform, so recording builds no +#: reform, resolves no list edit and needs no engine. +RECORDS_REQUESTS_ONLY = "records_requests_only" + + +@dataclass(frozen=True) +class ParameterChangesReform: + """A reform given as a ``Reform.from_dict`` payload for country ``us``. + + Reform validation scores OBBBA's provisions cumulatively from a pre-OBBBA + state; each state is one such payload. An empty payload is the baseline, + which a consumer asks for as ``simulate(None)``, so it is refused here. + """ + + parameter_changes: Mapping[str, Any] + + def __post_init__(self) -> None: + if not isinstance(self.parameter_changes, Mapping): + raise TypeError( + "ParameterChangesReform needs its parameter changes as a mapping " + f"of parameter paths, got {type(self.parameter_changes).__name__}." + ) + if not self.parameter_changes: + raise ValueError( + "ParameterChangesReform needs at least one of its parameter " + "changes; the baseline is simulate(None)." + ) + + +#: What a post-export request records as its reform: the description the +#: consumer builds the reform from. +type PostExportReform = ( + ReformCoverageProbe | ReformValidationSpec | ParameterChangesReform +) + + +def _post_export_reform_types() -> tuple[type, ...]: + # Imported here: reform_validation imports this module. + from microcosm.build.us_runtime.reform_validation import ReformValidationSpec + + return (ReformCoverageProbe, ReformValidationSpec, ParameterChangesReform) + + +def check_post_export_reform(reform: object) -> None: + """Refuse a reform that is not a description a worker can rebuild. + + Raises: + TypeError: Naming the reform's type and the types accepted. + """ + types = _post_export_reform_types() + if not isinstance(reform, types): + accepted = ", ".join(kind.__name__ for kind in types) + raise TypeError( + "Post-export scoring records each reform as the description a worker " + f"rebuilds it from ({accepted}); got a {type(reform).__qualname__}. " + "A consumer whose simulate carries RECORDS_REQUESTS_ONLY must hand it " + "that description, not a built reform." + ) + + +def build_post_export_reform(reform: PostExportReform) -> Any: + """Build the reform ``reform`` describes, with its consumer's own builder. + + Each builder is looked up when it is called, so this builds exactly what + the consumer builds when it scores the same description. + """ + check_post_export_reform(reform) + if isinstance(reform, ReformCoverageProbe): + from microcosm.build.us_runtime import reform_coverage_smoke + + return reform_coverage_smoke._build_reform(reform) + if isinstance(reform, ParameterChangesReform): + from microcosm.build.us_runtime import reform_validation + + return reform_validation._build_parameter_reform(reform.parameter_changes) + return reform.build_reform() + + +@dataclass(frozen=True) +class PostExportRequest: + """One request a post-export consumer makes of policyengine-us. + + Attributes: + consumer: The consumer's name in the release's post-export plan, such + as ``"reform_validation"``. + position: The request's place, from 0, in the order the serial scorer + runs the consumer's requests: the baseline plan's keys (scored + together in one pass, in ascending period order and then request + order), then one reform pass per reform request, in the order the + consumer first asks each reformed simulation for each key. + variable: The variable to calculate. + period: The year to calculate it for. + map_to: The entity the values are mapped to, or ``None`` for the + variable's own entity, which the engine resolves when it + calculates the variable. + reform: ``None`` for the baseline simulation; otherwise the + description the reform is rebuilt from (:func:`build_post_export_reform`). + reformed_simulation: For a reform request, which of the consumer's + ``simulate(reform)`` calls made the simulation asked, numbered from + 0 in call order (a simulation never asked makes no request but + keeps its number); ``None`` for the baseline. + """ + + consumer: str + position: int + variable: str + period: int + map_to: str | None = None + reform: PostExportReform | None = None + reformed_simulation: int | None = None + + def __post_init__(self) -> None: + for name in ("consumer", "variable"): + value = getattr(self, name) + if not isinstance(value, str) or not value: + raise ValueError( + f"PostExportRequest.{name} must be a non-empty string, " + f"got {value!r}." + ) + for name in ("position", "period"): + value = getattr(self, name) + if not isinstance(value, int) or isinstance(value, bool): + raise TypeError( + f"PostExportRequest.{name} must be an integer, got {value!r}." + ) + if self.position < 0: + raise ValueError( + f"PostExportRequest.position must be 0 or more, got {self.position}." + ) + if self.map_to is not None and ( + not isinstance(self.map_to, str) or not self.map_to + ): + raise ValueError( + "PostExportRequest.map_to must be None or an entity name, got " + f"{self.map_to!r}." + ) + if self.reform is None: + if self.reformed_simulation is not None: + raise ValueError( + "A baseline PostExportRequest names no reformed simulation, " + f"got {self.reformed_simulation!r}." + ) + return + check_post_export_reform(self.reform) + simulation = self.reformed_simulation + if ( + not isinstance(simulation, int) + or isinstance(simulation, bool) + or simulation < 0 + ): + raise ValueError( + "A reform PostExportRequest names its reformed simulation as an " + f"integer of 0 or more, got {simulation!r}." + ) + + @property + def key(self) -> tuple[str, int, str | None]: + """(variable, period, map_to), the release tool's ``PostExportKey``.""" + return (self.variable, self.period, self.map_to) + + def build_reform(self) -> Any: + """The reform the worker's engine applies; ``None`` for the baseline.""" + if self.reform is None: + return None + return build_post_export_reform(self.reform) 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 17ba72639a..067e66c872 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,6 +28,7 @@ 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.release_input_coverage import ( ListParameterEdit, ReformCoverageProbe, @@ -38,19 +39,12 @@ ) __all__ = [ - "RECORDS_REQUESTS_ONLY", "us_reform_coverage_smoke_gate", ] # simulate(reform_or_None) -> object with .calculate(measure, period).sum() SimulateFn = Callable[[Any], Any] -#: Set to ``True`` on a ``simulate`` that only records the keys it is asked -#: for and never applies a reform (the release tool's post-export plan dry -#: run). The gate then passes it each probe in place of the probe's built -#: reform, so recording resolves no list edit and needs no engine. -RECORDS_REQUESTS_ONLY = "records_requests_only" - def _weighted_total(simulation: Any, measure: str, period: int) -> float: """Weighted population total (policyengine-us MicroSeries .sum() is weighted).""" @@ -152,9 +146,10 @@ def us_reform_coverage_smoke_gate( simulate: ``simulate(None)`` builds the baseline; ``simulate(reform)`` builds the reformed simulation. Each result answers ``.calculate(measure, period).sum()`` as a weighted total. A - ``simulate`` whose :data:`RECORDS_REQUESTS_ONLY` attribute is true - only records requests: it receives each probe in place of the - probe's reform, and no reform is built. + ``simulate`` whose + :data:`~microcosm.build.us_runtime.post_export_requests.RECORDS_REQUESTS_ONLY` + attribute is true only records requests: it receives each probe + in place of the probe's reform, and no reform is built. probes: Probes to run. Defaults to the shipped manifest's probe set. period: Default period for probes without a probe-specific period. name: Gate name for the manifest. 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 36b1f30b53..4e0019604a 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 @@ -37,6 +37,10 @@ US_JCT_TAX_EXPENDITURE_REFORMS, SimpleTaxExpenditureReform, ) +from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, + ParameterChangesReform, +) from microcosm.calibrate.geography_constants import ( US_STATE_POSTAL_TO_NUMERIC_FIPS, ) @@ -746,6 +750,14 @@ def reform_validation_payload( incremental effect given the lines above it — so the per-line effects sum to the bill total, matching JCT (see ``stacked_obbba_effects``). The shape matches the calibration-diagnostics dashboard's reform_validation reader. + + A ``simulate`` whose + :data:`~microcosm.build.us_runtime.post_export_requests.RECORDS_REQUESTS_ONLY` + attribute is true only records requests (the release tool's post-export + dry run). It receives each reform's description in place of the built + reform: the spec for a row simulated on its own, and a + :class:`~microcosm.build.us_runtime.post_export_requests.ParameterChangesReform` + for each cumulative OBBBA state. No reform is built. """ estimates = in_sample_estimates or {} targets = in_sample_targets or {} @@ -754,6 +766,7 @@ def reform_validation_payload( obbba_specs = tuple(spec for spec in specs if _is_obbba_spec(spec)) obbba_pre_baseline_changes = _merged_parameter_changes(obbba_specs) obbba_stacked: dict[str, tuple[float, float, float]] | None = None + records_requests_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True def baseline_total(measure: str, at_period: int) -> float: nonlocal baseline @@ -765,8 +778,11 @@ def baseline_total(measure: str, at_period: int) -> float: return baseline_totals[key] def simulation_for_parameter_changes(changes: dict[str, Any]) -> Any: - reform = None if not changes else _build_parameter_reform(changes) - return simulate(reform) # type: ignore[misc] + if not changes: + return simulate(None) # type: ignore[misc] + if records_requests_only: + return simulate(ParameterChangesReform(changes)) # type: ignore[misc] + return simulate(_build_parameter_reform(changes)) # type: ignore[misc] def released_weighted_total( transient_simulation: Any, measure: str, at_period: int @@ -849,8 +865,9 @@ def simulated_effect( obbba_stacked = stacked_obbba_effects() return obbba_stacked.get(spec.id, (None, None, None)) base = baseline_total(spec.budget_measure, spec.period) + reform = spec if records_requests_only else spec.build_reform() reform_total = released_weighted_total( - simulate(spec.build_reform()), spec.budget_measure, spec.period + simulate(reform), spec.budget_measure, spec.period ) raw = reform_total - base # A counterfactual revert measures the provision as baseline − reform. diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index f672b84652..bb1a92180b 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -358,10 +358,14 @@ population_structure_holdout_unavailable, write_population_structure_holdout, ) +from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, + PostExportRequest, + check_post_export_reform, +) from microcosm.build.us_runtime.puf_capital_gains_tail import ( assert_puf_capital_gains_tail_survives_selection, ) -from microcosm.build.us_runtime.reform_coverage_smoke import RECORDS_REQUESTS_ONLY from microcosm.build.us_runtime.reform_validation import ( US_RELEASE_SPM_SELECTION, default_baseline_level_specs, @@ -5260,50 +5264,117 @@ def _post_export_values_and_weights(result, key: PostExportKey): class _RecordingPostExportSimulation: - """Engine-free stand-in that records the baseline keys a consumer asks for.""" + """Engine-free stand-in that records each key one simulation is asked for. - def __init__(self, keys: dict[PostExportKey, None] | None) -> None: - self._keys = keys + ``asked`` is shared by every recorder of one dry run: it collects + ``(simulation, key)`` in the order of first asks, where ``simulation`` is + the reformed simulation's number, or ``None`` for the baseline. + """ + + def __init__( + self, + asked: dict[tuple[int | None, PostExportKey], None], + simulation: int | None, + ) -> None: + self._asked = asked + self._simulation = simulation def calculate(self, variable, period=None, map_to=None) -> _PostExportValues: key = _post_export_key(variable, period, map_to) - if self._keys is not None: - self._keys.setdefault(key, None) + self._asked.setdefault((self._simulation, key), None) return _PostExportValues(np.zeros(0), np.zeros(0)) -def _record_post_export_requests( +def _dry_run_post_export_requests( consumer: Callable[[Callable[[Any], Any]], object], -) -> tuple[tuple[PostExportKey, ...], int]: - """Learn a consumer's baseline keys and reform pass count from recorders. - - No engine is constructed: ``simulate(None)`` returns a recorder that - logs every baseline request, and each ``simulate(reform)`` a recorder of - its own. The consumers ask for the same keys whatever values they get - back, and the served baseline refuses any key this dry run did not see, - so a value-dependent request cannot slip past the plan. ``simulate`` - carries ``RECORDS_REQUESTS_ONLY``, so the reform-coverage smoke gate hands - it each probe instead of building the probe's reform, and the dry run - resolves no list edit against an engine. - - When the consumer runs for real, each key a reformed simulation is first - asked for is one batched pass (``_BatchedPostExportReform``), so the pass - count is the distinct keys asked of each reformed simulation, summed. - Progress reporting alone uses it: a consumer that runs more passes than - counted reports no outer counter on the extra ones. +) -> tuple[tuple[int | None, object, PostExportKey], ...]: + """Every request ``consumer`` makes, learned from engine-free recorders. + + Returns ``(simulation, reform, key)`` for each request, in the order the + serial scorer runs them: the baseline plan first (``reform`` and + ``simulation`` None; ``_ascending_period_plan`` order), then the reform + requests. When the consumer runs for real, each key a reformed simulation + is first asked for is one batched pass (``_BatchedPostExportReform``), so + the reform requests follow those first asks; ``simulation`` numbers the + consumer's ``simulate(reform)`` calls from 0. + + No engine is constructed: ``simulate(None)`` returns a recorder that logs + every baseline request, and each ``simulate(reform)`` a recorder of its + own. The consumers ask for the same keys whatever values they get back, + and the served baseline refuses any key this dry run did not see, so a + value-dependent request cannot slip past the plan. ``simulate`` carries + ``RECORDS_REQUESTS_ONLY``, so each consumer hands it the description it + builds a reform from instead of building the reform (the reform-coverage + smoke check's probe, a reform-validation spec or a cumulative OBBBA + state's parameter changes), and the dry run resolves no list edit against + an engine. A reform given as anything else is refused + (``check_post_export_reform``): a worker process could not rebuild it. """ - keys: dict[PostExportKey, None] = {} - reform_keys: list[dict[PostExportKey, None]] = [] + asked: dict[tuple[int | None, PostExportKey], None] = {} + reforms: list[object] = [] def simulate(reform): if reform is None: - return _RecordingPostExportSimulation(keys) - reform_keys.append({}) - return _RecordingPostExportSimulation(reform_keys[-1]) + return _RecordingPostExportSimulation(asked, None) + check_post_export_reform(reform) + reforms.append(reform) + return _RecordingPostExportSimulation(asked, len(reforms) - 1) setattr(simulate, RECORDS_REQUESTS_ONLY, True) consumer(simulate) - return _ascending_period_plan(keys), sum(len(asked) for asked in reform_keys) + baseline = _ascending_period_plan( + key for simulation, key in asked if simulation is None + ) + return ( + *((None, None, key) for key in baseline), + *( + (simulation, reforms[simulation], key) + for simulation, key in asked + if simulation is not None + ), + ) + + +def _record_post_export_request_descriptors( + name: str, consumer: Callable[[Callable[[Any], Any]], object] +) -> tuple[PostExportRequest, ...]: + """Every request of the consumer ``name`` as a picklable descriptor. + + One ``PostExportRequest`` per request of the engine-free dry run + (``_dry_run_post_export_requests``), in the order the serial scorer runs + them, so a spawned worker process can run each request and the consumer's + output can be rebuilt from the results. Nothing records the descriptors: + the plan in ``calibration_diagnostics.json`` keeps its keys only. + """ + return 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( + _dry_run_post_export_requests(consumer) + ) + ) + + +def _record_post_export_requests( + consumer: Callable[[Callable[[Any], Any]], object], +) -> tuple[tuple[PostExportKey, ...], int]: + """Learn a consumer's baseline keys and reform pass count from its dry run. + + The baseline keys are the plan the served baseline scores; the pass count + is the dry run's reform requests (``_dry_run_post_export_requests``). + Progress reporting alone uses the count: a consumer that runs more passes + than counted reports no outer counter on the extra ones. + """ + requests = _dry_run_post_export_requests(consumer) + baseline = tuple(key for simulation, _, key in requests if simulation is None) + return baseline, len(requests) - len(baseline) def _record_post_export_baseline_plan( diff --git a/tools/sweep_us_post_export_scoring.py b/tools/sweep_us_post_export_scoring.py index 11b2bf6aae..037f99129e 100644 --- a/tools/sweep_us_post_export_scoring.py +++ b/tools/sweep_us_post_export_scoring.py @@ -31,7 +31,13 @@ def _load_builder(): def _record_requests(builder): - """Record OBBBA stacks and validation's missing-estimate fallback passes.""" + """Record OBBBA stacks and validation's missing-estimate fallback passes. + + The release's engine-free dry run records each consumer's requests as + picklable descriptors (``_record_post_export_request_descriptors``): the + baseline plans, and one reform request per reform pass, which each worker + rebuilds its reforms from. + """ specs = builder.load_default_reform_specs(period=builder.PERIOD) def validation(simulate): @@ -50,32 +56,19 @@ def validation(simulate): } plans, requests = {}, [] for name, consume in consumers.items(): - baseline = {} - - class RecordingSimulation: - def __init__(self, reform, *, name=name, baseline=baseline): - self.reform = reform - self.name = name - self.baseline = baseline - self.keys = set() - - def calculate(self, variable, period=None, map_to=None): - key = builder._post_export_key(variable, period, map_to) - if self.reform is None: - self.baseline.setdefault(key, None) - elif key not in self.keys: - requests.append((self.name, self.reform, key)) - self.keys.add(key) - return builder._RecordingPostExportSimulation(None).calculate(*key) - - consume(RecordingSimulation) - plans[name] = builder._ascending_period_plan(baseline) + recorded = builder._record_post_export_request_descriptors(name, consume) + plans[name] = tuple( + request.key for request in recorded if request.reform is None + ) + requests.extend(request for request in recorded if request.reform is not None) counts = { - "smoke_probes": sum(name == "reform_coverage_smoke" for name, _, _ in requests), + "smoke_probes": sum( + request.consumer == "reform_coverage_smoke" for request in requests + ), "validation_specs": sum(not spec.in_sample for spec in specs), "in_sample_fallback_specs": sum(spec.in_sample for spec in specs), "validation_reform_passes": sum( - name == "reform_validation" for name, _, _ in requests + request.consumer == "reform_validation" for request in requests ), "baseline_keys": {name: len(plan) for name, plan in plans.items()}, } @@ -124,9 +117,9 @@ def _score_baselines(builder, scorer, path, plans): def _comparison_indices(requests): """Compare the first two reform passes of each consumer to a whole file.""" seen, selected = {}, set() - for index, (name, _, _) in enumerate(requests): - seen[name] = seen.get(name, 0) + 1 - if seen[name] <= 2: + for index, request in enumerate(requests): + seen[request.consumer] = seen.get(request.consumer, 0) + 1 + if seen[request.consumer] <= 2: selected.add(index) return selected @@ -138,7 +131,8 @@ def _score_reforms(builder, scorer, path, requests, start, count): comparisons = _comparison_indices(requests) compared = [] for index in range(start, min(start + count, len(requests))): - name, reform, key = requests[index] + request = requests[index] + name, reform, key = request.consumer, request.build_reform(), request.key observed = consumer.simulate(reform).calculate(*key) if index in comparisons: whole = default_simulate_factory(path)(reform) From f3a170f0b2f47d49ce2619d3d2d05487518fde0b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:46:31 +0400 Subject: [PATCH 03/13] Test review round 1's descriptor gaps Failing tests for the gaps the first review found: the dry run accepts a reform description pickle cannot name; most descriptors look hashable but raise when hashed; a cumulative OBBBA state shares the consumer's dictionaries; the PostExportReform alias cannot be evaluated; and bad integer fields raise inconsistent error types. The recorded-outputs test also pins each stage's planned reform-pass count, as on origin/main. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_requests.py | 123 ++++++++++++++---- 1 file changed, 100 insertions(+), 23 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 449d62c212..6ca652b406 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 @@ -12,7 +12,9 @@ (the baseline plan, then each reform pass), name the reformed simulation that asked for each, and rebuild the reform that simulation was given; - every descriptor survives a pickle round trip through a spawned process; -- the dry run refuses a reform it cannot describe; +- the dry run refuses a reform it cannot describe or pickle; +- descriptors cannot be hashed and keep their own copy of a reform's + parameter changes; - the recorded outputs of the release stay byte-identical on the fixture. """ @@ -24,13 +26,17 @@ import json import multiprocessing import os +import pickle +import typing from collections.abc import Mapping from concurrent.futures import ProcessPoolExecutor +from types import MappingProxyType import microcosm.build.us_runtime.release_input_coverage as coverage_module from microcosm.build.us_runtime.post_export_requests import ( RECORDS_REQUESTS_ONLY, ParameterChangesReform, + PostExportReform, PostExportRequest, build_post_export_reform, ) @@ -309,23 +315,33 @@ def reformed(source): scorer.close() +@pytest.mark.parametrize("kind", ["built reform", "description pickle cannot name"]) def test_the_dry_run_refuses_a_reform_it_cannot_describe( - builder, no_engine, monkeypatch + builder, no_engine, monkeypatch, kind ) -> None: """A worker rebuilds each reform from its description, so a consumer that - hands the dry run a built reform fails the plan, which the release records - and refuses before the export, instead of recording a request no worker - could run.""" + hands the dry run a built reform, or a description that cannot be pickled, + fails the plan, which the release records and refuses before the export, + instead of recording a request no worker could run.""" class BuiltReform: pass + class LocalChanges(ParameterChangesReform): + """An accepted type, defined in a function: pickle cannot name it.""" + + if kind == "built reform": + reform, message = BuiltReform(), "BuiltReform" + else: + reform = LocalChanges({"gov.fixture": {"2024-01-01": 1}}) + message = "LocalChanges reform description that cannot be pickled" + def consumer(simulate): - simulate(BuiltReform()).calculate("income_tax", 2024) + simulate(reform).calculate("income_tax", 2024) - with pytest.raises(TypeError, match="BuiltReform"): + with pytest.raises(TypeError, match=message): builder._record_post_export_requests(consumer) - with pytest.raises(TypeError, match="BuiltReform"): + with pytest.raises(TypeError, match=message): builder._record_post_export_request_descriptors("fixture", consumer) monkeypatch.setattr( builder, @@ -339,7 +355,7 @@ def consumer(simulate): release_id=_RELEASE_ID, ) assert plan.error is not None - assert plan.error.startswith("TypeError") and "BuiltReform" in plan.error + assert plan.error.startswith("TypeError") and message in plan.error assert plan.terminal_failures() @@ -381,19 +397,24 @@ def test_a_request_rebuilds_its_reform_with_its_consumer_s_builder( @pytest.mark.parametrize( - "fields, message", + "fields, error, message", [ - ({"reform": None, "reformed_simulation": 0}, "reformed simulation"), - ({"reformed_simulation": None}, "reformed simulation"), - ({"reform": object()}, "object"), - ({"position": -1}, "position"), - ({"period": "2024"}, "period"), - ({"map_to": ""}, "map_to"), - ({"consumer": ""}, "consumer"), - ({"variable": ""}, "variable"), + ({"reform": None, "reformed_simulation": 0}, ValueError, "reformed simulation"), + ({"reformed_simulation": None}, ValueError, "reformed simulation"), + ({"reformed_simulation": -1}, ValueError, "reformed_simulation"), + ({"reformed_simulation": True}, TypeError, "reformed_simulation"), + ({"reformed_simulation": np.int64(0)}, TypeError, "reformed_simulation"), + ({"reform": object()}, TypeError, "object"), + ({"position": -1}, ValueError, "position"), + ({"position": np.int64(0)}, TypeError, "position"), + ({"period": "2024"}, TypeError, "period"), + ({"period": True}, TypeError, "period"), + ({"map_to": ""}, ValueError, "map_to"), + ({"consumer": ""}, ValueError, "consumer"), + ({"variable": ""}, ValueError, "variable"), ], ) -def test_a_request_refuses_inconsistent_fields(fields, message) -> None: +def test_a_request_refuses_inconsistent_fields(fields, error, message) -> None: valid = { "consumer": "fixture", "position": 0, @@ -404,7 +425,7 @@ def test_a_request_refuses_inconsistent_fields(fields, message) -> None: "reformed_simulation": 0, } PostExportRequest(**valid) - with pytest.raises((TypeError, ValueError), match=message): + with pytest.raises(error, match=message): PostExportRequest(**{**valid, **fields}) @@ -415,12 +436,54 @@ def test_parameter_changes_must_name_a_reform(changes) -> None: ParameterChangesReform(changes) +def test_descriptors_cannot_be_hashed_and_keep_their_own_changes() -> None: + """Most reform descriptions hold dictionaries, so no descriptor hashes + (results are keyed by consumer and position), and a cumulative OBBBA + state keeps a copy of the payload the consumer handed the dry run.""" + changes = {"gov.fixture.parameter": {"2026-01-01": 0}} + reform = ParameterChangesReform(changes) + changes["gov.fixture.parameter"]["2026-01-01"] = 1 + changes["gov.fixture.other"] = {"2026-01-01": 2} + assert reform.parameter_changes == {"gov.fixture.parameter": {"2026-01-01": 0}} + baseline = PostExportRequest( + consumer="fixture", position=0, variable="age", period=2024 + ) + reformed = PostExportRequest( + consumer="fixture", + position=1, + variable="income_tax", + period=2026, + reform=reform, + reformed_simulation=0, + ) + for value in (baseline, reformed, reform): + with pytest.raises(TypeError, match="unhashable"): + hash(value) + # A read-only mapping cannot be pickled; the copy is a dict, which can. + proxied = ParameterChangesReform( + MappingProxyType({"gov.fixture.parameter": {"2026-01-01": 0}}) + ) + assert type(proxied.parameter_changes) is dict + assert pickle.loads(pickle.dumps(proxied)) == proxied == reform + + +def test_the_reform_alias_names_the_three_descriptions() -> None: + assert typing.get_args(PostExportReform.__value__) == ( + ReformCoverageProbe, + ReformValidationSpec, + ParameterChangesReform, + ) + + #: SHA-256 of each output the post-export stages record, on the fixture frame #: and fake engine below, with a calibration fit covering two in-sample JCT #: reforms. Pinned from origin/main at fcabe4e65, before the dry run returned -#: descriptors. A change that moves one of them changes what a release records: -#: re-pin only when a probe, spec, baseline level or the fixture changed on -#: purpose, in the same pull request. +#: descriptors. The digests also cover the shipped probes, reform specs, +#: baseline levels and holdout benchmarks, so a change to any of those moves +#: 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. _RECORDED_OUTPUT_SHA256 = { "calibration_diagnostics.build.post_export_scoring": ( "7ed2a0dd088cf2d5a65e27e00368819cdf357160a5bdc2e42f079233d1f2f7b1" @@ -443,6 +506,17 @@ def test_parameter_changes_must_name_a_reform(changes) -> None: } +#: The reform passes the plan counts for each stage (its progress reporting +#: reads them), on the same fixture; also as on origin/main at fcabe4e65. +_PLANNED_REFORM_PASSES = { + "reform_coverage_smoke": 43, + "reform_validation": 64, + "demographics": 0, + "ssi_social_security_holdout": 0, + "medicare_irmaa_holdout": 0, +} + + def _json_ready(value): if isinstance(value, Mapping): return {str(key): _json_ready(item) for key, item in value.items()} @@ -468,6 +542,9 @@ def _recorded_post_export_outputs(builder, tmp_path) -> dict[str, object]: args, n_households=7, result=fit, release_id=_RELEASE_ID ) assert plan.error is None + assert { + name: plan.planned_reform_passes(name) for name in plan.baseline_plans + } == _PLANNED_REFORM_PASSES outputs: dict[str, object] = { "calibration_diagnostics.build.post_export_scoring": plan.record() } From 41644c640671ce19650bd316739f2a67a86fcc03 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:47:42 +0400 Subject: [PATCH 04/13] Close review round 1's descriptor gaps - check_post_export_reform also pickles each reform description, so a description pickle cannot name fails the release's pre-export plan, not the hand-over to a worker. - PostExportRequest and ParameterChangesReform are unhashable on purpose (most descriptions hold dictionaries); results are keyed by consumer and position. - ParameterChangesReform keeps a deep copy of its payload as a dict, so no later change to the consumer's dictionaries, which its reform specs share, reaches a recorded request. - reform_validation imports post_export_requests inside reform_validation_payload, so post_export_requests can import ReformValidationSpec and the PostExportReform alias evaluates. - Integer fields raise TypeError for a non-integer and ValueError below their minimum. - The descriptor function's docstring says that rebuilding an output means running the consumer again over the results: the smoke check also records each list-edit probe's resolved lists from the reform it builds itself. Co-Authored-By: Claude Opus 5.5 --- ...s-post-export-request-descriptors.added.md | 2 +- docs/us-release-build-rule.md | 16 ++-- .../build/us_runtime/post_export_requests.py | 90 ++++++++++++------- .../build/us_runtime/reform_validation.py | 10 ++- tools/build_us_fiscal_refresh_release.py | 10 ++- 5 files changed, 80 insertions(+), 48 deletions(-) diff --git a/changelog.d/us-post-export-request-descriptors.added.md b/changelog.d/us-post-export-request-descriptors.added.md index aa0e554302..21a699a80a 100644 --- a/changelog.d/us-post-export-request-descriptors.added.md +++ b/changelog.d/us-post-export-request-descriptors.added.md @@ -1 +1 @@ -The US release's engine-free post-export dry run now returns every request each post-export stage makes as a picklable `PostExportRequest` (`microcosm.build.us_runtime.post_export_requests`): the stage, the request's place in the order the serial scorer runs it, the variable, period and `map_to`, and for a reform request the description its reform is rebuilt from (the smoke probe, the reform-validation spec, or a cumulative OBBBA state's parameter changes) and which of the stage's reformed simulations asked for it. Reform validation, like the smoke check, now hands the dry run those descriptions instead of building reforms, so the dry run needs no policyengine-core, and it refuses a reform it cannot describe. Nothing records the descriptors: `calibration_diagnostics.json` and every post-export output keep their bytes, which a test pins on a fixture. `RECORDS_REQUESTS_ONLY` moves from `reform_coverage_smoke` to the new module. `tools/sweep_us_post_export_scoring.py` records through the descriptors and rebuilds each reform in the worker that scores it. +The US release's engine-free post-export dry run now returns every request each post-export stage makes as a picklable `PostExportRequest` (`microcosm.build.us_runtime.post_export_requests`): the stage, the request's place in the order the serial scorer runs it, the variable, period and `map_to`, and for a reform request the description its reform is rebuilt from (the smoke probe, the reform-validation spec, or a cumulative OBBBA state's parameter changes) and which of the stage's reformed simulations asked for it. Reform validation, like the smoke check, now hands the dry run those descriptions instead of building reforms, so the dry run needs no policyengine-core, and it refuses a reform it cannot describe or pickle. Nothing records the descriptors: the plan in `calibration_diagnostics.json`, each stage's output and each stage's reform-pass count stay the same, which a test pins on a fixture. `RECORDS_REQUESTS_ONLY` moves from `reform_coverage_smoke` to the new module. `tools/sweep_us_post_export_scoring.py` records through the descriptors and rebuilds each reform in the worker that scores it. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 8eaf71221b..7a621be9c2 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -445,18 +445,18 @@ one Microsimulation over the whole file. - Each stage's baseline requests are learned before export by an engine-free dry run and scored in one pass over the batches, in ascending period order. One engine refuses a period earlier than one it has already computed. - The same dry run 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. 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 one it cannot describe. Nothing records - the descriptors; the guard sweep below rebuilds each reform from its - descriptor in the worker that scores it. The real-engine test probes the MD CCS request-order premise by requesting 2025 state taxes after 2027 keys. It checks for the `md.msde.ccs.payment.informal.rates` error and warns if that error is absent; it does not require the upstream bug to persist. +- The same dry run 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. 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. + Nothing records the descriptors; the guard sweep below rebuilds each reform + from its descriptor in the worker that scores it. - 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_requests.py b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py index 7b752ef21f..05b45ab4fc 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 @@ -25,20 +25,22 @@ class defined inside a function, which pickle cannot name. So a consumer whose These types live here, in an importable package, because the release tool is loaded by file path, outside ``sys.modules``: a spawned process could not -unpickle a type defined in it. +unpickle a type defined in it. Neither type can be hashed, because a reform +description holds dictionaries; key a request's results by its +``(consumer, position)``. """ from __future__ import annotations +import copy +import pickle from collections.abc import Mapping from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from typing import Any +from microcosm.build.us_runtime.reform_validation import ReformValidationSpec from microcosm.build.us_runtime.release_input_coverage import ReformCoverageProbe -if TYPE_CHECKING: - from microcosm.build.us_runtime.reform_validation import ReformValidationSpec - __all__ = [ "RECORDS_REQUESTS_ONLY", "ParameterChangesReform", @@ -63,10 +65,17 @@ class ParameterChangesReform: Reform validation scores OBBBA's provisions cumulatively from a pre-OBBBA state; each state is one such payload. An empty payload is the baseline, which a consumer asks for as ``simulate(None)``, so it is refused here. + + It keeps a deep copy of the payload, as a ``dict``: the request records + the reform as the consumer asked for it, and no later change to the + consumer's dictionaries (which its reform specs share) reaches it. """ parameter_changes: Mapping[str, Any] + # Not hashable: the payload is a dictionary. + __hash__ = None # type: ignore[assignment] + def __post_init__(self) -> None: if not isinstance(self.parameter_changes, Mapping): raise TypeError( @@ -78,6 +87,9 @@ def __post_init__(self) -> None: "ParameterChangesReform needs at least one of its parameter " "changes; the baseline is simulate(None)." ) + object.__setattr__( + self, "parameter_changes", copy.deepcopy(dict(self.parameter_changes)) + ) #: What a post-export request records as its reform: the description the @@ -87,28 +99,40 @@ def __post_init__(self) -> None: ) -def _post_export_reform_types() -> tuple[type, ...]: - # Imported here: reform_validation imports this module. - from microcosm.build.us_runtime.reform_validation import ReformValidationSpec - - return (ReformCoverageProbe, ReformValidationSpec, ParameterChangesReform) +_POST_EXPORT_REFORM_TYPES = ( + ReformCoverageProbe, + ReformValidationSpec, + ParameterChangesReform, +) def check_post_export_reform(reform: object) -> None: """Refuse a reform that is not a description a worker can rebuild. + The description must be one of the accepted types and must pickle, so a + failure shows in the release's pre-export plan rather than when a request + is sent to a worker. + Raises: - TypeError: Naming the reform's type and the types accepted. + TypeError: Naming the reform's type and the types accepted, or why + the description cannot be pickled. """ - types = _post_export_reform_types() - if not isinstance(reform, types): - accepted = ", ".join(kind.__name__ for kind in types) + if not isinstance(reform, _POST_EXPORT_REFORM_TYPES): + accepted = ", ".join(kind.__name__ for kind in _POST_EXPORT_REFORM_TYPES) raise TypeError( "Post-export scoring records each reform as the description a worker " f"rebuilds it from ({accepted}); got a {type(reform).__qualname__}. " "A consumer whose simulate carries RECORDS_REQUESTS_ONLY must hand it " "that description, not a built reform." ) + try: + pickle.dumps(reform) + except (pickle.PicklingError, TypeError, AttributeError) as error: + raise TypeError( + f"Post-export scoring got a {type(reform).__qualname__} reform " + "description that cannot be pickled for a worker process: " + f"{type(error).__name__}: {error}" + ) from error def build_post_export_reform(reform: PostExportReform) -> Any: @@ -129,6 +153,17 @@ def build_post_export_reform(reform: PostExportReform) -> Any: return reform.build_reform() +def _require_integer(name: str, value: object, *, minimum: int | None = None) -> None: + if not isinstance(value, int) or isinstance(value, bool): + raise TypeError( + f"PostExportRequest.{name} must be a Python integer, got {value!r}." + ) + if minimum is not None and value < minimum: + raise ValueError( + f"PostExportRequest.{name} must be {minimum} or more, got {value}." + ) + + @dataclass(frozen=True) class PostExportRequest: """One request a post-export consumer makes of policyengine-us. @@ -162,6 +197,9 @@ class PostExportRequest: reform: PostExportReform | None = None reformed_simulation: int | None = None + # Not hashable: most reform descriptions hold dictionaries. + __hash__ = None # type: ignore[assignment] + def __post_init__(self) -> None: for name in ("consumer", "variable"): value = getattr(self, name) @@ -170,16 +208,8 @@ def __post_init__(self) -> None: f"PostExportRequest.{name} must be a non-empty string, " f"got {value!r}." ) - for name in ("position", "period"): - value = getattr(self, name) - if not isinstance(value, int) or isinstance(value, bool): - raise TypeError( - f"PostExportRequest.{name} must be an integer, got {value!r}." - ) - if self.position < 0: - raise ValueError( - f"PostExportRequest.position must be 0 or more, got {self.position}." - ) + _require_integer("position", self.position, minimum=0) + _require_integer("period", self.period) if self.map_to is not None and ( not isinstance(self.map_to, str) or not self.map_to ): @@ -195,16 +225,12 @@ def __post_init__(self) -> None: ) return check_post_export_reform(self.reform) - simulation = self.reformed_simulation - if ( - not isinstance(simulation, int) - or isinstance(simulation, bool) - or simulation < 0 - ): + if self.reformed_simulation is None: raise ValueError( - "A reform PostExportRequest names its reformed simulation as an " - f"integer of 0 or more, got {simulation!r}." + "A reform PostExportRequest names the reformed simulation that " + "asked for it." ) + _require_integer("reformed_simulation", self.reformed_simulation, minimum=0) @property def key(self) -> tuple[str, int, str | None]: 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 4e0019604a..3e06147e68 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 @@ -37,10 +37,6 @@ US_JCT_TAX_EXPENDITURE_REFORMS, SimpleTaxExpenditureReform, ) -from microcosm.build.us_runtime.post_export_requests import ( - RECORDS_REQUESTS_ONLY, - ParameterChangesReform, -) from microcosm.calibrate.geography_constants import ( US_STATE_POSTAL_TO_NUMERIC_FIPS, ) @@ -759,6 +755,12 @@ def reform_validation_payload( :class:`~microcosm.build.us_runtime.post_export_requests.ParameterChangesReform` for each cumulative OBBBA state. No reform is built. """ + # Imported here: post_export_requests imports ReformValidationSpec. + from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, + ParameterChangesReform, + ) + estimates = in_sample_estimates or {} targets = in_sample_targets or {} baseline: Any = None diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index bb1a92180b..62dea2fca9 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -5342,9 +5342,13 @@ def _record_post_export_request_descriptors( One ``PostExportRequest`` per request of the engine-free dry run (``_dry_run_post_export_requests``), in the order the serial scorer runs - them, so a spawned worker process can run each request and the consumer's - output can be rebuilt from the results. Nothing records the descriptors: - the plan in ``calibration_diagnostics.json`` keeps its keys only. + them, so a spawned worker process can run each request. The results are + the values each request calculates; a consumer's output also holds what + it reads off the reforms it builds itself (the smoke check records each + list-edit probe's resolved lists from its built reform), so rebuilding an + output means running the consumer again over the results. Nothing records + the descriptors: the plan in ``calibration_diagnostics.json`` keeps its + keys only. """ return tuple( PostExportRequest( From 7f5c9e056899cb84ee227b71491d855f71b6dcfc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:13:34 +0400 Subject: [PATCH 05/13] Test review round 2's descriptor gaps Failing tests for the gaps the second review found: the dry run accepts a subclass of a description type from a module only this process has, which pickles here but which a spawned worker could not unpickle; a pickling failure raised as ValueError escapes the refusal; parameter changes that cannot be copied raise an unexplained error; and wrong-typed string fields raise ValueError instead of TypeError. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_requests.py | 87 +++++++++++++++---- 1 file changed, 71 insertions(+), 16 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 6ca652b406..439502d268 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 @@ -21,12 +21,16 @@ # ruff: noqa: F403, F405 from __future__ import annotations +import dataclasses import hashlib import itertools import json import multiprocessing import os import pickle +import re +import threading +import types import typing from collections.abc import Mapping from concurrent.futures import ProcessPoolExecutor @@ -315,26 +319,69 @@ def reformed(source): scorer.close() -@pytest.mark.parametrize("kind", ["built reform", "description pickle cannot name"]) -def test_the_dry_run_refuses_a_reform_it_cannot_describe( - builder, no_engine, monkeypatch, kind -) -> None: - """A worker rebuilds each reform from its description, so a consumer that - hands the dry run a built reform, or a description that cannot be pickled, - fails the plan, which the release records and refuses before the export, - instead of recording a request no worker could run.""" +class _Unreducible: + """A value whose pickling raises ``ValueError``, not ``PicklingError``.""" + + def __reduce__(self): + raise ValueError("fixture value refuses to be pickled") + + +def _undescribable_reform(kind: str, monkeypatch): + """(a reform the dry run must refuse, the message it must give).""" class BuiltReform: pass - class LocalChanges(ParameterChangesReform): - """An accepted type, defined in a function: pickle cannot name it.""" - + spec = next( + spec + for spec in reform_validation_module.load_default_reform_specs(period=2024) + if spec.parameter_changes + ) if kind == "built reform": - reform, message = BuiltReform(), "BuiltReform" - else: - reform = LocalChanges({"gov.fixture": {"2024-01-01": 1}}) - message = "LocalChanges reform description that cannot be pickled" + return BuiltReform(), "got a .*BuiltReform" + if kind == "subclass registered only in this process": + # It pickles here, by its module's name; a spawned worker, which has + # no such module, could not unpickle it. + module = types.ModuleType("registered_only_in_this_process") + exec( + "from microcosm.build.us_runtime.post_export_requests import " + "ParameterChangesReform\n" + "class RegisteredChanges(ParameterChangesReform):\n" + " pass\n", + module.__dict__, + ) + monkeypatch.setitem(sys.modules, module.__name__, module) + reform = module.RegisteredChanges({"gov.fixture": {"2024-01-01": 1}}) + pickle.dumps(reform) + return reform, "got a RegisteredChanges" + if kind == "read-only mapping": + proxied = dataclasses.replace( + spec, parameter_changes=MappingProxyType(dict(spec.parameter_changes)) + ) + return proxied, "ReformValidationSpec reform description that cannot be pickled" + unreducible = dataclasses.replace( + spec, parameter_changes={"gov.fixture": {"2024-01-01": _Unreducible()}} + ) + return unreducible, "cannot be pickled .*ValueError: fixture value refuses" + + +@pytest.mark.parametrize( + "kind", + [ + "built reform", + "subclass registered only in this process", + "read-only mapping", + "value whose pickling raises ValueError", + ], +) +def test_the_dry_run_refuses_a_reform_it_cannot_describe( + builder, no_engine, monkeypatch, kind +) -> None: + """A worker rebuilds each reform from its description, so a consumer that + hands the dry run a built reform, or a description a worker might not + unpickle, fails the plan, which the release records and refuses before + the export, instead of recording a request no worker could run.""" + reform, message = _undescribable_reform(kind, monkeypatch) def consumer(simulate): simulate(reform).calculate("income_tax", 2024) @@ -355,7 +402,7 @@ def consumer(simulate): release_id=_RELEASE_ID, ) assert plan.error is not None - assert plan.error.startswith("TypeError") and message in plan.error + assert plan.error.startswith("TypeError") and re.search(message, plan.error) assert plan.terminal_failures() @@ -410,8 +457,11 @@ def test_a_request_rebuilds_its_reform_with_its_consumer_s_builder( ({"period": "2024"}, TypeError, "period"), ({"period": True}, TypeError, "period"), ({"map_to": ""}, ValueError, "map_to"), + ({"map_to": 5}, TypeError, "map_to"), ({"consumer": ""}, ValueError, "consumer"), + ({"consumer": 5}, TypeError, "consumer"), ({"variable": ""}, ValueError, "variable"), + ({"variable": None}, TypeError, "variable"), ], ) def test_a_request_refuses_inconsistent_fields(fields, error, message) -> None: @@ -436,6 +486,11 @@ def test_parameter_changes_must_name_a_reform(changes) -> None: ParameterChangesReform(changes) +def test_parameter_changes_that_cannot_be_copied_are_refused() -> None: + with pytest.raises(TypeError, match="parameter changes cannot be copied"): + ParameterChangesReform({"gov.fixture": {"2024-01-01": threading.Lock()}}) + + def test_descriptors_cannot_be_hashed_and_keep_their_own_changes() -> None: """Most reform descriptions hold dictionaries, so no descriptor hashes (results are keyed by consumer and position), and a cumulative OBBBA From e915ee2939f6ff4efd1a1569ba6980b2f7169a79 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:15:02 +0400 Subject: [PATCH 06/13] Close review round 2's descriptor gaps - check_post_export_reform accepts exactly the three description types, not subclasses, whose module a spawned worker might not have, and refuses every exception a trial pickle raises. - ParameterChangesReform reports changes it cannot copy as a TypeError that says so. - PostExportRequest raises TypeError for a wrong-typed string field and ValueError for an empty one, as it does for its integer fields. - The module docstring gives the right reason the types live in a package: a spawned process unpickles them however the release tool was started, while a type in the tool would unpickle only when the tool runs as a script, and then only by running the whole tool again as __mp_main__. - The docs, the changelog and the sweep's docstring say that _record_post_export_request_descriptors returns the descriptors and the release itself still takes only the plans and pass counts, and the changelog says the plan no longer builds reform-validation reform classes before the export. Co-Authored-By: Claude Opus 5.5 --- ...s-post-export-request-descriptors.added.md | 2 +- docs/us-release-build-rule.md | 8 ++- .../build/us_runtime/post_export_requests.py | 64 +++++++++++-------- .../post_export_request_worker.py | 8 ++- tools/sweep_us_post_export_scoring.py | 8 +-- 5 files changed, 52 insertions(+), 38 deletions(-) diff --git a/changelog.d/us-post-export-request-descriptors.added.md b/changelog.d/us-post-export-request-descriptors.added.md index 21a699a80a..0221f9ff14 100644 --- a/changelog.d/us-post-export-request-descriptors.added.md +++ b/changelog.d/us-post-export-request-descriptors.added.md @@ -1 +1 @@ -The US release's engine-free post-export dry run now returns every request each post-export stage makes as a picklable `PostExportRequest` (`microcosm.build.us_runtime.post_export_requests`): the stage, the request's place in the order the serial scorer runs it, the variable, period and `map_to`, and for a reform request the description its reform is rebuilt from (the smoke probe, the reform-validation spec, or a cumulative OBBBA state's parameter changes) and which of the stage's reformed simulations asked for it. Reform validation, like the smoke check, now hands the dry run those descriptions instead of building reforms, so the dry run needs no policyengine-core, and it refuses a reform it cannot describe or pickle. Nothing records the descriptors: the plan in `calibration_diagnostics.json`, each stage's output and each stage's reform-pass count stay the same, which a test pins on a fixture. `RECORDS_REQUESTS_ONLY` moves from `reform_coverage_smoke` to the new module. `tools/sweep_us_post_export_scoring.py` records through the descriptors and rebuilds each reform in the worker that scores it. +The US release tool's `_record_post_export_request_descriptors` returns every request each post-export stage makes in the engine-free post-export dry run as a picklable `PostExportRequest` (`microcosm.build.us_runtime.post_export_requests`), for later work that runs the requests in worker processes; the release itself still takes only the baseline plans and reform-pass counts. A descriptor holds the stage, the request's place in the order the serial scorer runs it, the variable, period and `map_to`, and for a reform request the description its reform is rebuilt from (the smoke probe, the reform-validation spec, or a cumulative OBBBA state's parameter changes) and which of the stage's reformed simulations asked for it. Reform validation, like the smoke check, now hands the dry run those descriptions instead of building reforms, so the dry run needs no policyengine-core, and it refuses a reform it cannot describe or pickle. The plan no longer builds reform-validation reform classes before the export, as it already did not for the smoke check. Nothing records the descriptors: the plan in `calibration_diagnostics.json`, each stage's output and each stage's reform-pass count stay the same, which a test pins on a fixture. `RECORDS_REQUESTS_ONLY` moves from `reform_coverage_smoke` to the new module. `tools/sweep_us_post_export_scoring.py` records through the descriptors and rebuilds each reform in the worker that scores it. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 7a621be9c2..62c3cfb587 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -449,9 +449,11 @@ one Microsimulation over the whole file. 2025 state taxes after 2027 keys. It checks for the `md.msde.ccs.payment.informal.rates` error and warns if that error is absent; it does not require the upstream bug to persist. -- The same dry run 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. A reform request holds +- The same dry run sees every request, baseline and reform. + `_record_post_export_request_descriptors` returns them as picklable + `PostExportRequest`s (`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 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. 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 05b45ab4fc..d926e7bdc2 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 @@ -5,8 +5,10 @@ once against engine-free recorders (its "dry run"). The consumers call ``simulate(None)`` for the baseline simulation and ``simulate(reform)`` for a reformed one, then ``.calculate(variable, period, map_to=...)`` on each. The -dry run returns every such request as a :class:`PostExportRequest`, which a -process started with the ``spawn`` method can unpickle and run. +release takes only each consumer's baseline plan and reform-pass count from the +dry run; the tool's ``_record_post_export_request_descriptors`` returns every +request of the same dry run as a :class:`PostExportRequest`, which a process +started with the ``spawn`` method can unpickle and run. A built reform cannot cross a process boundary: ``Reform.from_dict`` returns a class defined inside a function, which pickle cannot name. So a consumer whose @@ -23,11 +25,16 @@ class defined inside a function, which pickle cannot name. So a consumer whose - a :class:`ParameterChangesReform` (one of reform validation's cumulative OBBBA states), rebuilt by ``reform_validation._build_parameter_reform``. -These types live here, in an importable package, because the release tool is -loaded by file path, outside ``sys.modules``: a spawned process could not -unpickle a type defined in it. Neither type can be hashed, because a reform -description holds dictionaries; key a request's results by its -``(consumer, position)``. +These types live here, in an importable package, so that a spawned process +can unpickle them however the release tool was started. The tests and the +guard sweep load the tool by file path, outside ``sys.modules``, where a type +defined in it cannot be unpickled at all. A release runs the tool as a script, +where a spawned process would unpickle such a type only by running the whole +tool again as its ``__mp_main__`` module (which a process started with +``spawn`` does to the parent's main script in any case). + +Neither type can be hashed, because a reform description holds dictionaries; +key a request's results by its ``(consumer, position)``. """ from __future__ import annotations @@ -87,9 +94,14 @@ def __post_init__(self) -> None: "ParameterChangesReform needs at least one of its parameter " "changes; the baseline is simulate(None)." ) - object.__setattr__( - self, "parameter_changes", copy.deepcopy(dict(self.parameter_changes)) - ) + try: + copied = copy.deepcopy(dict(self.parameter_changes)) + except Exception as error: + raise TypeError( + "ParameterChangesReform's parameter changes cannot be copied: " + f"{type(error).__name__}: {error}" + ) from error + object.__setattr__(self, "parameter_changes", copied) #: What a post-export request records as its reform: the description the @@ -109,7 +121,8 @@ def __post_init__(self) -> None: def check_post_export_reform(reform: object) -> None: """Refuse a reform that is not a description a worker can rebuild. - The description must be one of the accepted types and must pickle, so a + The description must be exactly one of the accepted types, not a + subclass, whose module a worker might not have, and must pickle, so a failure shows in the release's pre-export plan rather than when a request is sent to a worker. @@ -117,7 +130,7 @@ def check_post_export_reform(reform: object) -> None: TypeError: Naming the reform's type and the types accepted, or why the description cannot be pickled. """ - if not isinstance(reform, _POST_EXPORT_REFORM_TYPES): + if type(reform) not in _POST_EXPORT_REFORM_TYPES: accepted = ", ".join(kind.__name__ for kind in _POST_EXPORT_REFORM_TYPES) raise TypeError( "Post-export scoring records each reform as the description a worker " @@ -127,7 +140,7 @@ def check_post_export_reform(reform: object) -> None: ) try: pickle.dumps(reform) - except (pickle.PicklingError, TypeError, AttributeError) as error: + except Exception as error: raise TypeError( f"Post-export scoring got a {type(reform).__qualname__} reform " "description that cannot be pickled for a worker process: " @@ -153,6 +166,13 @@ def build_post_export_reform(reform: PostExportReform) -> Any: return reform.build_reform() +def _require_name(name: str, value: object) -> None: + if not isinstance(value, str): + raise TypeError(f"PostExportRequest.{name} must be a string, got {value!r}.") + if not value: + raise ValueError(f"PostExportRequest.{name} must not be empty.") + + def _require_integer(name: str, value: object, *, minimum: int | None = None) -> None: if not isinstance(value, int) or isinstance(value, bool): raise TypeError( @@ -201,22 +221,12 @@ class PostExportRequest: __hash__ = None # type: ignore[assignment] def __post_init__(self) -> None: - for name in ("consumer", "variable"): - value = getattr(self, name) - if not isinstance(value, str) or not value: - raise ValueError( - f"PostExportRequest.{name} must be a non-empty string, " - f"got {value!r}." - ) + _require_name("consumer", self.consumer) + _require_name("variable", self.variable) _require_integer("position", self.position, minimum=0) _require_integer("period", self.period) - if self.map_to is not None and ( - not isinstance(self.map_to, str) or not self.map_to - ): - raise ValueError( - "PostExportRequest.map_to must be None or an entity name, got " - f"{self.map_to!r}." - ) + if self.map_to is not None: + _require_name("map_to", self.map_to) if self.reform is None: if self.reformed_simulation is not None: raise ValueError( diff --git a/test_support/microcosm_build/post_export_request_worker.py b/test_support/microcosm_build/post_export_request_worker.py index 2ac0dced09..52b752b6f5 100644 --- a/test_support/microcosm_build/post_export_request_worker.py +++ b/test_support/microcosm_build/post_export_request_worker.py @@ -1,9 +1,11 @@ """What a spawned pool worker receives of the post-export requests sent to it. This module imports nothing beyond the standard library, so a spawned process -that runs it loads only what unpickling the requests needs. The release tool -(``tools/build_us_fiscal_refresh_release.py``) is loaded by file path, outside -``sys.modules``; a type defined there cannot be unpickled in such a process. +that runs it loads what unpickling the requests needs and whatever the parent's +main script imports (under pytest, not the release tool). The tests load the +release tool (``tools/build_us_fiscal_refresh_release.py``) by file path, +outside ``sys.modules``, so a type defined there cannot be unpickled in such a +process. """ from __future__ import annotations diff --git a/tools/sweep_us_post_export_scoring.py b/tools/sweep_us_post_export_scoring.py index 037f99129e..fd6ca50296 100644 --- a/tools/sweep_us_post_export_scoring.py +++ b/tools/sweep_us_post_export_scoring.py @@ -33,10 +33,10 @@ def _load_builder(): def _record_requests(builder): """Record OBBBA stacks and validation's missing-estimate fallback passes. - The release's engine-free dry run records each consumer's requests as - picklable descriptors (``_record_post_export_request_descriptors``): the - baseline plans, and one reform request per reform pass, which each worker - rebuilds its reforms from. + ``_record_post_export_request_descriptors`` returns each consumer's + requests from the release's engine-free dry run as picklable descriptors: + the baseline plans, and one reform request per reform pass, from which + each worker rebuilds the reforms it scores. """ specs = builder.load_default_reform_specs(period=builder.PERIOD) From 19a098a4de495b197d34592798622808dcd0170c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:33:22 +0400 Subject: [PATCH 07/13] Test that the dry run names a refused reform's module Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_us_post_export_requests.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 439502d268..abd58c70a8 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 @@ -353,7 +353,10 @@ class BuiltReform: monkeypatch.setitem(sys.modules, module.__name__, module) reform = module.RegisteredChanges({"gov.fixture": {"2024-01-01": 1}}) pickle.dumps(reform) - return reform, "got a RegisteredChanges" + return ( + reform, + r"got a registered_only_in_this_process\.RegisteredChanges\. .* exactly", + ) if kind == "read-only mapping": proxied = dataclasses.replace( spec, parameter_changes=MappingProxyType(dict(spec.parameter_changes)) From a47df411b58571dbcae60e8a3ba6b2a983a42949 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:37:36 +0400 Subject: [PATCH 08/13] Name a refused reform's module, and fix two wordings The third review found the refusal message ambiguous for a subclass or a second copy of a description class, since it named the type without its module and ended "not a built reform". It now names the module and says the description must be one of the three types exactly. The module docstring now says a type in the tool loaded by file path cannot even be pickled, and the docs say _record_post_export_request_descriptors runs its own call of the dry run. Co-Authored-By: Claude Opus 5.5 --- docs/us-release-build-rule.md | 10 +++++----- .../microcosm/build/us_runtime/post_export_requests.py | 9 +++++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 62c3cfb587..d38f974e96 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -449,11 +449,11 @@ one Microsimulation over the whole file. 2025 state taxes after 2027 keys. It checks for the `md.msde.ccs.payment.informal.rates` error and warns if that error is absent; it does not require the upstream bug to persist. -- The same dry run sees every request, baseline and reform. - `_record_post_export_request_descriptors` returns them as picklable - `PostExportRequest`s (`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 reform request holds +- `_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 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. 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 d926e7bdc2..b954240fd1 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 @@ -28,7 +28,7 @@ class defined inside a function, which pickle cannot name. So a consumer whose These types live here, in an importable package, so that a spawned process can unpickle them however the release tool was started. The tests and the guard sweep load the tool by file path, outside ``sys.modules``, where a type -defined in it cannot be unpickled at all. A release runs the tool as a script, +defined in it cannot even be pickled. A release runs the tool as a script, where a spawned process would unpickle such a type only by running the whole tool again as its ``__mp_main__`` module (which a process started with ``spawn`` does to the parent's main script in any case). @@ -134,9 +134,10 @@ def check_post_export_reform(reform: object) -> None: accepted = ", ".join(kind.__name__ for kind in _POST_EXPORT_REFORM_TYPES) raise TypeError( "Post-export scoring records each reform as the description a worker " - f"rebuilds it from ({accepted}); got a {type(reform).__qualname__}. " - "A consumer whose simulate carries RECORDS_REQUESTS_ONLY must hand it " - "that description, not a built reform." + f"rebuilds it from ({accepted}); got a {type(reform).__module__}." + f"{type(reform).__qualname__}. A consumer whose simulate carries " + "RECORDS_REQUESTS_ONLY must hand it a description of one of those " + "types exactly, not a built reform or a subclass." ) try: pickle.dumps(reform) From 2d784ef873920c71b701868f9d0b97e915c430c5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:41:14 +0400 Subject: [PATCH 09/13] Classify post_export_requests among the reviewed US runtime modules test_us_runtime_module_classification_is_complete refuses a us_runtime module that is neither a registered population operator nor a reviewed other module. The new module reads no frame and treats no population. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_us_spine_blindness.py | 3 +++ 1 file changed, 3 insertions(+) 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 44664623b6..f1aa1e1016 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", + # 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", "pregnancy.py", # Pinned-archive sidecar restore (PAW_TYP); no population treatment. "public_assistance_type_source.py", From 1cbb20cdc67eca4b606df2b483dd03a5d6a42fc0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:15:51 +0400 Subject: [PATCH 10/13] Count post_export_requests among the modules the bindings reach reform_coverage_smoke now imports RECORDS_REQUESTS_ONLY from us_runtime.post_export_requests, so the hashes of the transport registry's bindings cover one more module (247, not 246). The engine-free CI job's test_the_batterys_binding_identity_adds_only_the_leaf_and_its_imports failed on that count. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_transport_evidence_kernels.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index 3e96f22df9..6e1577fd19 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -153,6 +153,9 @@ # microcosm#1585 item 11: us_runtime.multispine_pool's shadow sites # import us_runtime.gate_shadow. "microcosm.build.us_runtime.gate_shadow", + # microcosm#1722: us_runtime.reform_coverage_smoke imports + # RECORDS_REQUESTS_ONLY from us_runtime.post_export_requests. + "microcosm.build.us_runtime.post_export_requests", # microcosm#1405: the gate battery refuses a signing key the committed # registry does not let sign, so it imports # microcosm.data.gate_signing_keys, and with it the microcosm.data From 2240525cae45897fe67bb2c4b7d4636448caf185 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:40:18 +0400 Subject: [PATCH 11/13] Ask each reformed simulation completely in the first-ask order test Since the shared worker pool (#1726), the post-export scorer finishes a reformed simulation when the consumer opens the next one and refuses it further keys. The test's consumer opened all three reformed simulations before asking any, so the scored half of test_reform_requests_follow_the_order_of_first_asks raised on main. Its consumer now asks each reformed simulation for all its keys before opening the next, and still covers a repeated key, a simulation asked two keys, and an unasked simulation that keeps its number. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_requests.py | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 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 abd58c70a8..44ca64e73c 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 @@ -267,8 +267,11 @@ def test_reform_requests_follow_the_order_of_first_asks( builder, fake_reforms, tmp_path ) -> None: """A reform pass runs when a reformed simulation is first asked for a key, - so the descriptors follow those first asks across simulations; a - simulation never asked makes no request but keeps its number.""" + so the descriptors follow those first asks. The scorer finishes a + reformed simulation when the consumer opens the next one and refuses it + further keys, so a consumer asks each reformed simulation for all its + keys before opening the next; a simulation never asked makes no request + but keeps its number.""" first = ParameterChangesReform({"gov.fixture.first": {"2024-01-01": 1}}) second = ParameterChangesReform({"gov.fixture.second": {"2024-01-01": 2}}) unasked = ParameterChangesReform({"gov.fixture.unasked": {"2024-01-01": 3}}) @@ -282,22 +285,22 @@ def reformed(source): ) first_simulation = reformed(first) - second_simulation = reformed(second) - reformed(unasked) simulate(None).calculate("income_tax", 2025) - second_simulation.calculate("income_tax", 2024) first_simulation.calculate("income_tax", 2024) first_simulation.calculate("income_tax", 2024) - simulate(None).calculate("age", 2024, map_to="household") first_simulation.calculate("age", 2024, map_to="household") + reformed(unasked) + second_simulation = reformed(second) + simulate(None).calculate("age", 2024, map_to="household") + second_simulation.calculate("income_tax", 2024) requests = builder._record_post_export_request_descriptors("fixture", consumer) assert [(r.position, r.reformed_simulation, r.reform, r.key) for r in requests] == [ (0, None, None, ("age", 2024, "household")), (1, None, None, ("income_tax", 2025, None)), - (2, 1, second, ("income_tax", 2024, None)), - (3, 0, first, ("income_tax", 2024, None)), - (4, 0, first, ("age", 2024, "household")), + (2, 0, first, ("income_tax", 2024, None)), + (3, 0, first, ("age", 2024, "household")), + (4, 2, second, ("income_tax", 2024, None)), ] assert builder._record_post_export_requests(consumer) == ( (("age", 2024, "household"), ("income_tax", 2025, None)), From c18f4964134807ffe1ce431b14a75d68423abf81 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:47:42 +0400 Subject: [PATCH 12/13] Test that the dry run refuses a reformed simulation asked after the next opens The post-export scorer finishes a reformed simulation when the consumer opens the next one and refuses it any further key (#1726). A consumer that goes back to an earlier reformed simulation passes today's dry run and fails only in certification's scoring, after the export. The test expects the dry run to refuse it, for a key the simulation already asked and for a new one, and checks that the scorer refuses the same consumer. It fails on this commit: the dry run does not raise. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_requests.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) 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 44ca64e73c..066ce79948 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 @@ -322,6 +322,50 @@ def reformed(source): scorer.close() +@pytest.mark.parametrize( + "late_ask", + [("income_tax", 2024), ("age", 2024)], + ids=["a key it already asked", "a key it did not ask"], +) +def test_the_dry_run_refuses_a_reformed_simulation_asked_after_the_next_opens( + builder, fake_reforms, tmp_path, late_ask +) -> None: + """The scorer finishes a reformed simulation when the consumer opens the + next one and refuses it any further key, even one it already scored. The + dry run refuses the same consumer, so the release's plan fails before the + export instead of certification's scoring failing after it.""" + first = ParameterChangesReform({"gov.fixture.first": {"2024-01-01": 1}}) + second = ParameterChangesReform({"gov.fixture.second": {"2024-01-01": 2}}) + + def consumer(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + + def reformed(source): + return simulate( + source if records_only else build_post_export_reform(source) + ) + + first_simulation = reformed(first) + first_simulation.calculate("income_tax", 2024) + simulate(None).calculate("income_tax", 2024) + reformed(second).calculate("income_tax", 2024) + first_simulation.calculate(*late_ask) + + refusal = r"reformed simulation 0 for .* after opening reformed simulation 1\." + with pytest.raises(RuntimeError, match=refusal): + builder._record_post_export_request_descriptors("fixture", consumer) + with pytest.raises(RuntimeError, match=refusal): + builder._record_post_export_requests(consumer) + + scorer = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path) + try: + scoring = scorer.open_consumer("fixture", (("income_tax", 2024, None),)) + with pytest.raises(RuntimeError, match="asked a finished reform"): + consumer(scoring.simulate) + finally: + scorer.close() + + class _Unreducible: """A value whose pickling raises ``ValueError``, not ``PicklingError``.""" From 83080ce91d6b6f56ec5440c24d9c13ec438b14bc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:55:59 +0400 Subject: [PATCH 13/13] Refuse in the dry run a reformed simulation asked after the next opens The post-export scorer finishes a reformed simulation when the consumer opens the next one and refuses it any further key (#1726). The dry run's recorders now share its list of opened reforms, and a reformed simulation's recorder raises once a later one is open, so a consumer that goes back to an earlier reformed simulation fails the release's plan before the export instead of certification's scoring after it. No shipped consumer does; the recorded outputs' pinned digests are unchanged. The docs and changelog say so. Co-Authored-By: Claude Opus 5.5 --- ...s-post-export-request-descriptors.added.md | 2 +- docs/us-release-build-rule.md | 3 +++ tools/build_us_fiscal_refresh_release.py | 21 +++++++++++++++++-- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/changelog.d/us-post-export-request-descriptors.added.md b/changelog.d/us-post-export-request-descriptors.added.md index 0221f9ff14..aab943b296 100644 --- a/changelog.d/us-post-export-request-descriptors.added.md +++ b/changelog.d/us-post-export-request-descriptors.added.md @@ -1 +1 @@ -The US release tool's `_record_post_export_request_descriptors` returns every request each post-export stage makes in the engine-free post-export dry run as a picklable `PostExportRequest` (`microcosm.build.us_runtime.post_export_requests`), for later work that runs the requests in worker processes; the release itself still takes only the baseline plans and reform-pass counts. A descriptor holds the stage, the request's place in the order the serial scorer runs it, the variable, period and `map_to`, and for a reform request the description its reform is rebuilt from (the smoke probe, the reform-validation spec, or a cumulative OBBBA state's parameter changes) and which of the stage's reformed simulations asked for it. Reform validation, like the smoke check, now hands the dry run those descriptions instead of building reforms, so the dry run needs no policyengine-core, and it refuses a reform it cannot describe or pickle. The plan no longer builds reform-validation reform classes before the export, as it already did not for the smoke check. Nothing records the descriptors: the plan in `calibration_diagnostics.json`, each stage's output and each stage's reform-pass count stay the same, which a test pins on a fixture. `RECORDS_REQUESTS_ONLY` moves from `reform_coverage_smoke` to the new module. `tools/sweep_us_post_export_scoring.py` records through the descriptors and rebuilds each reform in the worker that scores it. +The US release tool's `_record_post_export_request_descriptors` returns every request each post-export stage makes in the engine-free post-export dry run as a picklable `PostExportRequest` (`microcosm.build.us_runtime.post_export_requests`), for later work that runs the requests in worker processes; the release itself still takes only the baseline plans and reform-pass counts. A descriptor holds the stage, the request's place in the order the serial scorer runs it, the variable, period and `map_to`, and for a reform request the description its reform is rebuilt from (the smoke probe, the reform-validation spec, or a cumulative OBBBA state's parameter changes) and which of the stage's reformed simulations asked for it. Reform validation, like the smoke check, now hands the dry run those descriptions instead of building reforms, so the dry run needs no policyengine-core, and it refuses a reform it cannot describe or pickle. It also refuses a key asked of a reformed simulation after the stage opened the next one, which the scorer refuses once it has finished that simulation, so such a stage fails the plan before the export rather than certification's scoring after it. The plan no longer builds reform-validation reform classes before the export, as it already did not for the smoke check. Nothing records the descriptors: the plan in `calibration_diagnostics.json`, each stage's output and each stage's reform-pass count stay the same, which a test pins on a fixture. `RECORDS_REQUESTS_ONLY` moves from `reform_coverage_smoke` to the new module. `tools/sweep_us_post_export_scoring.py` records through the descriptors and rebuilds each reform in the worker that scores it. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 701f98d429..764ec34243 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -457,6 +457,9 @@ one Microsimulation over the whole file. 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. - Each batch engine keeps policyengine-us's projection of the release year to diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index ede2e3c3cf..bcf5f18636 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -5273,18 +5273,33 @@ class _RecordingPostExportSimulation: ``asked`` is shared by every recorder of one dry run: it collects ``(simulation, key)`` in the order of first asks, where ``simulation`` is the reformed simulation's number, or ``None`` for the baseline. + ``reforms`` is the dry run's list of the reforms opened so far, also + shared, so a reformed simulation's recorder refuses every key once a later + one is opened, as the scorer refuses a finished ``_BatchedPostExportReform``. """ def __init__( self, asked: dict[tuple[int | None, PostExportKey], None], simulation: int | None, + reforms: Sequence[object], ) -> None: self._asked = asked self._simulation = simulation + self._reforms = reforms def calculate(self, variable, period=None, map_to=None) -> _PostExportValues: key = _post_export_key(variable, period, map_to) + latest = len(self._reforms) - 1 + if self._simulation is not None and self._simulation != latest: + raise RuntimeError( + f"A post-export consumer asked reformed simulation " + f"{self._simulation} for {key} after opening reformed simulation " + f"{latest}. The scorer finishes a reformed simulation when the " + "consumer opens the next one and refuses it further keys, so a " + "consumer asks each reformed simulation for all its keys before " + "opening the next." + ) self._asked.setdefault((self._simulation, key), None) return _PostExportValues(np.zeros(0), np.zeros(0)) @@ -5313,16 +5328,18 @@ def _dry_run_post_export_requests( state's parameter changes), and the dry run resolves no list edit against an engine. A reform given as anything else is refused (``check_post_export_reform``): a worker process could not rebuild it. + So is a key asked of a reformed simulation after the consumer opened the + next one, which the scorer refuses too (``_BatchedPostExportReform``). """ asked: dict[tuple[int | None, PostExportKey], None] = {} reforms: list[object] = [] def simulate(reform): if reform is None: - return _RecordingPostExportSimulation(asked, None) + return _RecordingPostExportSimulation(asked, None, reforms) check_post_export_reform(reform) reforms.append(reform) - return _RecordingPostExportSimulation(asked, len(reforms) - 1) + return _RecordingPostExportSimulation(asked, len(reforms) - 1, reforms) setattr(simulate, RECORDS_REQUESTS_ONLY, True) consumer(simulate)