diff --git a/changelog.d/1595-post-export-merged-baseline-pass.changed.md b/changelog.d/1595-post-export-merged-baseline-pass.changed.md new file mode 100644 index 0000000000..773c7ed112 --- /dev/null +++ b/changelog.d/1595-post-export-merged-baseline-pass.changed.md @@ -0,0 +1 @@ +US post-export scoring computes the baseline for all five post-export stages (the reform-coverage smoke, reform validation, demographics and the SSI/Social Security and Medicare IRMAA held-out reports) in one pass over the written H5's household batches, instead of one pass per stage: 177 batch engines instead of 885 on a national export. Each stage still receives only the keys its recorded plan holds, and the values are byte-identical. If the shared pass raises, every stage runs its own pass as before. Reform validation scores the pre-OBBBA state once for both OBBBA groups (income tax and estate tax in 2026), so its recorded `reform_passes` and `reform_systems` in the manifests' `post_export_scoring` block drop from 54 to 53 while `reform_validation.json` is unchanged; `tools/probe_us_post_export.py`'s plan comparison against a release built before this change therefore reports reform validation's 53 against 54. The guard sweep tool's baseline worker uses the shared pass too (microcosm#1595). diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 764ec34243..8e3508ac68 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -443,17 +443,43 @@ one Microsimulation over the whole file. (`US_RELEASE_SPM_SELECTION`, county geography) and is released before the next batch builds. - 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. + dry run. The scorer computes every stage's recorded keys together in one + pass over the batches, in ascending period order, and gives each stage only + the keys it recorded (microcosm#1595). Before, each of the five stages (the + smoke, reform validation, demographics and the two held-out reports) ran a + pass of its own: five passes over 177 batches on a national export. If the + shared pass raises, every stage runs its own pass as before, so a key that + only one held-out report asks for still fails that report alone. Each + stage's recorded `baseline_passes` stays 1: the one pass its baseline came + from, shared unless the shared pass failed. Only the build log tells the two + apart: it prints `Post-export merged baseline plan failed` on a fallback, + and the summary that reform validation, demographics and the held-out + reports print says `baseline served from the merged pass` when the stage was + served from the shared one. One engine refuses a period earlier than one it has already computed. 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 shared pass holds every stage's baseline arrays at once, from the + first stage's start until each stage has been served. On the + eight-household fixture that is 12,027 bytes, against 8,418 for reform + validation's plan, the largest one held before (about 1.4 times). Each of + its batch engines also computes every stage's keys (97 on the fixture, + against at most 75 before), so it caches more intermediate values. + - The shared pass runs when the first stage starts: the smoke, unless + `--skip-reform-coverage-smoke` is set. The build telemetry's time for that + stage now includes every stage's baseline work, and the later stages' + times include none. + - A shared pass that fails costs the time it ran in addition to every + stage's own pass. - `_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 + plans and reform-pass counts. A `prefetch` of several keys of one reformed + simulation is one pass, and its keys follow in ascending period order, as + the scorer computes them. A reform request holds 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. @@ -470,9 +496,14 @@ one Microsimulation over the whole file. `_dataset_from_frame(..., period_only=True)`. By default it keeps the projection, so a new caller that reads a later year gets the engine's own projected inputs. -- Each reform builds one tax-benefit system and scores its measure batch by - batch. Each batch engine gets that system alone, without `reform=`: given - both, policyengine-us creates a baseline branch, which clones the system. +- Each reform builds one tax-benefit system and scores its measures batch by + batch: one pass per measure, or one pass for the measures a stage asks for + together (`prefetch`). Reform validation asks the pre-OBBBA state (every + OBBBA provision reverted) for both OBBBA groups' starting totals, income tax + and estate tax in 2026, together, so that state costs one pass instead of + two (microcosm#1595). Each batch engine gets that system alone, without + `reform=`: given both, policyengine-us creates a baseline branch, which + clones the system. - Every statistic reads full-length values with their engine weights. The totals equal a whole-file simulation's up to floating-point summation order @@ -497,8 +528,11 @@ known violations at run time: Tests pin the watched lists against the installed engine's formula sources, exercise each guard on a real engine, and compare the shipped baseline plans -(18 smoke keys, 75 validation keys and 1 demographics key) against whole-file -values on a small written H5 in three batches. +(20 smoke keys, 75 validation keys and 1 demographics key), served from the +shared pass, against whole-file values on a small written H5 in three +batches. On the same H5 another test checks that the shared baseline pass and +the shared pre-OBBBA pass give the same bytes (values, weights and dtypes) as +separate passes. On 2026-09-24, the sweep below completed on a written fixture containing eight households across five states, with Medicaid enrollees, under policyengine-us @@ -522,13 +556,20 @@ records the shipped consumers' requests, including every out-of-sample validation reform and the OBBBA pre-baseline and stacked states. It also exercises the fallback simulations used when an in-sample estimate is absent. It scores at most four reform passes per worker, serially, and compares all -baseline values and four reform passes with whole-file engines. Workers stop +baseline values and four reform passes with whole-file engines. Its baseline +worker serves its three plans (the smoke, reform validation recorded without a +calibration fit, and demographics) from one shared pass; the release's shared +pass also holds the two held-out reports' keys. Its reform workers score each +recorded request in a pass of its own, so the pre-OBBBA state's two requests +are two passes there. Workers stop at a sampled 7 GiB RSS threshold and report their peak RSS, elapsed time, counts and the scored H5 digest. Run this fixture sweep before R4's full-export timing steps, and repeat it after a probe, spec or engine-lock change before starting a release. R4's existing full-export rehearsal times the smoke and validation -baseline plans plus three selected reform passes; it does not cover every +baseline plans plus three selected reform passes (`tools/probe_us_post_export.py` +still scores each stage's baseline plan in a pass of its own, which the release +no longer does); it does not cover every reform and does not replace this sweep. `calibration_diagnostics.json` records the plan under `build.post_export_scoring` 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 3e06147e68..31eed194a1 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 @@ -716,6 +716,13 @@ def simulate(reform: Any) -> Any: return simulate +def _request_period(request: tuple[str, int]) -> int: + """The period of a ``(measure, period)`` weighted-total request.""" + + measure, at_period = request + return at_period + + def reform_validation_payload( specs: Sequence[ReformValidationSpec], *, @@ -786,22 +793,44 @@ def simulation_for_parameter_changes(changes: dict[str, Any]) -> Any: 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 - ) -> float: - """Weighted total of a single-use reform simulation, then release it. + def released_weighted_totals( + transient_simulation: Any, requests: tuple[tuple[str, int], ...] + ) -> dict[tuple[str, int], float]: + """Weighted totals of a single-use reform simulation, then release it. + + ``requests`` are ``(measure, period)`` pairs, read in ascending period + order: policyengine-us 2.2.1 can fail to compute an earlier period + after a later one on the same simulation (microcosm#956). A simulation + offering ``prefetch`` (the release tool's household-batched reform) + scores them all in one pass before any total is read. microcosm#456: every out-of-sample score builds a full-release-sized engine simulation whose object graph stays reachable after the local name dies (system backref, branch-clone cycles). Release it and sweep so the smoke phase runs at one-simulation footprint. """ + ascending = tuple(sorted(dict.fromkeys(requests), key=_request_period)) try: - return _weighted_total(transient_simulation, measure, at_period) + prefetch = getattr(transient_simulation, "prefetch", None) + if prefetch is not None: + prefetch(ascending) + return { + (measure, at_period): _weighted_total( + transient_simulation, measure, at_period + ) + for measure, at_period in ascending + } finally: if _released_engine_state(transient_simulation): gc.collect() + def released_weighted_total( + transient_simulation: Any, measure: str, at_period: int + ) -> float: + """One weighted total of a single-use reform simulation, then release it.""" + request = (measure, at_period) + return released_weighted_totals(transient_simulation, (request,))[request] + def stacked_obbba_effects() -> dict[str, tuple[float, float, float]]: """Score the OBBBA provisions *stacked* in their JCX-35-25 order. @@ -824,21 +853,23 @@ def stacked_obbba_effects() -> dict[str, tuple[float, float, float]]: group reduces to enacting that provision alone). The pre-OBBBA baseline always merges every provision's revert, so each group is scored in the context of the whole bill; measures are disjoint taxes, so cross-group - interactions are nil by construction. + interactions are nil by construction. Every group therefore starts + from the same state, which one simulation scores for all groups. """ if simulate is None or not obbba_specs: return {} groups: dict[tuple[str, int], list[ReformValidationSpec]] = {} for spec in obbba_specs: groups.setdefault((spec.budget_measure, spec.period), []).append(spec) + # state 0: pre-OBBBA (every provision reverted, across all groups), + # each group's (measure, period) read from one simulation. + state_zero_totals = released_weighted_totals( + simulation_for_parameter_changes(obbba_pre_baseline_changes), + tuple(groups), + ) effects: dict[str, tuple[float, float, float]] = {} for (measure, period), group in groups.items(): - # state 0: pre-OBBBA (every provision reverted, across all groups). - prev_total = released_weighted_total( - simulation_for_parameter_changes(obbba_pre_baseline_changes), - measure, - period, - ) + prev_total = state_zero_totals[(measure, period)] enacted: set[str] = set() for spec in group: # Enacting a provision means dropping its repeal from the diff --git a/packages/microcosm-build/tests/engine_free/shared/test_reform_validation.py b/packages/microcosm-build/tests/engine_free/shared/test_reform_validation.py index efb80477f1..a8c576ccd8 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_reform_validation.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_reform_validation.py @@ -287,6 +287,120 @@ def simulate(reform): assert rows["obbba_estate"]["microcosm"]["budget_effect"] == pytest.approx(-20.0) +def test_obbba_pre_baseline_state_is_one_simulation_for_every_group(monkeypatch): + # Every group stacks from the same pre-OBBBA state, so that state is + # simulated once. A simulation offering ``prefetch`` (the release tool's + # batched reform) gets every group's (measure, period) in one call before + # any total is read, so the release scores the state in one pass. + def spec(id_, path, measure): + return ReformValidationSpec( + id=id_, + name=id_, + category="OBBBA", + in_sample=False, + period=2026, + jct_score=-1.0, + jct_window="FY2026", + jct_source="JCX", + jct_source_url="", + parameter_changes={path: {"2026-01-01.2026-12-31": 0}}, + effect_direction="baseline_minus_reform", + budget_measure=measure, + ) + + specs = ( + spec("obbba_a", "gov.example.a", "income_tax"), + spec("obbba_b", "gov.example.b", "income_tax"), + spec("obbba_estate", "gov.example.estate", "estate_tax"), + ) + monkeypatch.setattr( + reform_validation_module, + "_build_parameter_reform", + lambda changes: frozenset(changes), + ) + pre_obbba = frozenset({"gov.example.a", "gov.example.b", "gov.example.estate"}) + totals = { + pre_obbba: {"income_tax": 1_000.0, "estate_tax": 50.0}, + frozenset({"gov.example.b", "gov.example.estate"}): {"income_tax": 900.0}, + frozenset({"gov.example.estate"}): {"income_tax": 960.0}, + frozenset({"gov.example.a", "gov.example.b"}): {"estate_tax": 30.0}, + } + simulated = [] + prefetched = [] + + class _PrefetchingSim(_FakeSim): + def __init__(self, reform) -> None: + super().__init__(totals[reform]) + self._reform = reform + self._read = [] + + def prefetch(self, requests): + assert not self._read + prefetched.append((self._reform, tuple(requests))) + + def calculate(self, measure, period): + self._read.append(measure) + return super().calculate(measure, period) + + def simulate(reform): + simulated.append(reform) + return _PrefetchingSim(reform) + + payload = reform_validation_payload(specs, period=2026, simulate=simulate) + assert simulated.count(pre_obbba) == 1 + assert [requests for reform, requests in prefetched if reform == pre_obbba] == [ + (("income_tax", 2026), ("estate_tax", 2026)) + ] + rows = {row["id"]: row for row in payload["reforms"]} + assert rows["obbba_a"]["microcosm"]["baseline_total"] == pytest.approx(1_000.0) + assert rows["obbba_b"]["microcosm"]["budget_effect"] == pytest.approx(60.0) + assert rows["obbba_estate"]["microcosm"]["baseline_total"] == pytest.approx(50.0) + assert rows["obbba_estate"]["microcosm"]["budget_effect"] == pytest.approx(-20.0) + + +def test_obbba_pre_baseline_state_reads_its_groups_in_ascending_period(monkeypatch): + # One simulation answers every group's starting total. A later group + # listed first is still read after the earlier one, since policyengine-us + # 2.2.1 can fail to compute an earlier period after a later one. + def spec(id_, path, period): + return ReformValidationSpec( + id=id_, + name=id_, + category="OBBBA", + in_sample=False, + period=period, + jct_score=-1.0, + jct_window="FY2026", + jct_source="JCX", + jct_source_url="", + parameter_changes={path: {"2026-01-01.2027-12-31": 0}}, + effect_direction="baseline_minus_reform", + ) + + specs = ( + spec("obbba_late", "gov.example.late", 2027), + spec("obbba_early", "gov.example.early", 2026), + ) + monkeypatch.setattr( + reform_validation_module, + "_build_parameter_reform", + lambda changes: frozenset(changes), + ) + pre_obbba = frozenset({"gov.example.late", "gov.example.early"}) + read_periods = {} + + class _PeriodRecordingSim: + def __init__(self, reform) -> None: + self._reform = reform + + def calculate(self, measure, period): + read_periods.setdefault(self._reform, []).append(period) + return _FakeSeries(1_000.0 if self._reform == pre_obbba else 900.0) + + reform_validation_payload(specs, period=2026, simulate=_PeriodRecordingSim) + assert read_periods[pre_obbba] == [2026, 2027] + + def test_obbba_stacked_scoring_releases_intermediate_simulations(monkeypatch): specs = tuple( ReformValidationSpec( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index 5611c05447..200647fab5 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -7272,7 +7272,12 @@ def calculate(variable, period): def simulate(reform): return SimpleNamespace(calculate=calculate) - return SimpleNamespace(name=name, simulate=simulate, record=lambda: record) + return SimpleNamespace( + name=name, + simulate=simulate, + record=lambda: record, + baseline_from_merged_pass=False, + ) def finish_consumer(self, scoring): captured.setdefault("finished_consumers", []).append(scoring.name) 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 066ce79948..41335cb7a0 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 @@ -11,6 +11,8 @@ - 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; +- a ``prefetch`` of several keys is one reform pass, and its keys not asked + before follow in ascending period order, as the scorer computes them; - every descriptor survives a pickle round trip through a spawned process; - the dry run refuses a reform it cannot describe or pickle; - descriptors cannot be hashed and keep their own copy of a reform's @@ -87,6 +89,11 @@ def test_the_dry_run_returns_every_request_as_a_descriptor(builder, no_engine) - period=builder.PERIOD )[:2] } + obbba_groups = { + (spec.budget_measure, spec.period) + for spec in specs + if reform_validation_module._is_obbba_spec(spec) + } recorded: dict[str, tuple[PostExportRequest, ...]] = {} for name, consumer in _shipped_consumers(builder).items(): requests = builder._record_post_export_request_descriptors(name, consumer) @@ -103,7 +110,13 @@ def test_the_dry_run_returns_every_request_as_a_descriptor(builder, no_engine) - # run's. plan, passes = builder._record_post_export_requests(consumer) assert tuple(request.key for request in baseline) == plan - assert len(reformed) == passes + # One pass per reform request, except reform validation's pre-OBBBA + # state: one prefetch reads it for every OBBBA group in one pass + # (microcosm#1595). + shared_pass_requests = ( + len(obbba_groups) - 1 if name == "reform_validation" else 0 + ) + assert len(reformed) == passes + shared_pass_requests recorded[name] = requests assert list(recorded) == [ "reform_coverage_smoke", @@ -148,7 +161,7 @@ def test_the_dry_run_returns_every_request_as_a_descriptor(builder, no_engine) - 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 + # OBBBA: every (measure, period) group reads 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 = [ @@ -167,8 +180,20 @@ def test_the_dry_run_returns_every_request_as_a_descriptor(builder, no_engine) - (spec.budget_measure, spec.period) for spec in obbba ) ] - assert len({request.reformed_simulation for request in validation}) == len( - validation + # One reformed simulation per request, except the pre-OBBBA state: every + # group's key comes from one simulation of it (microcosm#1595). + assert ( + len( + { + request.reformed_simulation + for request in states + if request.reform == pre_obbba + } + ) + == 1 + ) + assert len({request.reformed_simulation for request in validation}) == ( + len(validation) - len(groups) + 1 ) for name in ( @@ -366,6 +391,71 @@ def reformed(source): scorer.close() +def _prefetching_consumer(*, prefetch_after_the_next_opens: bool): + """A consumer that asks its first reformed simulation for one key, then + prefetches three (one asked already, two new in descending period order), + prefetches an asked key again, and asks a second reformed simulation for + one key; optionally it then prefetches from the first again.""" + 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", 2026) + first_simulation.prefetch( + (("estate_tax", 2027), ("income_tax", 2026), ("estate_tax", 2026)) + ) + first_simulation.prefetch((("estate_tax", 2027),)) + reformed(second).calculate("income_tax", 2026) + if prefetch_after_the_next_opens: + first_simulation.prefetch((("income_tax", 2027),)) + + return consumer, first, second + + +def test_a_prefetch_is_one_pass_with_its_new_keys_in_ascending_period_order( + builder, fake_reforms, tmp_path +) -> None: + """``_BatchedPostExportReform.prefetch`` scores the keys a reformed + simulation was not asked before in one pass, in ascending period order. + The dry run records those keys in that order, counts that prefetch as one + pass and a prefetch of asked keys as none, and refuses a prefetch of a + reformed simulation once the next one has opened, as the scorer does.""" + consumer, first, second = _prefetching_consumer(prefetch_after_the_next_opens=False) + requests = builder._record_post_export_request_descriptors("fixture", consumer) + assert [(r.position, r.reformed_simulation, r.reform, r.key) for r in requests] == [ + (0, 0, first, ("income_tax", 2026, None)), + (1, 0, first, ("estate_tax", 2026, None)), + (2, 0, first, ("estate_tax", 2027, None)), + (3, 1, second, ("income_tax", 2026, None)), + ] + assert builder._record_post_export_requests(consumer) == ((), 3) + + late_consumer, _, _ = _prefetching_consumer(prefetch_after_the_next_opens=True) + refusal = r"reformed simulation 0 for .* after opening reformed simulation 1\." + with pytest.raises(RuntimeError, match=refusal): + builder._record_post_export_request_descriptors("fixture", late_consumer) + + scorer = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path) + try: + scoring = scorer.open_consumer("fixture", (), planned_reform_passes=3) + consumer(scoring.simulate) + assert scoring.record()["reform_passes"] == 3 + scorer.finish_consumer(scoring) + late_scoring = scorer.open_consumer("late fixture", ()) + with pytest.raises(RuntimeError, match="asked a finished reform"): + late_consumer(late_scoring.simulate) + finally: + scorer.close() + + class _Unreducible: """A value whose pickling raises ``ValueError``, not ``PicklingError``.""" @@ -612,10 +702,13 @@ def test_the_reform_alias_names_the_three_descriptions() -> 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. +#: reads them), on the same fixture; as on origin/main at fcabe4e65, except +#: reform validation's: it scores the pre-OBBBA state once for both OBBBA +#: groups (microcosm#1595), so it counts 63 passes, one fewer, for the same +#: 64 reform requests. _PLANNED_REFORM_PASSES = { "reform_coverage_smoke": 43, - "reform_validation": 64, + "reform_validation": 63, "demographics": 0, "ssi_social_security_holdout": 0, "medicare_irmaa_holdout": 0, 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 e6ef80678c..55e051a1e4 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 @@ -5,8 +5,10 @@ from collections.abc import Iterator from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, ParameterChangesReform, PostExportRequest, + build_post_export_reform, ) from microcosm.calibrate import DroppedConstraintMatrix from test_support.microcosm_build.us_post_export_scoring import * @@ -1714,6 +1716,52 @@ def test_guard_sweep_records_and_scores_shipped_reform_passes( scorer.close() +def test_guard_sweep_baseline_worker_scores_its_plans_in_one_pass( + builder, fake_reforms, monkeypatch, tmp_path +) -> None: + """The guard sweep's baseline worker registers the plans it recorded, so + its scorer serves them from one merged pass, as the release does, and + compares each consumer's served values with a whole-file engine.""" + sweep = _load_sweep_module() + frame, log = _nested_frame(), _EngineLog() + opened: list[dict[str, object]] = [] + scorer_cls = builder._HouseholdBatchedPostExportScorer + + def fake_engine_scorer(dataset_path, **options): + opened.append(options) + return scorer_cls( + dataset_path, + **options, + microsimulation_cls=_fake_engine(log), + dataset_from_frame=lambda batch_frame: batch_frame, + load_frame=lambda path, *, expected_sha256: frame, + ) + + monkeypatch.setattr(sweep, "_load_builder", lambda: builder) + monkeypatch.setattr(sweep, "_watch_worker_rss", lambda: None) + monkeypatch.setattr( + builder, "_HouseholdBatchedPostExportScorer", fake_engine_scorer + ) + monkeypatch.setattr( + reform_validation_module, + "default_simulate_factory", + lambda path: _unbatched_simulate(frame, _EngineLog()), + ) + plans, _, _ = sweep._record_requests(builder) + report = sweep._worker( + SimpleNamespace( + dataset_path=_written_h5(tmp_path), + batch_size=3, + worker_start=None, + reforms_per_worker=4, + ) + ) + assert [options["baseline_plans"] for options in opened] == [plans] + assert report["n_batches"] == 3 + assert len(log.constructions) == 3 + assert all(engine.tax_benefit_system is None for engine in log.constructions) + + def test_guard_sweep_runs_every_chunk_and_propagates_worker_failure(tmp_path) -> None: import subprocess @@ -2009,6 +2057,460 @@ def recording_dataset_from_frame(frame, **kwargs): assert calls == [{"assert_no_formula_owned_columns": False}] +# --------------------------------------------------------------------------- +# One merged baseline pass for the planned consumers (microcosm#1595) +# --------------------------------------------------------------------------- + + +def _release_plan(builder, fit=None): + """The plan and consumers ``_main`` records for the nested frame.""" + fit = _full_in_sample_fit(builder.PERIOD) if fit is None else fit + args = _plan_args() + plan = builder._record_post_export_scoring_plan( + args, n_households=7, result=fit, release_id="fixture-release" + ) + assert plan.error is None + consumers = builder._post_export_consumers( + args, result=fit, release_id="fixture-release" + ) + return plan, consumers + + +def _baseline_constructions(log): + return [engine for engine in log.constructions if engine.tax_benefit_system is None] + + +def _union_plan(builder, plans): + return builder._ascending_period_plan( + key for plan in plans.values() for key in plan + ) + + +def test_registered_plans_share_one_baseline_pass_with_unchanged_outputs( + builder, fake_reforms, tmp_path +) -> None: + """The five planned consumers' baselines cost one batch-outer pass over + the union of their plans, in ascending period order, instead of one pass + each. Every output, every served baseline array (byte for byte) and the + manifests' block equal those of the separate passes.""" + plan, consumers = _release_plan(builder) + assert list(consumers) == [ + "reform_coverage_smoke", + "reform_validation", + "demographics", + "ssi_social_security_holdout", + "medicare_irmaa_holdout", + ] + frame = _nested_frame() + separate_log, merged_log = _EngineLog(), _EngineLog() + separate = _scorer(builder, frame, separate_log, 3, tmp_path / "separate") + merged = _scorer( + builder, + frame, + merged_log, + 3, + tmp_path / "merged", + baseline_plans=plan.baseline_plans, + ) + expected_outputs, expected_served = _run_planned_consumers( + separate, plan, consumers + ) + outputs, served = _run_planned_consumers(merged, plan, consumers) + + assert {name: _comparable_output(output) for name, output in outputs.items()} == { + name: _comparable_output(output) for name, output in expected_outputs.items() + } + for name, expected_values in expected_served.items(): + assert list(served[name]) == list(plan.baseline_plan(name)), name + assert list(expected_values) == list(plan.baseline_plan(name)), name + for key, values in expected_values.items(): + assert _same_bytes(served[name][key], values), (name, key) + block = merged.manifest_record() + assert block == separate.manifest_record() + assert { + name: record["baseline_passes"] for name, record in block["consumers"].items() + } == {name: 1 for name in consumers} + + union = _union_plan(builder, plan.baseline_plans) + assert len(union) < sum(len(keys) for keys in plan.baseline_plans.values()) + assert len(_baseline_constructions(separate_log)) == 5 * separate.n_batches + merged_baseline = _baseline_constructions(merged_log) + assert len(merged_baseline) == merged.n_batches == 3 + assert all( + engine.periods == [key[1] for key in union] for engine in merged_baseline + ) + + +def test_open_post_export_scorer_registers_the_recorded_plans( + builder, fake_reforms, engine_free_loader, tmp_path +) -> None: + """``_main``'s scorer serves the plan it recorded from one pass: opening + the first consumer scores every planned consumer's baseline keys.""" + log, _ = engine_free_loader + plan, _ = _release_plan(builder) + scorer = builder._open_post_export_scorer(plan, _written_h5(tmp_path)) + scorer.open_consumer("demographics", plan.baseline_plan("demographics")) + union = _union_plan(builder, plan.baseline_plans) + assert [len(engine.household_ids) for engine in log.constructions] == [3, 3, 1] + assert all( + engine.periods == [key[1] for key in union] for engine in log.constructions + ) + scorer.close() + + +def test_a_registered_consumer_is_served_only_its_own_plan( + builder, fake_reforms, tmp_path +) -> None: + """The merged pass scores keys other consumers planned; a consumer's + served baseline still refuses every key outside its own plan.""" + plan, _ = _release_plan(builder) + scorer = _scorer( + builder, + _nested_frame(), + _EngineLog(), + 3, + tmp_path, + baseline_plans=plan.baseline_plans, + ) + key = ("income_tax", 2024, None) + assert key in plan.baseline_plan("reform_coverage_smoke") + assert key not in plan.baseline_plan("demographics") + smoke = scorer.open_consumer( + "reform_coverage_smoke", plan.baseline_plan("reform_coverage_smoke") + ) + demographics = scorer.open_consumer( + "demographics", plan.baseline_plan("demographics") + ) + assert smoke.simulate(None).calculate("income_tax", 2024).sum() != 0.0 + with pytest.raises(RuntimeError, match="which its recorded plan does not hold"): + demographics.simulate(None).calculate("income_tax", 2024) + # The served baseline's prefetch, which the dry run's recorder also + # offers, refuses the same key and accepts the consumer's own. + with pytest.raises(RuntimeError, match="which its recorded plan does not hold"): + demographics.simulate(None).prefetch((("income_tax", 2024),)) + demographics.simulate(None).prefetch((("age", 2024),)) + + +def test_a_registered_consumer_opened_with_another_plan_is_refused( + builder, tmp_path +) -> None: + """A consumer is refused a plan other than its recorded one, including an + empty recorded plan, and still after the merged pass has failed.""" + plans = { + "demographics": (("age", 2024, None),), + "ssi_social_security_holdout": (("ssi", 2024, None),), + "nothing planned": (), + } + log = _EngineLog() + scorer = _scorer(builder, _nested_frame(), log, 3, tmp_path, baseline_plans=plans) + refused = "demographics: .* registered baseline plan" + with pytest.raises(ValueError, match=refused): + scorer.open_consumer("demographics", (("age", 2024, None), ("ssi", 2024, None))) + with pytest.raises(ValueError, match=refused): + scorer.open_consumer("demographics", ()) + with pytest.raises( + ValueError, match="nothing planned: .* registered baseline plan" + ): + scorer.open_consumer("nothing planned", (("age", 2024, None),)) + assert log.constructions == [] + assert scorer.open_consumer("nothing planned", ())._baseline == {} + + log.fail_on = "ssi" + with pytest.raises(RuntimeError, match="fixture engine refuses ssi"): + scorer.open_consumer( + "ssi_social_security_holdout", plans["ssi_social_security_holdout"] + ) + with pytest.raises(ValueError, match=refused): + scorer.open_consumer("demographics", (("age", 2024, None), ("ssi", 2024, None))) + + +def test_the_merged_baseline_holds_only_keys_an_unserved_consumer_needs( + builder, tmp_path +) -> None: + """Each served consumer's keys are dropped from the scorer once no + consumer still to be served planned them, so the merged values are freed + as the consumers finish. A consumer opened again scores its own plan.""" + tax_2024 = ("income_tax", 2024, None) + snap_2024 = ("snap", 2024, None) + tax_2025 = ("income_tax", 2025, None) + plans = { + "first": (tax_2024, snap_2024), + "second": (snap_2024, tax_2025), + "third": (tax_2025,), + } + log = _EngineLog() + scorer = _scorer(builder, _nested_frame(), log, 3, tmp_path, baseline_plans=plans) + scorer.open_consumer("first", plans["first"]) + assert set(scorer._merged_baseline) == {snap_2024, tax_2025} + scorer.open_consumer("second", plans["second"]) + assert set(scorer._merged_baseline) == {tax_2025} + third = scorer.open_consumer("third", plans["third"]) + assert not scorer._merged_baseline + assert len(log.constructions) == scorer.n_batches + assert all(engine.periods == [2024, 2024, 2025] for engine in log.constructions) + assert third.simulate(None).calculate("income_tax", 2025).sum() != 0.0 + + scorer.open_consumer("first", plans["first"]) + assert len(log.constructions) == 2 * scorer.n_batches + assert all( + engine.periods == [2024, 2024] + for engine in log.constructions[scorer.n_batches :] + ) + + +def test_a_failed_merged_pass_falls_back_to_each_consumers_own_pass( + builder, fake_reforms, tmp_path, capsys +) -> None: + """A key that fails the merged pass costs no other consumer its + baseline: each consumer then scores its own plan, as before the merge, + so only the holdout that planned the failing key fails, with the error + it raised before.""" + plan, consumers = _release_plan(builder) + failing = "medicare_enrolled" + assert [ + name + for name, keys in plan.baseline_plans.items() + if any(key[0] == failing for key in keys) + ] == ["medicare_irmaa_holdout"] + + def run(scorer): + outputs, errors = {}, {} + for name, consumer in consumers.items(): + try: + scoring = scorer.open_consumer( + name, + plan.baseline_plan(name), + planned_reform_passes=plan.planned_reform_passes(name), + ) + except RuntimeError as error: + errors[name] = str(error) + continue + outputs[name] = _comparable_output(consumer(scoring.simulate)) + scorer.finish_consumer(scoring) + return outputs, errors + + frame = _nested_frame() + separate_log, merged_log = _EngineLog(), _EngineLog() + separate_log.fail_on = merged_log.fail_on = failing + separate = _scorer(builder, frame, separate_log, 3, tmp_path / "separate") + merged = _scorer( + builder, + frame, + merged_log, + 3, + tmp_path / "merged", + baseline_plans=plan.baseline_plans, + ) + expected = run(separate) + capsys.readouterr() + observed = run(merged) + + assert observed == expected + assert expected[1] == { + "medicare_irmaa_holdout": "fixture engine refuses medicare_enrolled" + } + assert merged.manifest_record() == separate.manifest_record() + # The merged pass stopped in its first batch engine, which was released; + # every consumer then ran the passes it ran before. + assert len(_baseline_constructions(merged_log)) == ( + len(_baseline_constructions(separate_log)) + 1 + ) + assert all(engine.dataset is None for engine in merged_log.constructions) + assert "merged baseline plan failed" in capsys.readouterr().out + + +def test_a_failed_merged_pass_frees_its_partial_values_before_the_fallback( + builder, tmp_path +) -> None: + """The fallback pass starts only after the failed merged pass's frame, + and the per-batch values it had collected, are released, including + values held in a reference cycle, which only a full collection frees.""" + import weakref + + plans = {"first": (("age", 2024, None),), "second": (("ssi", 2024, None),)} + scorer = _scorer( + builder, _nested_frame(), _EngineLog(), 3, tmp_path, baseline_plans=plans + ) + partial_values: list[weakref.ref] = [] + score = scorer._score + + class _PartialValues: + pass + + def failing_merged_score(keys, **options): + if options["label"] == "merged baseline plan": + collected = _PartialValues() + collected.cycle = collected + partial_values.append(weakref.ref(collected)) + raise RuntimeError("the merged pass failed in its last batch") + assert partial_values and partial_values[0]() is None, ( + "the failed merged pass's values are still alive" + ) + return score(keys, **options) + + scorer._score = failing_merged_score + first = scorer.open_consumer("first", plans["first"]) + assert first.simulate(None).calculate("age", 2024).sum() > 0.0 + + +def test_a_merged_pass_error_that_cannot_be_printed_still_falls_back( + builder, tmp_path, capsys +) -> None: + """The fallback holds when the merged pass's error cannot be turned into + text: the consumer scores its own plan, and the merged pass is not tried + again for the next consumer.""" + plans = {"first": (("age", 2024, None),), "second": (("ssi", 2024, None),)} + scorer = _scorer( + builder, _nested_frame(), _EngineLog(), 3, tmp_path, baseline_plans=plans + ) + score = scorer._score + + class _UnprintableError(RuntimeError): + def __str__(self) -> str: + raise ValueError("this error has no text") + + def failing_merged_score(keys, **options): + if options["label"] == "merged baseline plan": + raise _UnprintableError() + return score(keys, **options) + + scorer._score = failing_merged_score + passes = _record_pass_labels(scorer) + first = scorer.open_consumer("first", plans["first"]) + second = scorer.open_consumer("second", plans["second"]) + assert first.simulate(None).calculate("age", 2024).sum() > 0.0 + assert second.simulate(None).calculate("ssi", 2024).sum() > 0.0 + assert passes == [ + "merged baseline plan", + "first baseline plan", + "second baseline plan", + ] + assert "_UnprintableError" in capsys.readouterr().out + + +def test_the_consumer_log_names_the_merged_pass(builder, tmp_path, capsys) -> None: + """A consumer served from the merged pass says so in the build log; its + recorded ``baseline_passes`` stays 1.""" + plans = {"demographics": (("age", 2024, None),)} + scorer = _scorer( + builder, _nested_frame(), _EngineLog(), 3, tmp_path, baseline_plans=plans + ) + for name in ("demographics", "unregistered"): + builder._score_post_export_consumer( + name, + lambda simulate: simulate(None).calculate("age", 2024).sum(), + dataset_path=scorer.dataset_path, + post_export_scorer=scorer, + baseline_plan=plans["demographics"], + maximum_microsim_batch_size=3, + ) + log = capsys.readouterr().out + assert ( + "Post-export demographics: baseline served from the merged pass (1 keys)" in log + ) + assert "Post-export unregistered: 1 baseline pass (1 keys)" in log + assert { + name: record["baseline_passes"] + for name, record in scorer.consumer_records.items() + } == {"demographics": 1, "unregistered": 1} + + +# --------------------------------------------------------------------------- +# Several keys of one reformed simulation in one pass (microcosm#1595) +# --------------------------------------------------------------------------- + + +def test_a_prefetched_reform_scores_its_keys_in_one_pass( + builder, fake_reforms, tmp_path +) -> None: + """``prefetch`` scores every key a reformed simulation has not scored in + one batch-outer pass, in ascending period order. The dry run counts that + pass once, a later ``calculate`` of a prefetched key costs no pass, and + the totals equal those of one pass per key.""" + description = ParameterChangesReform({"gov.fixture.two_keys": {"2026-01-01": 1}}) + reform = build_post_export_reform(description) + + def consumer(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + reformed = simulate(description if records_only else reform) + reformed.prefetch((("income_tax", 2027), ("estate_tax", 2026))) + reformed.prefetch((("estate_tax", 2026),)) + return ( + reformed.calculate("estate_tax", 2026).sum(), + reformed.calculate("income_tax", 2027).sum(), + ) + + plan, passes = builder._record_post_export_requests(consumer) + assert (plan, passes) == ((), 1) + log = _EngineLog() + scorer = _scorer(builder, _nested_frame(), log, 3, tmp_path / "together") + scoring = scorer.open_consumer("two keys", plan, planned_reform_passes=passes) + together = consumer(scoring.simulate) + record = scoring.record() + assert (record["reform_passes"], record["reform_systems"]) == (1, 1) + assert len(log.constructions) == scorer.n_batches + assert all(engine.periods == [2026, 2027] for engine in log.constructions) + + alone = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path / "alone") + one_key_each = alone.open_consumer("one key each", ()) + assert together == ( + one_key_each.simulate(reform).calculate("estate_tax", 2026).sum(), + one_key_each.simulate(reform).calculate("income_tax", 2027).sum(), + ) + assert one_key_each.record()["reform_passes"] == 2 + + +def test_reform_validation_scores_the_pre_obbba_state_in_one_pass( + builder, fake_reforms, tmp_path +) -> None: + """Every OBBBA group stacks from the same pre-OBBBA state (every + provision reverted), so the release scores that state once: one reform + system and one pass for both groups' (measure, period) keys. With a + release fit, reform validation runs 53 reform passes, as its dry run + counts, instead of 54.""" + plan, consumers = _release_plan(builder) + specs = reform_validation_module.load_default_reform_specs(period=builder.PERIOD) + obbba = [spec for spec in specs if reform_validation_module._is_obbba_spec(spec)] + pre_obbba = json.dumps( + reform_validation_module._merged_parameter_changes(obbba), + sort_keys=True, + default=str, + ) + assert {(spec.budget_measure, spec.period) for spec in obbba} == { + ("income_tax", 2026), + ("estate_tax", 2026), + } + log = _EngineLog() + scorer = _scorer( + builder, + _nested_frame(), + log, + 3, + tmp_path, + baseline_plans=plan.baseline_plans, + ) + scoring = scorer.open_consumer( + "reform_validation", + plan.baseline_plan("reform_validation"), + planned_reform_passes=plan.planned_reform_passes("reform_validation"), + ) + consumers["reform_validation"](scoring.simulate) + record = scoring.record() + assert plan.planned_reform_passes("reform_validation") == 53 + assert record["reform_passes"] == record["reform_systems"] == 53 + pre_obbba_systems = [ + system for system in log.systems if system.reform.label == pre_obbba + ] + assert len(pre_obbba_systems) == 1 + pre_obbba_engines = [ + engine + for engine in log.constructions + if engine.tax_benefit_system is pre_obbba_systems[0] + ] + assert len(pre_obbba_engines) == scorer.n_batches + assert all(engine.periods == [2026, 2026] for engine in pre_obbba_engines) + + # --------------------------------------------------------------------------- # Rule modules: each reform's are removed once the consumer moves on # --------------------------------------------------------------------------- diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py index d4e2154ee7..abeb735155 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py @@ -272,7 +272,8 @@ def test_additivity_guards_fire_on_the_installed_engine(builder, tmp_path) -> No def test_shipped_baseline_plans_match_whole_file_policyengine_us( builder, tmp_path ) -> None: - """The smoke, validation and demographics baseline values match in 3 batches. + """The smoke, validation and demographics baseline values, served from + one merged pass in 3 batches, match a whole-file engine. The complete reform sweep runs separately through ``tools/sweep_us_post_export_scoring.py`` in bounded worker processes. @@ -287,15 +288,94 @@ def test_shipped_baseline_plans_match_whole_file_policyengine_us( "demographics": 1, } scorer = builder._HouseholdBatchedPostExportScorer( - path, maximum_microsim_batch_size=3 + path, maximum_microsim_batch_size=3, baseline_plans=plans ) assert scorer.n_batches == 3 + passes = _record_pass_labels(scorer) try: sweep._score_baselines(builder, scorer, path, plans) + # One merged pass, not a fallback to one pass per plan. + assert passes == ["merged baseline plan"] finally: scorer.close() +@pytest.mark.slow +def test_merged_baseline_and_shared_pre_obbba_pass_are_byte_identical( + builder, tmp_path +) -> None: + """On policyengine-us, in 3 household batches: the one merged baseline + pass serves every planned consumer the same bytes (values, weights and + dtypes) as that consumer's own pass, and the pre-OBBBA state scored once + for both OBBBA groups gives each group's total the bytes of a pass of its + own (microcosm#1595). One person holds a taxable estate, so the estate + tax, which the shared pass computes after the income tax, is nonzero.""" + people = sum(len(members) for _, _, members in _GUARD_HOUSEHOLDS) + path = _write_engine_h5( + builder, + tmp_path, + _GUARD_HOUSEHOLDS, + person_inputs={"taxable_estate_value": [30_000_000.0] + [0.0] * (people - 1)}, + ) + fit = _full_in_sample_fit(builder.PERIOD) + plan = builder._record_post_export_scoring_plan( + _plan_args(), + n_households=len(_GUARD_HOUSEHOLDS), + result=fit, + release_id="fixture-release", + ) + assert plan.error is None and len(plan.baseline_plans) == 5 + separate = builder._HouseholdBatchedPostExportScorer( + path, maximum_microsim_batch_size=3 + ) + merged = builder._HouseholdBatchedPostExportScorer( + path, maximum_microsim_batch_size=3, baseline_plans=plan.baseline_plans + ) + assert merged.n_batches == separate.n_batches == 3 + merged_passes = _record_pass_labels(merged) + try: + for name in plan.baseline_plans: + expected = separate.open_consumer(name, plan.baseline_plan(name)) + observed = merged.open_consumer(name, plan.baseline_plan(name)) + for key in plan.baseline_plan(name): + assert _same_bytes(observed._baseline[key], expected._baseline[key]), ( + name, + key, + ) + del expected, observed + # One merged pass, not a fallback to one pass per consumer. + assert merged_passes == ["merged baseline plan"] + assert not merged._merged_baseline + + specs = reform_validation_module.load_default_reform_specs( + period=builder.PERIOD + ) + obbba = [ + spec for spec in specs if reform_validation_module._is_obbba_spec(spec) + ] + reform = reform_validation_module._build_parameter_reform( + reform_validation_module._merged_parameter_changes(obbba) + ) + requests = tuple( + dict.fromkeys((spec.budget_measure, spec.period) for spec in obbba) + ) + assert len(requests) == 2 + consumer = separate.open_consumer("pre-OBBBA state", ()) + shared = consumer.simulate(reform) + shared.prefetch(requests) + # Read the shared pass's values first: opening the next reform + # finishes this one, which then refuses further keys. + shared_values = {request: shared.calculate(*request) for request in requests} + for request in requests: + alone = consumer.simulate(reform).calculate(*request) + assert _same_bytes(shared_values[request], alone), request + assert alone.sum() != 0.0, request + assert consumer.record()["reform_passes"] == 1 + len(requests) + finally: + separate.close() + merged.close() + + @pytest.mark.slow def test_reform_passes_leave_no_rule_modules_behind_and_score_the_same( builder, tmp_path, monkeypatch diff --git a/test_support/microcosm_build/us_post_export_scoring.py b/test_support/microcosm_build/us_post_export_scoring.py index ca6b83e7a6..0e7bd9d993 100644 --- a/test_support/microcosm_build/us_post_export_scoring.py +++ b/test_support/microcosm_build/us_post_export_scoring.py @@ -8,7 +8,8 @@ the plan's contract: output identical to the unbatched path, batches that partition the pool, one live engine at a time, the SPM selection on every construction, one reform system per reform (handed to each batch engine -without ``reform=``), one baseline pass per plan, ascending periods per engine, +without ``reform=``), one baseline pass per plan (one merged pass for +registered plans), ascending periods per engine, engine-free recording, the ``_main`` and writer wiring, the scored-sha binding, the nesting, order and weight premises, the additivity guards (population aggregates, baseline-branch readers, behavioral-response @@ -518,8 +519,22 @@ def _written_h5(tmp_path: Path) -> Path: def _scorer( - builder, frame, log, batch_size, tmp_path, *, loads=None, variables_dir=None + builder, + frame, + log, + batch_size, + tmp_path, + *, + loads=None, + baseline_plans=None, + variables_dir=None, ): + """A scorer over ``frame`` on the fake engine. + + ``baseline_plans`` registers consumers' plans for one shared baseline + pass, as ``_open_post_export_scorer`` does with the recorded plan. + ``variables_dir`` makes each fake rules build register a module there. + """ path = _written_h5(tmp_path) def load_frame(load_path, *, expected_sha256): @@ -527,12 +542,93 @@ def load_frame(load_path, *, expected_sha256): loads.append((Path(load_path), expected_sha256)) return frame + registered = {} if baseline_plans is None else {"baseline_plans": baseline_plans} return builder._HouseholdBatchedPostExportScorer( path, maximum_microsim_batch_size=batch_size, microsimulation_cls=_fake_engine(log, variables_dir=variables_dir), dataset_from_frame=lambda batch_frame: batch_frame, load_frame=load_frame, + **registered, + ) + + +def _full_in_sample_fit(period: int): + """A calibration fit covering every in-sample JCT reform, as a release + fit does, so reform validation simulates only the out-of-sample specs.""" + fitted = [ + spec + for spec in reform_validation_module.load_default_reform_specs(period=period) + if spec.in_sample + ] + return SimpleNamespace( + diagnostics=[ + SimpleNamespace( + final_estimate=-1_000.0 * (index + 1), target=-900.0 * (index + 1) + ) + for index, _ in enumerate(fitted) + ], + problem=SimpleNamespace( + targets=[SimpleNamespace(name=spec.id) for spec in fitted] + ), + ) + + +def _run_planned_consumers(scorer, plan, consumers): + """Open, run and finish each planned consumer in run order, as ``_main`` + does, with the plan's baseline keys and reform pass count. Returns each + consumer's output and served baseline values.""" + outputs, served = {}, {} + for name, consumer in consumers.items(): + scoring = scorer.open_consumer( + name, + plan.baseline_plan(name), + planned_reform_passes=plan.planned_reform_passes(name), + ) + outputs[name] = consumer(scoring.simulate) + served[name] = dict(scoring._baseline) + scorer.finish_consumer(scoring) + return outputs, served + + +def _comparable_output(output): + """A consumer's output in a form ``==`` compares exactly.""" + if hasattr(output, "passed") and hasattr(output, "details"): + return (output.passed, tuple(output.failures), output.details) + if isinstance(output, tuple): + return tuple(np.asarray(item).tolist() for item in output) + return output + + +def _record_pass_labels(scorer) -> list[str]: + """Record the label of every batch-outer pass ``scorer`` runs, so a test + can tell the merged baseline pass from a fallback to separate passes.""" + labels: list[str] = [] + score = scorer._score + + def recording_score(keys, **options): + labels.append(options["label"]) + return score(keys, **options) + + scorer._score = recording_score + return labels + + +def _same_bytes(observed, expected) -> bool: + """Values and weights of two scored results are byte-identical.""" + values, reference = np.asarray(observed.values), np.asarray(expected.values) + if values.dtype != reference.dtype or values.shape != reference.shape: + return False + if values.dtype == object: + same_values = values.tolist() == reference.tolist() + else: + same_values = values.tobytes() == reference.tobytes() + weights = np.asarray(observed.weights) + reference_weights = np.asarray(expected.weights) + return ( + same_values + and weights.dtype == reference_weights.dtype + and weights.tobytes() == reference_weights.tobytes() ) @@ -820,11 +916,14 @@ def _small_calibration_problem(n: int = 40): ) -def _write_engine_h5(builder, directory: Path, households) -> Path: +def _write_engine_h5( + builder, directory: Path, households, *, person_inputs=None +) -> Path: """Write ``households`` as a release H5 through the engine's own writer. One tax unit, SPM unit and family per household; household ``i`` weighs - ``1,000 * i``. + ``1,000 * i``. ``person_inputs`` maps an extra person input column to its + values, one per person in household order. """ from microcosm.frame.adapters.policyengine_us import PolicyEngineUSEngine @@ -847,6 +946,8 @@ def _write_engine_h5(builder, directory: Path, households) -> Path: } ) person = pd.DataFrame(rows) + for column, values in (person_inputs or {}).items(): + person[column] = np.asarray(values, dtype=np.float64) household_ids = np.arange(1, len(households) + 1, dtype=np.int64) frame = Frame( { diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 18e090dfda..7c15de718b 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -5080,11 +5080,16 @@ def _select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame # household and the batches must partition every entity, or the scorer # refuses before any engine exists; # * every construction declares ``spm=US_RELEASE_SPM_SELECTION``; -# * a consumer's baseline requests are learned by an engine-free recording -# dry run and scored in ONE batch-outer pass, in ascending period order; -# the served baseline refuses any key outside that recorded plan; -# * each reform builds ONE tax-benefit system (microcosm#456) and scores its -# keys batch by batch; every batch engine is released before the next; +# * each consumer's baseline requests are learned by an engine-free recording +# dry run; the scorer registers the recorded plans and scores their union +# in ONE batch-outer pass, in ascending period order, serving each consumer +# its own keys (microcosm#1595). A consumer without a registered plan, and +# every consumer once that pass has failed, scores its own plan in a pass +# of its own. The served baseline refuses any key outside the consumer's +# recorded plan; +# * each reform builds ONE tax-benefit system (microcosm#456) and scores each +# key, or each set of keys it is asked to ``prefetch``, in one pass, batch +# by batch; every batch engine is released before the next; # * a batch reform engine gets that system alone, not ``reform=`` too (see # ``_HouseholdBatchedPostExportScorer._construct``), so it carries no # ``baseline`` branch; it refuses the formulas that read one @@ -5104,7 +5109,9 @@ def _select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame # a batch-local aggregate. #: Recorded in ``post_export_scoring`` blocks; bump with any change to how the -#: written H5 is scored. +#: written H5 is scored that can change a scored value. Regrouping keys into +#: fewer passes while every value stays byte-identical (the merged baseline +#: pass and the shared pre-OBBBA pass, microcosm#1595) keeps it. POST_EXPORT_SCORING_METHOD = "household_batched_written_h5" #: One scored request: (variable, period, map_to). @@ -5272,11 +5279,16 @@ class _RecordingPostExportSimulation: """Engine-free stand-in that records each key one simulation is asked for. ``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``. + ``(simulation, key)`` in the order the serial scorer computes them, 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``. ``reform_passes``, also shared, gets one + entry per batched reform pass: when the consumer runs for real, each + ``calculate`` or ``prefetch`` that asks a reformed simulation for a key it + was not asked before is one pass of ``_BatchedPostExportReform``, which + computes the new keys in ascending period order. """ def __init__( @@ -5284,25 +5296,39 @@ def __init__( asked: dict[tuple[int | None, PostExportKey], None], simulation: int | None, reforms: Sequence[object], + reform_passes: list[int], ) -> None: self._asked = asked self._simulation = simulation self._reforms = reforms + self._reform_passes = reform_passes def calculate(self, variable, period=None, map_to=None) -> _PostExportValues: - key = _post_export_key(variable, period, map_to) + self._record((_post_export_key(variable, period, map_to),)) + return _PostExportValues(np.zeros(0), np.zeros(0)) + + def prefetch(self, requests) -> None: + """Record ``requests`` as ``_BatchedPostExportReform.prefetch`` scores them.""" + self._record(tuple(_post_export_key(*request) for request in requests)) + + def _record(self, keys: Sequence[PostExportKey]) -> None: latest = len(self._reforms) - 1 if self._simulation is not None and self._simulation != latest: + asked_for = keys[0] if len(keys) == 1 else tuple(keys) 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." + f"{self._simulation} for {asked_for} after opening reformed " + f"simulation {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)) + new_keys = _ascending_period_plan( + key for key in keys if (self._simulation, key) not in self._asked + ) + self._asked.update(dict.fromkeys((self._simulation, key) for key in new_keys)) + if new_keys and self._simulation is not None: + self._reform_passes.append(self._simulation) def _dry_run_post_export_requests( @@ -5313,10 +5339,12 @@ def _dry_run_post_export_requests( 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. + requests. When the consumer runs for real, each ``calculate`` or + ``prefetch`` that asks a reformed simulation for keys it was not asked + before is one batched pass (``_BatchedPostExportReform``), which computes + those keys in ascending period order, so the reform requests follow that + order; ``simulation`` numbers the consumer's ``simulate(reform)`` calls + from 0. ``_dry_run_post_export`` also counts the passes. No engine is constructed: ``simulate(None)`` returns a recorder that logs every baseline request, and each ``simulate(reform)`` a recorder of its @@ -5332,22 +5360,35 @@ def _dry_run_post_export_requests( So is a key asked of a reformed simulation after the consumer opened the next one, which the scorer refuses too (``_BatchedPostExportReform``). """ + return _dry_run_post_export(consumer)[0] + + +def _dry_run_post_export( + consumer: Callable[[Callable[[Any], Any]], object], +) -> tuple[tuple[tuple[int | None, object, PostExportKey], ...], int]: + """``_dry_run_post_export_requests``'s requests and the number of batched + reform passes the scorer runs for them: one per ``calculate`` or + ``prefetch`` that asks a reformed simulation for a key not asked of it + before, so a ``prefetch`` of several keys is one pass.""" asked: dict[tuple[int | None, PostExportKey], None] = {} reforms: list[object] = [] + reform_passes: list[int] = [] def simulate(reform): if reform is None: - return _RecordingPostExportSimulation(asked, None, reforms) + return _RecordingPostExportSimulation(asked, None, reforms, reform_passes) check_post_export_reform(reform) reforms.append(reform) - return _RecordingPostExportSimulation(asked, len(reforms) - 1, reforms) + return _RecordingPostExportSimulation( + asked, len(reforms) - 1, reforms, reform_passes + ) setattr(simulate, RECORDS_REQUESTS_ONLY, True) consumer(simulate) baseline = _ascending_period_plan( key for simulation, key in asked if simulation is None ) - return ( + requests = ( *((None, None, key) for key in baseline), *( (simulation, reforms[simulation], key) @@ -5355,6 +5396,7 @@ def simulate(reform): if simulation is not None ), ) + return requests, len(reform_passes) def _record_post_export_request_descriptors( @@ -5393,14 +5435,16 @@ def _record_post_export_requests( ) -> 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. + The baseline keys are the plan the served baseline scores. The pass count + is the batched reform passes the scorer runs for the dry run's reform + requests (``_dry_run_post_export``): a ``prefetch`` of several keys of one + reformed simulation is one pass. 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) + requests, reform_passes = _dry_run_post_export(consumer) baseline = tuple(key for simulation, _, key in requests if simulation is None) - return baseline, len(requests) - len(baseline) + return baseline, reform_passes def _record_post_export_baseline_plan( @@ -5764,7 +5808,12 @@ def __init__( microsimulation_cls=None, dataset_from_frame=None, load_frame=None, + baseline_plans: Mapping[str, Sequence[PostExportKey]] | None = None, ) -> None: + """``baseline_plans`` registers consumers' recorded baseline plans by + name: the first of them opened scores the union of every registered + plan in one batch-outer pass, and each is served its own keys from it + (``_baseline_for``).""" self.dataset_path = Path(dataset_path) self.maximum_batch_size = maximum_microsim_batch_size # The scored bytes are bound to this digest: the loader refuses a file @@ -5818,6 +5867,17 @@ def dataset_from_frame(batch_frame: Frame): # Each finished consumer's scoring record, for the manifests' block. # Records, not consumers: a finished consumer's arrays must be freed. self.consumer_records: dict[str, dict[str, object]] = {} + # Every registered plan, which an opened consumer must match; the + # non-empty ones not yet served; and the merged pass's values of the + # keys those still need (None until that pass runs). + self._registered_baseline_plans: dict[str, tuple[PostExportKey, ...]] = { + name: tuple(plan) for name, plan in (baseline_plans or {}).items() + } + self._unserved_baseline_plans = { + name: plan for name, plan in self._registered_baseline_plans.items() if plan + } + self._merged_baseline: dict[PostExportKey, _PostExportValues] | None = None + self._merged_baseline_failed = False # The reform last handed to any consumer. Consumers run one after # another, so at most one reform's system and rule modules are held; # opening the next reform, finishing its consumer or closing the scorer @@ -5830,7 +5890,8 @@ def open_consumer( baseline_plan: Sequence[PostExportKey], planned_reform_passes: int | None = None, ) -> _PostExportConsumer: - """Score ``baseline_plan`` now; return the consumer's simulate seam. + """Score or serve ``baseline_plan`` now (``_baseline_for``); return the + consumer's simulate seam. With ``planned_reform_passes``, each reform pass reports its number of that count as its progress's outer counter. @@ -5887,6 +5948,7 @@ def manifest_record(self) -> dict[str, object]: def close(self) -> None: self._finish_open_reform() self._batch_frames = None + self._merged_baseline = None _collect_family_garbage() def _open_reform_for( @@ -5911,6 +5973,68 @@ def _batches(self) -> tuple[Frame, ...]: raise RuntimeError("The post-export scorer is closed.") return self._batch_frames + def _baseline_for( + self, name: str, baseline_plan: tuple[PostExportKey, ...] + ) -> tuple[dict[PostExportKey, _PostExportValues], bool]: + """Score ``name``'s baseline plan, or serve it from the merged pass. + + Returns the plan's values and whether they came from the merged pass. + A registered consumer opened with any plan but its registered one is + refused. The first registered consumer opened scores the union of + every unserved registered plan in one batch-outer pass, in ascending + period order; each registered consumer is then served exactly its own + keys, once, and the merged values are dropped once no unserved + registered plan holds them. A consumer without a registered plan, or + opened again, scores its own plan in a pass of its own. If the merged + pass raises, every consumer scores its own plan, so a key that only + one consumer planned fails that consumer alone, with the error it + raised before the merge (the holdout reports catch it). + """ + registered = self._registered_baseline_plans.get(name) + if registered is not None and registered != baseline_plan: + raise ValueError( + f"{name}: opened with a baseline plan other than its registered " + "baseline plan; a registered consumer is served the plan recorded " + "before export." + ) + if not baseline_plan: + return {}, False + self._batches() + if name not in self._unserved_baseline_plans or self._merged_baseline_failed: + return self._score(baseline_plan, label=f"{name} baseline plan"), False + if self._merged_baseline is None: + union = _ascending_period_plan( + key for plan in self._unserved_baseline_plans.values() for key in plan + ) + try: + self._merged_baseline = self._score(union, label="merged baseline plan") + except Exception as error: + self._merged_baseline_failed = True + try: + reason = f"{type(error).__name__}: {error}" + except Exception: + reason = type(error).__name__ + print( + f"Post-export merged baseline plan failed ({reason}); each " + "consumer scores its own baseline plan instead.", + flush=True, + ) + if self._merged_baseline_failed: + # Outside the handler, so the failed pass's traceback and the + # per-batch values its frame collected are no longer + # referenced; a full collection frees any held in a cycle. + _collect_family_garbage() + return self._score(baseline_plan, label=f"{name} baseline plan"), False + del self._unserved_baseline_plans[name] + served = {key: self._merged_baseline[key] for key in baseline_plan} + still_planned = { + key for plan in self._unserved_baseline_plans.values() for key in plan + } + for key in tuple(self._merged_baseline): + if key not in still_planned: + del self._merged_baseline[key] + return served, True + def _construct(self, batch_frame: Frame, *, reform_system): dataset = self._dataset_from_frame(batch_frame) if reform_system is None: @@ -6041,6 +6165,7 @@ def _open_post_export_scorer( dataset_path, maximum_microsim_batch_size=plan.maximum_batch_size, expected_n_households=plan.n_households, + baseline_plans=plan.baseline_plans, ) @@ -6087,10 +6212,8 @@ def __init__( self.reform_passes = 0 self.planned_reform_passes = planned_reform_passes self.reform_systems = 0 - self._baseline = ( - scorer._score(baseline_plan, label=f"{name} baseline plan") - if baseline_plan - else {} + self._baseline, self.baseline_from_merged_pass = scorer._baseline_for( + name, baseline_plan ) def simulate(self, reform): @@ -6124,11 +6247,20 @@ def _baseline_values(self, key: PostExportKey) -> _PostExportValues: "baseline request, so nothing is scored off-plan." ) from None - def _reform_values(self, reform_system, key: PostExportKey): - label = f"{self.name} reform {key[0]}@{key[1]}" - self._scorer._assert_reform_keeps_baseline_responses( - reform_system, key, label=label - ) + def _reform_values( + self, reform_system, keys: tuple[PostExportKey, ...] + ) -> dict[PostExportKey, _PostExportValues]: + """One batched reform pass over ``keys`` (ascending period order).""" + label = f"{self.name} reform " + ", ".join( + f"{variable}@{period}" for variable, period, _ in keys + ) + checked_periods: set[int] = set() + for key in keys: + if key[1] not in checked_periods: + checked_periods.add(key[1]) + self._scorer._assert_reform_keeps_baseline_responses( + reform_system, key, label=label + ) self.reform_passes += 1 planned = self.planned_reform_passes outer = ( @@ -6136,10 +6268,9 @@ def _reform_values(self, reform_system, key: PostExportKey): if planned is not None and self.reform_passes <= planned else None ) - scored = self._scorer._score( - (key,), label=label, reform_system=reform_system, outer=outer + return self._scorer._score( + keys, label=label, reform_system=reform_system, outer=outer ) - return scored[key] class _PlannedPostExportBaseline: @@ -6153,11 +6284,18 @@ def calculate(self, variable, period=None, map_to=None) -> _PostExportValues: _post_export_key(variable, period, map_to) ) + def prefetch(self, requests) -> None: + """Nothing to score: refuse any request outside the served plan, as + ``calculate`` would (the dry run's recorder takes ``prefetch`` too).""" + for request in requests: + self._consumer._baseline_values(_post_export_key(*request)) + class _BatchedPostExportReform: - """A reformed simulation a consumer sees: each key is one batched pass. + """A reformed simulation a consumer sees: each key not yet scored, or each + ``prefetch`` of several such keys, is one batched pass. - The reform's tax-benefit system is built once, on the first key, and + The reform's tax-benefit system is built once, on the first pass, and handed to every batch engine (microcosm#456). The engines get that system alone (see ``_HouseholdBatchedPostExportScorer._construct``). @@ -6180,29 +6318,46 @@ def __init__(self, consumer: _PostExportConsumer, reform) -> None: def calculate(self, variable, period=None, map_to=None) -> _PostExportValues: key = _post_export_key(variable, period, map_to) + self._score_new((key,)) + return self._results[key] + + def prefetch(self, requests) -> None: + """Score every requested key not yet scored in one batched pass. + + ``requests`` are ``(variable, period)`` or ``(variable, period, + map_to)`` tuples. Each batch engine computes them in ascending period + order, and later ``calculate`` calls for them are served from the + pass. The dry run counts it as one pass + (``_RecordingPostExportSimulation.prefetch``). + """ + self._score_new(tuple(_post_export_key(*request) for request in requests)) + + def _score_new(self, keys: Sequence[PostExportKey]) -> None: if self._finished: + asked = keys[0] if len(keys) == 1 else tuple(keys) raise RuntimeError( - f"{self._consumer.name} asked a finished reform for {key}. A " + f"{self._consumer.name} asked a finished reform for {asked}. A " "post-export consumer scores each reform completely before it " "opens the next one, which finishes and releases the earlier." ) - if key not in self._results: - if self._system is None: - scorer = self._consumer._scorer - rule_modules = EngineVariableModuleScope().open() - try: - self._system = ( - scorer._microsimulation_cls.default_tax_benefit_system( - reform=self._reform - ) - ) - except BaseException: - rule_modules.close() - raise - self._rule_modules = rule_modules - self._consumer.reform_systems += 1 - self._results[key] = self._consumer._reform_values(self._system, key) - return self._results[key] + new_keys = _ascending_period_plan( + key for key in keys if key not in self._results + ) + if not new_keys: + return + if self._system is None: + scorer = self._consumer._scorer + rule_modules = EngineVariableModuleScope().open() + try: + self._system = scorer._microsimulation_cls.default_tax_benefit_system( + reform=self._reform + ) + except BaseException: + rule_modules.close() + raise + self._rule_modules = rule_modules + self._consumer.reform_systems += 1 + self._results.update(self._consumer._reform_values(self._system, new_keys)) def finish(self) -> None: """Drop the reform's system and remove the modules its build added.""" @@ -11429,8 +11584,13 @@ def _score_post_export_consumer( ) output = consumer(scoring.simulate) record = scorer.finish_consumer(scoring) + baseline = ( + "baseline served from the merged pass" + if scoring.baseline_from_merged_pass + else f"{record['baseline_passes']} baseline pass" + ) print( - f"Post-export {name}: {record['baseline_passes']} baseline pass " + f"Post-export {name}: {baseline} " f"({len(plan)} keys), {record['reform_passes']} reform passes, " f"{record['reform_systems']} reform systems, " f"{record['n_batches']} batches of up to " @@ -19594,7 +19754,8 @@ def _certify_us_build( # smoke, reform validation, demographics) scores THIS file through one # household-batched scorer instead of one whole-pool Microsimulation each. # It loads the written H5 once, binds its sha256 (the manifest must pin - # the same bytes), and serves the baseline plans recorded above. + # the same bytes), and serves the baseline plans recorded above from one + # merged baseline pass (microcosm#1595). post_export_scorer = _open_post_export_scorer( post_export_scoring_plan, dataset_path ) @@ -19643,8 +19804,9 @@ def _certify_us_build( ) + "\n" ) - # The smoke's scored baseline plan is recorded; free its arrays before - # reform validation scores its own. + # The smoke's record is written; free its reform results before reform + # validation runs. Its baseline values stay with the scorer only while + # a consumer still to be served planned them. del smoke_scoring if telemetry is not None: telemetry.attach_artifact( diff --git a/tools/sweep_us_post_export_scoring.py b/tools/sweep_us_post_export_scoring.py index fd6ca50296..65cf425921 100644 --- a/tools/sweep_us_post_export_scoring.py +++ b/tools/sweep_us_post_export_scoring.py @@ -35,8 +35,10 @@ def _record_requests(builder): ``_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. + the baseline plans, and the reform requests, from which each worker + rebuilds the reforms it scores. A worker scores each reform request as a + pass of its own; the release scores the requests of one ``prefetch`` + (reform validation's shared pre-OBBBA state) in one pass. """ specs = builder.load_default_reform_specs(period=builder.PERIOD) @@ -173,8 +175,12 @@ def _worker(args): started = time.monotonic() builder = _load_builder() plans, requests, counts = _record_requests(builder) + # The baseline worker registers its plans, so its scorer serves them from + # one merged pass, as the release's scorer does. scorer = builder._HouseholdBatchedPostExportScorer( - args.dataset_path, maximum_microsim_batch_size=args.batch_size + args.dataset_path, + maximum_microsim_batch_size=args.batch_size, + baseline_plans=plans if args.worker_start is None else None, ) if scorer.n_batches < 2: raise ValueError("The guard sweep needs at least two household batches")