Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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).
59 changes: 50 additions & 9 deletions docs/us-release-build-rule.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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],
*,
Expand Down Expand Up @@ -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.

Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading