diff --git a/changelog.d/us-post-export-request-descriptors.added.md b/changelog.d/us-post-export-request-descriptors.added.md new file mode 100644 index 0000000000..aab943b296 --- /dev/null +++ b/changelog.d/us-post-export-request-descriptors.added.md @@ -0,0 +1 @@ +The US release tool's `_record_post_export_request_descriptors` returns every request each post-export stage makes in the engine-free post-export dry run as a picklable `PostExportRequest` (`microcosm.build.us_runtime.post_export_requests`), for later work that runs the requests in worker processes; the release itself still takes only the baseline plans and reform-pass counts. A descriptor holds the stage, the request's place in the order the serial scorer runs it, the variable, period and `map_to`, and for a reform request the description its reform is rebuilt from (the smoke probe, the reform-validation spec, or a cumulative OBBBA state's parameter changes) and which of the stage's reformed simulations asked for it. Reform validation, like the smoke check, now hands the dry run those descriptions instead of building reforms, so the dry run needs no policyengine-core, and it refuses a reform it cannot describe or pickle. It also refuses a key asked of a reformed simulation after the stage opened the next one, which the scorer refuses once it has finished that simulation, so such a stage fails the plan before the export rather than certification's scoring after it. The plan no longer builds reform-validation reform classes before the export, as it already did not for the smoke check. Nothing records the descriptors: the plan in `calibration_diagnostics.json`, each stage's output and each stage's reform-pass count stay the same, which a test pins on a fixture. `RECORDS_REQUESTS_ONLY` moves from `reform_coverage_smoke` to the new module. `tools/sweep_us_post_export_scoring.py` records through the descriptors and rebuilds each reform in the worker that scores it. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 92645b1559..764ec34243 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -449,6 +449,19 @@ one Microsimulation over the whole file. 2025 state taxes after 2027 keys. It checks for the `md.msde.ccs.payment.informal.rates` error and warns if that error is absent; it does not require the upstream bug to persist. +- `_record_post_export_request_descriptors` runs the same dry run and returns + every request, baseline and reform, as a picklable `PostExportRequest` + (`microcosm.build.us_runtime.post_export_requests`), which a process started + with `spawn` can unpickle; the release itself still takes only the baseline + plans and reform-pass counts. A reform request holds + the description its stage builds the reform from: the smoke probe, the + reform-validation spec, or a cumulative OBBBA state's parameter changes. The + dry run builds no reform, and refuses a reform it cannot describe or pickle. + It also refuses a key asked of a reformed simulation after its stage opened + the next one: the scorer finishes a reformed simulation when the next opens + and refuses it further keys, so the plan fails before the export instead. + Nothing records the descriptors; the guard sweep below rebuilds each reform + from its descriptor in the worker that scores it. - Each batch engine keeps policyengine-us's projection of the release year to its last CPI-U year (2035), because the plans request keys in later years (reform validation reaches past 2025). The build's own simulations hold diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py new file mode 100644 index 0000000000..b954240fd1 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/post_export_requests.py @@ -0,0 +1,255 @@ +"""Picklable descriptions of the US release's post-export scoring requests. + +The release tool (``tools/build_us_fiscal_refresh_release.py``) learns what +each post-export consumer will ask policyengine-us for by running the consumer +once against engine-free recorders (its "dry run"). The consumers call +``simulate(None)`` for the baseline simulation and ``simulate(reform)`` for a +reformed one, then ``.calculate(variable, period, map_to=...)`` on each. The +release takes only each consumer's baseline plan and reform-pass count from the +dry run; the tool's ``_record_post_export_request_descriptors`` returns every +request of the same dry run as a :class:`PostExportRequest`, which a process +started with the ``spawn`` method can unpickle and run. + +A built reform cannot cross a process boundary: ``Reform.from_dict`` returns a +class defined inside a function, which pickle cannot name. So a consumer whose +``simulate`` carries :data:`RECORDS_REQUESTS_ONLY` hands it the description it +builds the reform from instead, and :func:`build_post_export_reform` rebuilds +the reform from that description with the consumer's own builder: + +- a :class:`~microcosm.build.us_runtime.release_input_coverage.ReformCoverageProbe` + (the reform-coverage smoke check), rebuilt by + ``reform_coverage_smoke._build_reform``; +- a :class:`~microcosm.build.us_runtime.reform_validation.ReformValidationSpec` + (a reform-validation row simulated on its own), rebuilt by its + ``build_reform``; +- a :class:`ParameterChangesReform` (one of reform validation's cumulative + OBBBA states), rebuilt by ``reform_validation._build_parameter_reform``. + +These types live here, in an importable package, so that a spawned process +can unpickle them however the release tool was started. The tests and the +guard sweep load the tool by file path, outside ``sys.modules``, where a type +defined in it cannot even be pickled. A release runs the tool as a script, +where a spawned process would unpickle such a type only by running the whole +tool again as its ``__mp_main__`` module (which a process started with +``spawn`` does to the parent's main script in any case). + +Neither type can be hashed, because a reform description holds dictionaries; +key a request's results by its ``(consumer, position)``. +""" + +from __future__ import annotations + +import copy +import pickle +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any + +from microcosm.build.us_runtime.reform_validation import ReformValidationSpec +from microcosm.build.us_runtime.release_input_coverage import ReformCoverageProbe + +__all__ = [ + "RECORDS_REQUESTS_ONLY", + "ParameterChangesReform", + "PostExportReform", + "PostExportRequest", + "build_post_export_reform", + "check_post_export_reform", +] + +#: Set to ``True`` on a ``simulate`` that only records the requests it is +#: asked for and never applies a reform (the release tool's engine-free dry +#: run). A consumer then hands it the description of each reform (see the +#: module docstring) in place of the built reform, so recording builds no +#: reform, resolves no list edit and needs no engine. +RECORDS_REQUESTS_ONLY = "records_requests_only" + + +@dataclass(frozen=True) +class ParameterChangesReform: + """A reform given as a ``Reform.from_dict`` payload for country ``us``. + + Reform validation scores OBBBA's provisions cumulatively from a pre-OBBBA + state; each state is one such payload. An empty payload is the baseline, + which a consumer asks for as ``simulate(None)``, so it is refused here. + + It keeps a deep copy of the payload, as a ``dict``: the request records + the reform as the consumer asked for it, and no later change to the + consumer's dictionaries (which its reform specs share) reaches it. + """ + + parameter_changes: Mapping[str, Any] + + # Not hashable: the payload is a dictionary. + __hash__ = None # type: ignore[assignment] + + def __post_init__(self) -> None: + if not isinstance(self.parameter_changes, Mapping): + raise TypeError( + "ParameterChangesReform needs its parameter changes as a mapping " + f"of parameter paths, got {type(self.parameter_changes).__name__}." + ) + if not self.parameter_changes: + raise ValueError( + "ParameterChangesReform needs at least one of its parameter " + "changes; the baseline is simulate(None)." + ) + try: + copied = copy.deepcopy(dict(self.parameter_changes)) + except Exception as error: + raise TypeError( + "ParameterChangesReform's parameter changes cannot be copied: " + f"{type(error).__name__}: {error}" + ) from error + object.__setattr__(self, "parameter_changes", copied) + + +#: What a post-export request records as its reform: the description the +#: consumer builds the reform from. +type PostExportReform = ( + ReformCoverageProbe | ReformValidationSpec | ParameterChangesReform +) + + +_POST_EXPORT_REFORM_TYPES = ( + ReformCoverageProbe, + ReformValidationSpec, + ParameterChangesReform, +) + + +def check_post_export_reform(reform: object) -> None: + """Refuse a reform that is not a description a worker can rebuild. + + The description must be exactly one of the accepted types, not a + subclass, whose module a worker might not have, and must pickle, so a + failure shows in the release's pre-export plan rather than when a request + is sent to a worker. + + Raises: + TypeError: Naming the reform's type and the types accepted, or why + the description cannot be pickled. + """ + if type(reform) not in _POST_EXPORT_REFORM_TYPES: + accepted = ", ".join(kind.__name__ for kind in _POST_EXPORT_REFORM_TYPES) + raise TypeError( + "Post-export scoring records each reform as the description a worker " + f"rebuilds it from ({accepted}); got a {type(reform).__module__}." + f"{type(reform).__qualname__}. A consumer whose simulate carries " + "RECORDS_REQUESTS_ONLY must hand it a description of one of those " + "types exactly, not a built reform or a subclass." + ) + try: + pickle.dumps(reform) + except Exception as error: + raise TypeError( + f"Post-export scoring got a {type(reform).__qualname__} reform " + "description that cannot be pickled for a worker process: " + f"{type(error).__name__}: {error}" + ) from error + + +def build_post_export_reform(reform: PostExportReform) -> Any: + """Build the reform ``reform`` describes, with its consumer's own builder. + + Each builder is looked up when it is called, so this builds exactly what + the consumer builds when it scores the same description. + """ + check_post_export_reform(reform) + if isinstance(reform, ReformCoverageProbe): + from microcosm.build.us_runtime import reform_coverage_smoke + + return reform_coverage_smoke._build_reform(reform) + if isinstance(reform, ParameterChangesReform): + from microcosm.build.us_runtime import reform_validation + + return reform_validation._build_parameter_reform(reform.parameter_changes) + return reform.build_reform() + + +def _require_name(name: str, value: object) -> None: + if not isinstance(value, str): + raise TypeError(f"PostExportRequest.{name} must be a string, got {value!r}.") + if not value: + raise ValueError(f"PostExportRequest.{name} must not be empty.") + + +def _require_integer(name: str, value: object, *, minimum: int | None = None) -> None: + if not isinstance(value, int) or isinstance(value, bool): + raise TypeError( + f"PostExportRequest.{name} must be a Python integer, got {value!r}." + ) + if minimum is not None and value < minimum: + raise ValueError( + f"PostExportRequest.{name} must be {minimum} or more, got {value}." + ) + + +@dataclass(frozen=True) +class PostExportRequest: + """One request a post-export consumer makes of policyengine-us. + + Attributes: + consumer: The consumer's name in the release's post-export plan, such + as ``"reform_validation"``. + position: The request's place, from 0, in the order the serial scorer + runs the consumer's requests: the baseline plan's keys (scored + together in one pass, in ascending period order and then request + order), then one reform pass per reform request, in the order the + consumer first asks each reformed simulation for each key. + variable: The variable to calculate. + period: The year to calculate it for. + map_to: The entity the values are mapped to, or ``None`` for the + variable's own entity, which the engine resolves when it + calculates the variable. + reform: ``None`` for the baseline simulation; otherwise the + description the reform is rebuilt from (:func:`build_post_export_reform`). + reformed_simulation: For a reform request, which of the consumer's + ``simulate(reform)`` calls made the simulation asked, numbered from + 0 in call order (a simulation never asked makes no request but + keeps its number); ``None`` for the baseline. + """ + + consumer: str + position: int + variable: str + period: int + map_to: str | None = None + reform: PostExportReform | None = None + reformed_simulation: int | None = None + + # Not hashable: most reform descriptions hold dictionaries. + __hash__ = None # type: ignore[assignment] + + def __post_init__(self) -> None: + _require_name("consumer", self.consumer) + _require_name("variable", self.variable) + _require_integer("position", self.position, minimum=0) + _require_integer("period", self.period) + if self.map_to is not None: + _require_name("map_to", self.map_to) + if self.reform is None: + if self.reformed_simulation is not None: + raise ValueError( + "A baseline PostExportRequest names no reformed simulation, " + f"got {self.reformed_simulation!r}." + ) + return + check_post_export_reform(self.reform) + if self.reformed_simulation is None: + raise ValueError( + "A reform PostExportRequest names the reformed simulation that " + "asked for it." + ) + _require_integer("reformed_simulation", self.reformed_simulation, minimum=0) + + @property + def key(self) -> tuple[str, int, str | None]: + """(variable, period, map_to), the release tool's ``PostExportKey``.""" + return (self.variable, self.period, self.map_to) + + def build_reform(self) -> Any: + """The reform the worker's engine applies; ``None`` for the baseline.""" + if self.reform is None: + return None + return build_post_export_reform(self.reform) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/reform_coverage_smoke.py b/packages/microcosm-build/src/microcosm/build/us_runtime/reform_coverage_smoke.py index 17ba72639a..067e66c872 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/reform_coverage_smoke.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/reform_coverage_smoke.py @@ -28,6 +28,7 @@ from typing import Any from microcosm.build.gates import GateResult +from microcosm.build.us_runtime.post_export_requests import RECORDS_REQUESTS_ONLY from microcosm.build.us_runtime.release_input_coverage import ( ListParameterEdit, ReformCoverageProbe, @@ -38,19 +39,12 @@ ) __all__ = [ - "RECORDS_REQUESTS_ONLY", "us_reform_coverage_smoke_gate", ] # simulate(reform_or_None) -> object with .calculate(measure, period).sum() SimulateFn = Callable[[Any], Any] -#: Set to ``True`` on a ``simulate`` that only records the keys it is asked -#: for and never applies a reform (the release tool's post-export plan dry -#: run). The gate then passes it each probe in place of the probe's built -#: reform, so recording resolves no list edit and needs no engine. -RECORDS_REQUESTS_ONLY = "records_requests_only" - def _weighted_total(simulation: Any, measure: str, period: int) -> float: """Weighted population total (policyengine-us MicroSeries .sum() is weighted).""" @@ -152,9 +146,10 @@ def us_reform_coverage_smoke_gate( simulate: ``simulate(None)`` builds the baseline; ``simulate(reform)`` builds the reformed simulation. Each result answers ``.calculate(measure, period).sum()`` as a weighted total. A - ``simulate`` whose :data:`RECORDS_REQUESTS_ONLY` attribute is true - only records requests: it receives each probe in place of the - probe's reform, and no reform is built. + ``simulate`` whose + :data:`~microcosm.build.us_runtime.post_export_requests.RECORDS_REQUESTS_ONLY` + attribute is true only records requests: it receives each probe + in place of the probe's reform, and no reform is built. probes: Probes to run. Defaults to the shipped manifest's probe set. period: Default period for probes without a probe-specific period. name: Gate name for the manifest. diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/reform_validation.py b/packages/microcosm-build/src/microcosm/build/us_runtime/reform_validation.py index 36b1f30b53..3e06147e68 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/reform_validation.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/reform_validation.py @@ -746,7 +746,21 @@ def reform_validation_payload( incremental effect given the lines above it — so the per-line effects sum to the bill total, matching JCT (see ``stacked_obbba_effects``). The shape matches the calibration-diagnostics dashboard's reform_validation reader. + + A ``simulate`` whose + :data:`~microcosm.build.us_runtime.post_export_requests.RECORDS_REQUESTS_ONLY` + attribute is true only records requests (the release tool's post-export + dry run). It receives each reform's description in place of the built + reform: the spec for a row simulated on its own, and a + :class:`~microcosm.build.us_runtime.post_export_requests.ParameterChangesReform` + for each cumulative OBBBA state. No reform is built. """ + # Imported here: post_export_requests imports ReformValidationSpec. + from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, + ParameterChangesReform, + ) + estimates = in_sample_estimates or {} targets = in_sample_targets or {} baseline: Any = None @@ -754,6 +768,7 @@ def reform_validation_payload( obbba_specs = tuple(spec for spec in specs if _is_obbba_spec(spec)) obbba_pre_baseline_changes = _merged_parameter_changes(obbba_specs) obbba_stacked: dict[str, tuple[float, float, float]] | None = None + records_requests_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True def baseline_total(measure: str, at_period: int) -> float: nonlocal baseline @@ -765,8 +780,11 @@ def baseline_total(measure: str, at_period: int) -> float: return baseline_totals[key] def simulation_for_parameter_changes(changes: dict[str, Any]) -> Any: - reform = None if not changes else _build_parameter_reform(changes) - return simulate(reform) # type: ignore[misc] + if not changes: + return simulate(None) # type: ignore[misc] + if records_requests_only: + return simulate(ParameterChangesReform(changes)) # type: ignore[misc] + return simulate(_build_parameter_reform(changes)) # type: ignore[misc] def released_weighted_total( transient_simulation: Any, measure: str, at_period: int @@ -849,8 +867,9 @@ def simulated_effect( obbba_stacked = stacked_obbba_effects() return obbba_stacked.get(spec.id, (None, None, None)) base = baseline_total(spec.budget_measure, spec.period) + reform = spec if records_requests_only else spec.build_reform() reform_total = released_weighted_total( - simulate(spec.build_reform()), spec.budget_measure, spec.period + simulate(reform), spec.budget_measure, spec.period ) raw = reform_total - base # A counterfactual revert measures the provision as baseline − reform. diff --git a/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py b/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py index fbd210b5e1..f6ab98e933 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py @@ -8,6 +8,7 @@ from hypothesis import strategies as st import microcosm.build.us_runtime.release_input_coverage as coverage_module +from microcosm.build.us_runtime.post_export_requests import RECORDS_REQUESTS_ONLY from microcosm.build.us_runtime.release_input_coverage import ( US_RELEASE_INPUT_COVERAGE_SCHEMA_VERSION, ListParameterEdit, @@ -394,7 +395,7 @@ def simulate(reform): return _Sim(4.16e10 if reform is not None else 4.0e10) if flag: - setattr(simulate, smoke_module.RECORDS_REQUESTS_ONLY, True) + setattr(simulate, RECORDS_REQUESTS_ONLY, True) probes = [_probe(), _list_edit_probe()] result = us_reform_coverage_smoke_gate( simulate=simulate, probes=probes, period=2024 diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index 450512f6c5..45c00b1743 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -158,6 +158,9 @@ # microcosm#1585 item 11: us_runtime.multispine_pool's shadow sites # import us_runtime.gate_shadow. "microcosm.build.us_runtime.gate_shadow", + # microcosm#1722: us_runtime.reform_coverage_smoke imports + # RECORDS_REQUESTS_ONLY from us_runtime.post_export_requests. + "microcosm.build.us_runtime.post_export_requests", # microcosm#1686: the five SIPP donor modules import the shared read # of the SIPP person file. "microcosm.build.us_runtime.sipp_december_person_rows", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_requests.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_requests.py new file mode 100644 index 0000000000..066ce79948 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_requests.py @@ -0,0 +1,695 @@ +"""Post-export requests recorded as picklable descriptors. + +The engine-free dry run that learns each post-export consumer's baseline plan +also returns every request the consumer makes as a ``PostExportRequest``, so +that later work can send the requests to spawned worker processes and rebuild +each consumer's output from their results. These tests check that: + +- the dry run returns one descriptor per request of every shipped consumer, + with no engine importable, and builds no reform: each reform is recorded as + the description its consumer builds it from; +- the descriptors list the requests in the order the serial scorer runs them + (the baseline plan, then each reform pass), name the reformed simulation + that asked for each, and rebuild the reform that simulation was given; +- every descriptor survives a pickle round trip through a spawned process; +- the dry run refuses a reform it cannot describe or pickle; +- descriptors cannot be hashed and keep their own copy of a reform's + parameter changes; +- the recorded outputs of the release stay byte-identical on the fixture. +""" + +# ruff: noqa: F403, F405 +from __future__ import annotations + +import dataclasses +import hashlib +import itertools +import json +import multiprocessing +import os +import pickle +import re +import threading +import types +import typing +from collections.abc import Mapping +from concurrent.futures import ProcessPoolExecutor +from types import MappingProxyType + +import microcosm.build.us_runtime.release_input_coverage as coverage_module +from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, + ParameterChangesReform, + PostExportReform, + PostExportRequest, + build_post_export_reform, +) +from test_support.microcosm_build.post_export_request_worker import ( + requests_as_a_spawned_worker_receives_them, +) +from test_support.microcosm_build.us_post_export_scoring import * + +_RELEASE_ID = "fixture-release" + + +def _shipped_consumers(builder): + """The five post-export consumers a release runs, in run order.""" + return builder._post_export_consumers( + _plan_args(), + result=_calibration_result_with_in_sample_fit(builder.PERIOD), + release_id=_RELEASE_ID, + ) + + +@pytest.fixture +def no_engine(monkeypatch): + """No engine package importable, no list edit resolvable, no reform built.""" + for module in ("policyengine_us", "policyengine_core", "policyengine_core.reforms"): + monkeypatch.setitem(sys.modules, module, None) + + def refused(*args, **kwargs): + raise AssertionError("the engine-free dry run built a reform") + + # The installed-engine reader is cached per process, so blocking the + # imports alone would not catch a resolution served from an earlier test. + monkeypatch.setattr(coverage_module, "_installed_parameter_stages", refused) + monkeypatch.setattr(smoke_module, "_build_reform", refused) + monkeypatch.setattr(reform_validation_module, "_build_parameter_reform", refused) + monkeypatch.setattr(ReformValidationSpec, "build_reform", refused) + + +def test_the_dry_run_returns_every_request_as_a_descriptor(builder, no_engine) -> None: + probes = us_release_reform_coverage_probes() + specs = reform_validation_module.load_default_reform_specs(period=builder.PERIOD) + fitted = { + spec.id + for spec in reform_validation_module.in_sample_reform_specs( + period=builder.PERIOD + )[:2] + } + recorded: dict[str, tuple[PostExportRequest, ...]] = {} + for name, consumer in _shipped_consumers(builder).items(): + requests = builder._record_post_export_request_descriptors(name, consumer) + assert all(isinstance(request, PostExportRequest) for request in requests) + assert {request.consumer for request in requests} <= {name} + assert [request.position for request in requests] == list(range(len(requests))) + baseline = tuple(request for request in requests if request.reform is None) + reformed = tuple(request for request in requests if request.reform is not None) + # The baseline plan first, as the serial scorer scores it. + assert requests == (*baseline, *reformed) + assert all(request.reformed_simulation is None for request in baseline) + assert all(isinstance(request.reformed_simulation, int) for request in reformed) + # The plan and the pass count the release records are the same dry + # run's. + plan, passes = builder._record_post_export_requests(consumer) + assert tuple(request.key for request in baseline) == plan + assert len(reformed) == passes + recorded[name] = requests + assert list(recorded) == [ + "reform_coverage_smoke", + "reform_validation", + "demographics", + "ssi_social_security_holdout", + "medicare_irmaa_holdout", + ] + + smoke = [ + request + for request in recorded["reform_coverage_smoke"] + if request.reform is not None + ] + assert [request.reform for request in smoke] == list(probes) + assert [request.reformed_simulation for request in smoke] == list( + range(len(probes)) + ) + assert [request.key for request in smoke] == [ + (probe.budget_measure, int(probe.period or builder.PERIOD), None) + for probe in probes + ] + + validation = [ + request + for request in recorded["reform_validation"] + if request.reform is not None + ] + assert {type(request.reform) for request in validation} == { + ReformValidationSpec, + ParameterChangesReform, + } + # Every spec simulated on its own: the out-of-sample ones outside OBBBA's + # stacks, and the in-sample ones the calibration fit does not cover. + assert [ + request.reform.id + for request in validation + if isinstance(request.reform, ReformValidationSpec) + ] == [ + spec.id + for spec in specs + if not reform_validation_module._is_obbba_spec(spec) + and not (spec.in_sample and spec.id in fitted) + ] + # OBBBA: each (measure, period) group scores the pre-OBBBA state, then one + # stacked state per provision. + obbba = [spec for spec in specs if reform_validation_module._is_obbba_spec(spec)] + states = [ + request + for request in validation + if isinstance(request.reform, ParameterChangesReform) + ] + groups = {(spec.budget_measure, spec.period) for spec in obbba} + assert len(states) == len(obbba) + len(groups) + pre_obbba = ParameterChangesReform( + reform_validation_module._merged_parameter_changes(obbba) + ) + assert [request.key[:2] for request in states if request.reform == pre_obbba] == [ + (measure, period) + for measure, period in dict.fromkeys( + (spec.budget_measure, spec.period) for spec in obbba + ) + ] + assert len({request.reformed_simulation for request in validation}) == len( + validation + ) + + for name in ( + "demographics", + "ssi_social_security_holdout", + "medicare_irmaa_holdout", + ): + assert all(request.reform is None for request in recorded[name]), name + + +def test_every_request_round_trips_through_a_spawned_process( + builder, no_engine +) -> None: + """A worker started with the ``spawn`` method, which has never run the + release tool, unpickles every shipped request and sends it back equal.""" + requests = tuple( + request + for name, consumer in _shipped_consumers(builder).items() + for request in builder._record_post_export_request_descriptors(name, consumer) + ) + assert any(request.reform is not None for request in requests) + with ProcessPoolExecutor( + max_workers=1, mp_context=multiprocessing.get_context("spawn") + ) as executor: + received = executor.submit( + requests_as_a_spawned_worker_receives_them, requests + ).result() + assert received["start_method"] == "spawn" + assert received["process_id"] != os.getpid() + assert received["requests"] == requests + assert received["type_modules"] == [ + "microcosm.build.us_runtime.post_export_requests", + "microcosm.build.us_runtime.reform_validation", + "microcosm.build.us_runtime.release_input_coverage", + ] + + +def _watched_simulate(builder, simulate, asked: list): + """``simulate``, logging each reformed simulation's first ask per key. + + Each entry is (the reformed simulation's number among the consumer's + ``simulate(reform)`` calls, the reform's label, the key). + """ + numbers = itertools.count() + + def watched(reform): + simulation = simulate(reform) + if reform is None: + return simulation + number = next(numbers) + + class Watched: + def calculate(self, variable, period=None, map_to=None): + entry = ( + number, + reform.label, + builder._post_export_key(variable, period, map_to), + ) + if entry not in asked: + asked.append(entry) + return simulation.calculate(variable, period, map_to) + + return Watched() + + return watched + + +def test_the_descriptors_list_the_passes_the_serial_scorer_runs( + builder, fake_reforms, tmp_path +) -> None: + """Each consumer, scored as ``_main`` scores it, runs its baseline plan and + then one reform pass per reform descriptor, in descriptor order, on the + reformed simulation each descriptor names, with the reform it rebuilds.""" + scorer = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path) + try: + for name, consumer in _shipped_consumers(builder).items(): + requests = builder._record_post_export_request_descriptors(name, consumer) + baseline = tuple(r.key for r in requests if r.reform is None) + reformed = [r for r in requests if r.reform is not None] + scoring = scorer.open_consumer( + name, baseline, planned_reform_passes=len(reformed) + ) + assert scoring.baseline_plan == baseline + asked: list = [] + consumer(_watched_simulate(builder, scoring.simulate, asked)) + assert asked == [ + (request.reformed_simulation, request.build_reform().label, request.key) + for request in reformed + ], name + assert scorer.finish_consumer(scoring)["reform_passes"] == len(reformed) + finally: + scorer.close() + + +def test_reform_requests_follow_the_order_of_first_asks( + builder, fake_reforms, tmp_path +) -> None: + """A reform pass runs when a reformed simulation is first asked for a key, + so the descriptors follow those first asks. The scorer finishes a + reformed simulation when the consumer opens the next one and refuses it + further keys, so a consumer asks each reformed simulation for all its + keys before opening the next; a simulation never asked makes no request + but keeps its number.""" + first = ParameterChangesReform({"gov.fixture.first": {"2024-01-01": 1}}) + second = ParameterChangesReform({"gov.fixture.second": {"2024-01-01": 2}}) + unasked = ParameterChangesReform({"gov.fixture.unasked": {"2024-01-01": 3}}) + + 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) + simulate(None).calculate("income_tax", 2025) + first_simulation.calculate("income_tax", 2024) + first_simulation.calculate("income_tax", 2024) + first_simulation.calculate("age", 2024, map_to="household") + reformed(unasked) + second_simulation = reformed(second) + simulate(None).calculate("age", 2024, map_to="household") + second_simulation.calculate("income_tax", 2024) + + requests = builder._record_post_export_request_descriptors("fixture", consumer) + assert [(r.position, r.reformed_simulation, r.reform, r.key) for r in requests] == [ + (0, None, None, ("age", 2024, "household")), + (1, None, None, ("income_tax", 2025, None)), + (2, 0, first, ("income_tax", 2024, None)), + (3, 0, first, ("age", 2024, "household")), + (4, 2, second, ("income_tax", 2024, None)), + ] + assert builder._record_post_export_requests(consumer) == ( + (("age", 2024, "household"), ("income_tax", 2025, None)), + 3, + ) + + scorer = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path) + try: + baseline = tuple(r.key for r in requests if r.reform is None) + scoring = scorer.open_consumer("fixture", baseline) + asked: list = [] + consumer(_watched_simulate(builder, scoring.simulate, asked)) + assert asked == [ + (r.reformed_simulation, r.build_reform().label, r.key) + for r in requests + if r.reform is not None + ] + finally: + scorer.close() + + +@pytest.mark.parametrize( + "late_ask", + [("income_tax", 2024), ("age", 2024)], + ids=["a key it already asked", "a key it did not ask"], +) +def test_the_dry_run_refuses_a_reformed_simulation_asked_after_the_next_opens( + builder, fake_reforms, tmp_path, late_ask +) -> None: + """The scorer finishes a reformed simulation when the consumer opens the + next one and refuses it any further key, even one it already scored. The + dry run refuses the same consumer, so the release's plan fails before the + export instead of certification's scoring failing after it.""" + first = ParameterChangesReform({"gov.fixture.first": {"2024-01-01": 1}}) + second = ParameterChangesReform({"gov.fixture.second": {"2024-01-01": 2}}) + + def consumer(simulate): + records_only = getattr(simulate, RECORDS_REQUESTS_ONLY, False) is True + + def reformed(source): + return simulate( + source if records_only else build_post_export_reform(source) + ) + + first_simulation = reformed(first) + first_simulation.calculate("income_tax", 2024) + simulate(None).calculate("income_tax", 2024) + reformed(second).calculate("income_tax", 2024) + first_simulation.calculate(*late_ask) + + refusal = r"reformed simulation 0 for .* after opening reformed simulation 1\." + with pytest.raises(RuntimeError, match=refusal): + builder._record_post_export_request_descriptors("fixture", consumer) + with pytest.raises(RuntimeError, match=refusal): + builder._record_post_export_requests(consumer) + + scorer = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path) + try: + scoring = scorer.open_consumer("fixture", (("income_tax", 2024, None),)) + with pytest.raises(RuntimeError, match="asked a finished reform"): + consumer(scoring.simulate) + finally: + scorer.close() + + +class _Unreducible: + """A value whose pickling raises ``ValueError``, not ``PicklingError``.""" + + def __reduce__(self): + raise ValueError("fixture value refuses to be pickled") + + +def _undescribable_reform(kind: str, monkeypatch): + """(a reform the dry run must refuse, the message it must give).""" + + class BuiltReform: + pass + + spec = next( + spec + for spec in reform_validation_module.load_default_reform_specs(period=2024) + if spec.parameter_changes + ) + if kind == "built reform": + return BuiltReform(), "got a .*BuiltReform" + if kind == "subclass registered only in this process": + # It pickles here, by its module's name; a spawned worker, which has + # no such module, could not unpickle it. + module = types.ModuleType("registered_only_in_this_process") + exec( + "from microcosm.build.us_runtime.post_export_requests import " + "ParameterChangesReform\n" + "class RegisteredChanges(ParameterChangesReform):\n" + " pass\n", + module.__dict__, + ) + monkeypatch.setitem(sys.modules, module.__name__, module) + reform = module.RegisteredChanges({"gov.fixture": {"2024-01-01": 1}}) + pickle.dumps(reform) + return ( + reform, + r"got a registered_only_in_this_process\.RegisteredChanges\. .* exactly", + ) + if kind == "read-only mapping": + proxied = dataclasses.replace( + spec, parameter_changes=MappingProxyType(dict(spec.parameter_changes)) + ) + return proxied, "ReformValidationSpec reform description that cannot be pickled" + unreducible = dataclasses.replace( + spec, parameter_changes={"gov.fixture": {"2024-01-01": _Unreducible()}} + ) + return unreducible, "cannot be pickled .*ValueError: fixture value refuses" + + +@pytest.mark.parametrize( + "kind", + [ + "built reform", + "subclass registered only in this process", + "read-only mapping", + "value whose pickling raises ValueError", + ], +) +def test_the_dry_run_refuses_a_reform_it_cannot_describe( + builder, no_engine, monkeypatch, kind +) -> None: + """A worker rebuilds each reform from its description, so a consumer that + hands the dry run a built reform, or a description a worker might not + unpickle, fails the plan, which the release records and refuses before + the export, instead of recording a request no worker could run.""" + reform, message = _undescribable_reform(kind, monkeypatch) + + def consumer(simulate): + simulate(reform).calculate("income_tax", 2024) + + with pytest.raises(TypeError, match=message): + builder._record_post_export_requests(consumer) + with pytest.raises(TypeError, match=message): + builder._record_post_export_request_descriptors("fixture", consumer) + monkeypatch.setattr( + builder, + "_post_export_consumers", + lambda args, *, result, release_id: {"fixture": consumer}, + ) + plan = builder._record_post_export_scoring_plan( + _plan_args(), + n_households=7, + result=_empty_calibration_result(), + release_id=_RELEASE_ID, + ) + assert plan.error is not None + assert plan.error.startswith("TypeError") and re.search(message, plan.error) + assert plan.terminal_failures() + + +def test_a_request_rebuilds_its_reform_with_its_consumer_s_builder( + monkeypatch, +) -> None: + built: list[tuple[str, object]] = [] + monkeypatch.setattr( + smoke_module, "_build_reform", lambda probe: built.append(("probe", probe)) + ) + monkeypatch.setattr( + ReformValidationSpec, + "build_reform", + lambda spec: built.append(("spec", spec)), + ) + monkeypatch.setattr( + reform_validation_module, + "_build_parameter_reform", + lambda changes: built.append(("changes", changes)), + ) + probe = us_release_reform_coverage_probes()[0] + spec = reform_validation_module.load_default_reform_specs(period=2024)[0] + changes = {"gov.fixture.parameter": {"2026-01-01": 0}} + for reform in (probe, spec, ParameterChangesReform(changes)): + PostExportRequest( + consumer="fixture", + position=0, + variable="income_tax", + period=2026, + reform=reform, + reformed_simulation=0, + ).build_reform() + assert built == [("probe", probe), ("spec", spec), ("changes", changes)] + baseline = PostExportRequest( + consumer="fixture", position=0, variable="age", period=2024 + ) + assert baseline.build_reform() is None + assert baseline.key == ("age", 2024, None) + + +@pytest.mark.parametrize( + "fields, error, message", + [ + ({"reform": None, "reformed_simulation": 0}, ValueError, "reformed simulation"), + ({"reformed_simulation": None}, ValueError, "reformed simulation"), + ({"reformed_simulation": -1}, ValueError, "reformed_simulation"), + ({"reformed_simulation": True}, TypeError, "reformed_simulation"), + ({"reformed_simulation": np.int64(0)}, TypeError, "reformed_simulation"), + ({"reform": object()}, TypeError, "object"), + ({"position": -1}, ValueError, "position"), + ({"position": np.int64(0)}, TypeError, "position"), + ({"period": "2024"}, TypeError, "period"), + ({"period": True}, TypeError, "period"), + ({"map_to": ""}, ValueError, "map_to"), + ({"map_to": 5}, TypeError, "map_to"), + ({"consumer": ""}, ValueError, "consumer"), + ({"consumer": 5}, TypeError, "consumer"), + ({"variable": ""}, ValueError, "variable"), + ({"variable": None}, TypeError, "variable"), + ], +) +def test_a_request_refuses_inconsistent_fields(fields, error, message) -> None: + valid = { + "consumer": "fixture", + "position": 0, + "variable": "income_tax", + "period": 2026, + "map_to": None, + "reform": ParameterChangesReform({"gov.fixture": {"2026-01-01": 0}}), + "reformed_simulation": 0, + } + PostExportRequest(**valid) + with pytest.raises(error, match=message): + PostExportRequest(**{**valid, **fields}) + + +@pytest.mark.parametrize("changes", [{}, None, [("gov.fixture", 1)]]) +def test_parameter_changes_must_name_a_reform(changes) -> None: + """No changes is the baseline, which consumers ask for as ``None``.""" + with pytest.raises((TypeError, ValueError), match="parameter changes"): + ParameterChangesReform(changes) + + +def test_parameter_changes_that_cannot_be_copied_are_refused() -> None: + with pytest.raises(TypeError, match="parameter changes cannot be copied"): + ParameterChangesReform({"gov.fixture": {"2024-01-01": threading.Lock()}}) + + +def test_descriptors_cannot_be_hashed_and_keep_their_own_changes() -> None: + """Most reform descriptions hold dictionaries, so no descriptor hashes + (results are keyed by consumer and position), and a cumulative OBBBA + state keeps a copy of the payload the consumer handed the dry run.""" + changes = {"gov.fixture.parameter": {"2026-01-01": 0}} + reform = ParameterChangesReform(changes) + changes["gov.fixture.parameter"]["2026-01-01"] = 1 + changes["gov.fixture.other"] = {"2026-01-01": 2} + assert reform.parameter_changes == {"gov.fixture.parameter": {"2026-01-01": 0}} + baseline = PostExportRequest( + consumer="fixture", position=0, variable="age", period=2024 + ) + reformed = PostExportRequest( + consumer="fixture", + position=1, + variable="income_tax", + period=2026, + reform=reform, + reformed_simulation=0, + ) + for value in (baseline, reformed, reform): + with pytest.raises(TypeError, match="unhashable"): + hash(value) + # A read-only mapping cannot be pickled; the copy is a dict, which can. + proxied = ParameterChangesReform( + MappingProxyType({"gov.fixture.parameter": {"2026-01-01": 0}}) + ) + assert type(proxied.parameter_changes) is dict + assert pickle.loads(pickle.dumps(proxied)) == proxied == reform + + +def test_the_reform_alias_names_the_three_descriptions() -> None: + assert typing.get_args(PostExportReform.__value__) == ( + ReformCoverageProbe, + ReformValidationSpec, + ParameterChangesReform, + ) + + +#: SHA-256 of each output the post-export stages record, on the fixture frame +#: and fake engine below, with a calibration fit covering two in-sample JCT +#: reforms. Pinned from origin/main at fcabe4e65, before the dry run returned +#: descriptors. The digests also cover the shipped probes, reform specs, +#: baseline levels and holdout benchmarks, so a change to any of those moves +#: them too. Re-pin only when such an input or the fixture changed on purpose, +#: in the same pull request, by copying the digests this test's failure +#: prints. The manifests' ``post_export_scoring`` block, which holds the +#: method label and the batching, is not pinned here. +_RECORDED_OUTPUT_SHA256 = { + "calibration_diagnostics.build.post_export_scoring": ( + "7ed2a0dd088cf2d5a65e27e00368819cdf357160a5bdc2e42f079233d1f2f7b1" + ), + "reform_coverage_smoke": ( + "c2e6cbf63b02fc5dbbc1ddd5507edd5e9cfb21a41143469cc737c69279da9842" + ), + "reform_validation": ( + "e84481d7051f60570f7ba7bfafd0c631c4de5f19fb27ec2d50e8d7802689910e" + ), + "demographics": ( + "081adcc03922e4e3a7cf288f337fa28bd32511d4ca6626b3afed896edfa0d4c2" + ), + "ssi_social_security_holdout": ( + "b3d2db968bb3b10d004783ab7c080d6b4e376e4441e6753c05712bbd35c1a4b4" + ), + "medicare_irmaa_holdout": ( + "1962831f0fb368fdadd222e42310ca45a70effe214fe520c11a7f1f60d75337f" + ), +} + + +#: The reform passes the plan counts for each stage (its progress reporting +#: reads them), on the same fixture; also as on origin/main at fcabe4e65. +_PLANNED_REFORM_PASSES = { + "reform_coverage_smoke": 43, + "reform_validation": 64, + "demographics": 0, + "ssi_social_security_holdout": 0, + "medicare_irmaa_holdout": 0, +} + + +def _json_ready(value): + if isinstance(value, Mapping): + return {str(key): _json_ready(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_ready(item) for item in value] + if isinstance(value, np.ndarray): + return [_json_ready(item) for item in value.tolist()] + if isinstance(value, np.generic): + return value.item() + return value + + +def _sha256_of(value) -> str: + encoded = json.dumps(_json_ready(value), sort_keys=True, allow_nan=False) + return hashlib.sha256(encoded.encode()).hexdigest() + + +def _recorded_post_export_outputs(builder, tmp_path) -> dict[str, object]: + """What ``_main`` records: the plan, then each consumer through one scorer.""" + fit = _calibration_result_with_in_sample_fit(builder.PERIOD) + args = _plan_args() + plan = builder._record_post_export_scoring_plan( + args, n_households=7, result=fit, release_id=_RELEASE_ID + ) + assert plan.error is None + assert { + name: plan.planned_reform_passes(name) for name in plan.baseline_plans + } == _PLANNED_REFORM_PASSES + outputs: dict[str, object] = { + "calibration_diagnostics.build.post_export_scoring": plan.record() + } + scorer = _scorer(builder, _nested_frame(), _EngineLog(), 3, tmp_path) + try: + for name, consumer in builder._post_export_consumers( + args, result=fit, release_id=_RELEASE_ID + ).items(): + outputs[name] = builder._score_post_export_consumer( + name, + consumer, + dataset_path=scorer.dataset_path, + post_export_scorer=scorer, + baseline_plan=plan.baseline_plan(name), + maximum_microsim_batch_size=args.maximum_microsim_batch_size, + planned_reform_passes=plan.planned_reform_passes(name), + ) + finally: + scorer.close() + smoke = outputs["reform_coverage_smoke"] + outputs["reform_coverage_smoke"] = { + "name": smoke.name, + "passed": smoke.passed, + "failures": list(smoke.failures), + "details": smoke.details, + } + ages, weights = outputs["demographics"] + outputs["demographics"] = demographics_payload( + ages, weights, period=builder.PERIOD, release_id=_RELEASE_ID + ) + return outputs + + +def test_the_release_s_recorded_post_export_outputs_are_unchanged( + builder, fake_reforms, tmp_path +) -> None: + """The plan in ``calibration_diagnostics.json`` and every consumer's output + keep their bytes: the descriptors are returned, never recorded.""" + outputs = _recorded_post_export_outputs(builder, tmp_path) + assert list(outputs) == list(_RECORDED_OUTPUT_SHA256) + assert { + name: _sha256_of(output) for name, output in outputs.items() + } == _RECORDED_OUTPUT_SHA256 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index 1febf7e71d..e6ef80678c 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 @@ -4,6 +4,10 @@ import weakref from collections.abc import Iterator +from microcosm.build.us_runtime.post_export_requests import ( + ParameterChangesReform, + PostExportRequest, +) from microcosm.calibrate import DroppedConstraintMatrix from test_support.microcosm_build.us_post_export_scoring import * @@ -1650,29 +1654,35 @@ def test_guard_sweep_records_and_scores_shipped_reform_passes( "reform_validation": 75, "demographics": 1, } + # The sweep records the release's descriptors: each names its consumer and + # rebuilds its reform from the description the consumer recorded. + assert all(isinstance(request, PostExportRequest) for request in requests) + assert all(request.reform is not None for request in requests) smoke_requests = [ - request for request in requests if request[0] == "reform_coverage_smoke" - ] - assert [reform.label for _, reform, _ in smoke_requests] == [ - probe.id for probe in us_release_reform_coverage_probes() + request for request in requests if request.consumer == "reform_coverage_smoke" ] + assert [request.reform for request in smoke_requests] == list( + us_release_reform_coverage_probes() + ) validation_requests = [ - request for request in requests if request[0] == "reform_validation" + request for request in requests if request.consumer == "reform_validation" ] ordinary_specs = [ spec for spec in specs if not reform_validation_module._is_obbba_spec(spec) ] - assert {spec.id for spec in ordinary_specs}.issubset( - {reform.label for _, reform, _ in validation_requests} - ) + assert [ + request.reform + for request in validation_requests + if isinstance(request.reform, ReformValidationSpec) + ] == ordinary_specs obbba_specs = [ spec for spec in specs if reform_validation_module._is_obbba_spec(spec) ] - pre_baseline = reform_validation_module._merged_parameter_changes(obbba_specs) + pre_baseline = ParameterChangesReform( + reform_validation_module._merged_parameter_changes(obbba_specs) + ) pre_baseline_requests = [ - key - for _, reform, key in validation_requests - if reform.label == json.dumps(pre_baseline, sort_keys=True, default=str) + request.key for request in validation_requests if request.reform == pre_baseline ] obbba_groups = {(spec.budget_measure, spec.period) for spec in obbba_specs} assert {(key[0], key[1]) for key in pre_baseline_requests} == obbba_groups diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index 330060d03e..580076b900 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -378,6 +378,9 @@ # Reviewed held-out population-structure diagnostic over the written # H5; no population treatment. "population_structure_holdout.py", + # Picklable descriptions of the release's post-export scoring requests + # and the reforms they carry; reads no frame and treats no population. + "post_export_requests.py", "pregnancy.py", # Pinned-archive sidecar restore (PAW_TYP); no population treatment. "public_assistance_type_source.py", diff --git a/test_support/microcosm_build/post_export_request_worker.py b/test_support/microcosm_build/post_export_request_worker.py new file mode 100644 index 0000000000..52b752b6f5 --- /dev/null +++ b/test_support/microcosm_build/post_export_request_worker.py @@ -0,0 +1,28 @@ +"""What a spawned pool worker receives of the post-export requests sent to it. + +This module imports nothing beyond the standard library, so a spawned process +that runs it loads what unpickling the requests needs and whatever the parent's +main script imports (under pytest, not the release tool). The tests load the +release tool (``tools/build_us_fiscal_refresh_release.py``) by file path, +outside ``sys.modules``, so a type defined there cannot be unpickled in such a +process. +""" + +from __future__ import annotations + +import multiprocessing +import os + + +def requests_as_a_spawned_worker_receives_them(requests): + """Return the unpickled requests with where this process got their types.""" + types = {type(request) for request in requests} + types |= { + type(request.reform) for request in requests if request.reform is not None + } + return { + "requests": requests, + "process_id": os.getpid(), + "start_method": multiprocessing.get_start_method(), + "type_modules": sorted({kind.__module__ for kind in types}), + } diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index ec8896e639..bcf5f18636 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -359,10 +359,14 @@ population_structure_holdout_unavailable, write_population_structure_holdout, ) +from microcosm.build.us_runtime.post_export_requests import ( + RECORDS_REQUESTS_ONLY, + PostExportRequest, + check_post_export_reform, +) from microcosm.build.us_runtime.puf_capital_gains_tail import ( assert_puf_capital_gains_tail_survives_selection, ) -from microcosm.build.us_runtime.reform_coverage_smoke import RECORDS_REQUESTS_ONLY from microcosm.build.us_runtime.reform_validation import ( US_RELEASE_SPM_SELECTION, default_baseline_level_specs, @@ -5264,50 +5268,138 @@ def _post_export_values_and_weights(result, key: PostExportKey): class _RecordingPostExportSimulation: - """Engine-free stand-in that records the baseline keys a consumer asks for.""" + """Engine-free stand-in that records each key one simulation is asked for. + + ``asked`` is shared by every recorder of one dry run: it collects + ``(simulation, key)`` in the order of first asks, where ``simulation`` is + the reformed simulation's number, or ``None`` for the baseline. + ``reforms`` is the dry run's list of the reforms opened so far, also + shared, so a reformed simulation's recorder refuses every key once a later + one is opened, as the scorer refuses a finished ``_BatchedPostExportReform``. + """ - def __init__(self, keys: dict[PostExportKey, None] | None) -> None: - self._keys = keys + def __init__( + self, + asked: dict[tuple[int | None, PostExportKey], None], + simulation: int | None, + reforms: Sequence[object], + ) -> None: + self._asked = asked + self._simulation = simulation + self._reforms = reforms def calculate(self, variable, period=None, map_to=None) -> _PostExportValues: key = _post_export_key(variable, period, map_to) - if self._keys is not None: - self._keys.setdefault(key, None) + latest = len(self._reforms) - 1 + if self._simulation is not None and self._simulation != latest: + raise RuntimeError( + f"A post-export consumer asked reformed simulation " + f"{self._simulation} for {key} after opening reformed simulation " + f"{latest}. The scorer finishes a reformed simulation when the " + "consumer opens the next one and refuses it further keys, so a " + "consumer asks each reformed simulation for all its keys before " + "opening the next." + ) + self._asked.setdefault((self._simulation, key), None) return _PostExportValues(np.zeros(0), np.zeros(0)) -def _record_post_export_requests( +def _dry_run_post_export_requests( consumer: Callable[[Callable[[Any], Any]], object], -) -> tuple[tuple[PostExportKey, ...], int]: - """Learn a consumer's baseline keys and reform pass count from recorders. - - No engine is constructed: ``simulate(None)`` returns a recorder that - logs every baseline request, and each ``simulate(reform)`` a recorder of - its own. The consumers ask for the same keys whatever values they get - back, and the served baseline refuses any key this dry run did not see, - so a value-dependent request cannot slip past the plan. ``simulate`` - carries ``RECORDS_REQUESTS_ONLY``, so the reform-coverage smoke gate hands - it each probe instead of building the probe's reform, and the dry run - resolves no list edit against an engine. - - When the consumer runs for real, each key a reformed simulation is first - asked for is one batched pass (``_BatchedPostExportReform``), so the pass - count is the distinct keys asked of each reformed simulation, summed. - Progress reporting alone uses it: a consumer that runs more passes than - counted reports no outer counter on the extra ones. +) -> tuple[tuple[int | None, object, PostExportKey], ...]: + """Every request ``consumer`` makes, learned from engine-free recorders. + + Returns ``(simulation, reform, key)`` for each request, in the order the + serial scorer runs them: the baseline plan first (``reform`` and + ``simulation`` None; ``_ascending_period_plan`` order), then the reform + requests. When the consumer runs for real, each key a reformed simulation + is first asked for is one batched pass (``_BatchedPostExportReform``), so + the reform requests follow those first asks; ``simulation`` numbers the + consumer's ``simulate(reform)`` calls from 0. + + No engine is constructed: ``simulate(None)`` returns a recorder that logs + every baseline request, and each ``simulate(reform)`` a recorder of its + own. The consumers ask for the same keys whatever values they get back, + and the served baseline refuses any key this dry run did not see, so a + value-dependent request cannot slip past the plan. ``simulate`` carries + ``RECORDS_REQUESTS_ONLY``, so each consumer hands it the description it + builds a reform from instead of building the reform (the reform-coverage + smoke check's probe, a reform-validation spec or a cumulative OBBBA + state's parameter changes), and the dry run resolves no list edit against + an engine. A reform given as anything else is refused + (``check_post_export_reform``): a worker process could not rebuild it. + So is a key asked of a reformed simulation after the consumer opened the + next one, which the scorer refuses too (``_BatchedPostExportReform``). """ - keys: dict[PostExportKey, None] = {} - reform_keys: list[dict[PostExportKey, None]] = [] + asked: dict[tuple[int | None, PostExportKey], None] = {} + reforms: list[object] = [] def simulate(reform): if reform is None: - return _RecordingPostExportSimulation(keys) - reform_keys.append({}) - return _RecordingPostExportSimulation(reform_keys[-1]) + return _RecordingPostExportSimulation(asked, None, reforms) + check_post_export_reform(reform) + reforms.append(reform) + return _RecordingPostExportSimulation(asked, len(reforms) - 1, reforms) setattr(simulate, RECORDS_REQUESTS_ONLY, True) consumer(simulate) - return _ascending_period_plan(keys), sum(len(asked) for asked in reform_keys) + baseline = _ascending_period_plan( + key for simulation, key in asked if simulation is None + ) + return ( + *((None, None, key) for key in baseline), + *( + (simulation, reforms[simulation], key) + for simulation, key in asked + if simulation is not None + ), + ) + + +def _record_post_export_request_descriptors( + name: str, consumer: Callable[[Callable[[Any], Any]], object] +) -> tuple[PostExportRequest, ...]: + """Every request of the consumer ``name`` as a picklable descriptor. + + One ``PostExportRequest`` per request of the engine-free dry run + (``_dry_run_post_export_requests``), in the order the serial scorer runs + them, so a spawned worker process can run each request. The results are + the values each request calculates; a consumer's output also holds what + it reads off the reforms it builds itself (the smoke check records each + list-edit probe's resolved lists from its built reform), so rebuilding an + output means running the consumer again over the results. Nothing records + the descriptors: the plan in ``calibration_diagnostics.json`` keeps its + keys only. + """ + return tuple( + PostExportRequest( + consumer=name, + position=position, + variable=variable, + period=period, + map_to=map_to, + reform=reform, + reformed_simulation=simulation, + ) + for position, (simulation, reform, (variable, period, map_to)) in enumerate( + _dry_run_post_export_requests(consumer) + ) + ) + + +def _record_post_export_requests( + consumer: Callable[[Callable[[Any], Any]], object], +) -> tuple[tuple[PostExportKey, ...], int]: + """Learn a consumer's baseline keys and reform pass count from its dry run. + + The baseline keys are the plan the served baseline scores; the pass count + is the dry run's reform requests (``_dry_run_post_export_requests``). + Progress reporting alone uses the count: a consumer that runs more passes + than counted reports no outer counter on the extra ones. + """ + requests = _dry_run_post_export_requests(consumer) + baseline = tuple(key for simulation, _, key in requests if simulation is None) + return baseline, len(requests) - len(baseline) def _record_post_export_baseline_plan( diff --git a/tools/sweep_us_post_export_scoring.py b/tools/sweep_us_post_export_scoring.py index 11b2bf6aae..fd6ca50296 100644 --- a/tools/sweep_us_post_export_scoring.py +++ b/tools/sweep_us_post_export_scoring.py @@ -31,7 +31,13 @@ def _load_builder(): def _record_requests(builder): - """Record OBBBA stacks and validation's missing-estimate fallback passes.""" + """Record OBBBA stacks and validation's missing-estimate fallback passes. + + ``_record_post_export_request_descriptors`` returns each consumer's + requests from the release's engine-free dry run as picklable descriptors: + the baseline plans, and one reform request per reform pass, from which + each worker rebuilds the reforms it scores. + """ specs = builder.load_default_reform_specs(period=builder.PERIOD) def validation(simulate): @@ -50,32 +56,19 @@ def validation(simulate): } plans, requests = {}, [] for name, consume in consumers.items(): - baseline = {} - - class RecordingSimulation: - def __init__(self, reform, *, name=name, baseline=baseline): - self.reform = reform - self.name = name - self.baseline = baseline - self.keys = set() - - def calculate(self, variable, period=None, map_to=None): - key = builder._post_export_key(variable, period, map_to) - if self.reform is None: - self.baseline.setdefault(key, None) - elif key not in self.keys: - requests.append((self.name, self.reform, key)) - self.keys.add(key) - return builder._RecordingPostExportSimulation(None).calculate(*key) - - consume(RecordingSimulation) - plans[name] = builder._ascending_period_plan(baseline) + recorded = builder._record_post_export_request_descriptors(name, consume) + plans[name] = tuple( + request.key for request in recorded if request.reform is None + ) + requests.extend(request for request in recorded if request.reform is not None) counts = { - "smoke_probes": sum(name == "reform_coverage_smoke" for name, _, _ in requests), + "smoke_probes": sum( + request.consumer == "reform_coverage_smoke" for request in requests + ), "validation_specs": sum(not spec.in_sample for spec in specs), "in_sample_fallback_specs": sum(spec.in_sample for spec in specs), "validation_reform_passes": sum( - name == "reform_validation" for name, _, _ in requests + request.consumer == "reform_validation" for request in requests ), "baseline_keys": {name: len(plan) for name, plan in plans.items()}, } @@ -124,9 +117,9 @@ def _score_baselines(builder, scorer, path, plans): def _comparison_indices(requests): """Compare the first two reform passes of each consumer to a whole file.""" seen, selected = {}, set() - for index, (name, _, _) in enumerate(requests): - seen[name] = seen.get(name, 0) + 1 - if seen[name] <= 2: + for index, request in enumerate(requests): + seen[request.consumer] = seen.get(request.consumer, 0) + 1 + if seen[request.consumer] <= 2: selected.add(index) return selected @@ -138,7 +131,8 @@ def _score_reforms(builder, scorer, path, requests, start, count): comparisons = _comparison_indices(requests) compared = [] for index in range(start, min(start + count, len(requests))): - name, reform, key = requests[index] + request = requests[index] + name, reform, key = request.consumer, request.build_reform(), request.key observed = consumer.simulate(reform).calculate(*key) if index in comparisons: whole = default_simulate_factory(path)(reform)