diff --git a/changelog.d/uk-engine-read-year-window.changed.md b/changelog.d/uk-engine-read-year-window.changed.md new file mode 100644 index 0000000000..2417504ebf --- /dev/null +++ b/changelog.d/uk-engine-read-year-window.changed.md @@ -0,0 +1 @@ +UK build simulations now hold no year after the one they read. Given a one-year dataset, policyengine-uk (2.177.7) projects it to 2032, and every constructor runs the Universal Credit rebalancing loop over 2026-2032, working out `uc_LCWRA_element` and the arrays behind it for each year; the build reads only 2024 and 2025. Two UK helpers in `microcosm.frame.adapters.policyengine_uk` stop both: `uk_dataset_through` (policyengine-uk's own `extend_single_year_dataset` with `end_year`) and `uk_rebalancing_years_through` (a context manager that narrows `uc_reform.REBALANCING_YEARS` while one simulation is built and restores it after, on success or error). The spine adapter's `materialize` projects its dataset only to the period it reads, on its current-law parameters. The measure resolver in scratch mode, which the dense and national measure steps use, writes its scratch file as a multi-year H5 through its year and builds its main, annual-income and counterfactual simulations inside the loop cut. It projects on one current-law parameter tree per process, not one per resolver. Release scoring (a direct H5) keeps the whole projection, so policyengine-uk still checks every year of a finished file. Values do not change: a new engine test compares every requested output and every array each simulation and its baseline hold up to the year read, for 2024 data read at 2024 and at 2025 and 2025 data read at 2025, through both routes, on a synthetic frame where the health element is paid. Measured on a synthetic 80,000-household simulation of 2024 data read at 2025 (medians of three runs), construction falls from 12.1 to 2.1 seconds and peak memory from 4,981 to 3,152 MiB. Tests pin the source digests of `add_universal_credit_reform` and `_add_inactive_health_element_formula`, and that `REBALANCING_YEARS` is still a range. policyengine-uk now labels a projected year's CGT inputs "supplied" rather than "projected"; nothing in Microcosm reads that label. `uk_dataset_through` runs the one-year dataset's own `validate()` before it projects, because policyengine-uk runs that check only on a year it projects and a stage that reads its data's own year now projects nothing; a NaN in any column still raises policyengine-uk's own error. The check is a little stricter than the projection was: policyengine-uk drops `unused_pension_annual_allowance` from projected years and turns a NaN `student_loan_plan` into the string "nan" there, so a NaN in either now raises too. Microcosm writes the first never and the second with a plan or "NONE" on every row. `uk_dataset_through` refuses an end year before the data's year, so a scratch resolver whose year is before its frame's year now raises `ValueError`; no build does that. Two guards go with the cut. A resolver in scratch mode refuses a measure dated after its year (`cgt__*`, `company_car_benefit_`): policyengine-uk would answer it from the last year's inputs, with no error and with other values than a release gives. The loop cut holds a lock while its block is open, so a cut on another thread waits and cannot leave the range cut for the rest of the process; a block for another year inside an open block is refused, and so is a range that something else changed inside the block. Release scoring builds its simulations inside `uk_whole_rebalancing_years`, which waits for an open cut and refuses a `REBALANCING_YEARS` that is not the range the engine builds from its own first and last years. `frs_legacy_proxies` is the first UK stage whose implementation hash covers the adapter, and a node key includes its parents' keys, so that stage and every node after it, the dense and national steps included, re-key once; the six FRS stages before it keep their keys. diff --git a/changelog.d/us-engine-read-year-window.changed.md b/changelog.d/us-engine-read-year-window.changed.md new file mode 100644 index 0000000000..6bd17458b2 --- /dev/null +++ b/changelog.d/us-engine-read-year-window.changed.md @@ -0,0 +1 @@ +The PolicyEngine-US adapter's `materialize` now hands `Microsimulation` a dataset that holds the read year alone. Given a single-year dataset, policyengine-us 2.2.1 adds an uprated copy of every later year up to its last CPI-U year (2035), stores all twelve years' inputs, and copies all of them again into each branch it opens (federal itemization and some state taxes). `materialize` reads only the dataset's own year, so the adapter now stops the extension there (`extend_single_year_dataset(..., end_year=period)`). Values do not change: no policyengine-us formula reads a later year's data, and a test compares six variables, `household_net_income` among them, with the engine's default window. On the public populace-us 2024 file (57,240 households), process memory after the engine is built falls from 3.66 to 1.78 GiB; on 15,000 of its households, peak memory while computing `income_tax` falls from 10.47 to 8.74 GiB. Calculation time does not change. The adapter's source feeds the implementation hashes of the US post-transfer seed and materialize kernels, and a node key includes its parents' keys, so the seed and every node after it re-key once. The US release builder's in-build simulations, which read only 2024, now stop there too: its six in-build sites (the target frame, reform targets, ACA source inputs, Medicaid and SNAP eligibility, and the December SSI amounts) ask `_dataset_from_frame(..., period_only=True)` for the year alone (`us_dataset_through`). By default `_dataset_from_frame` keeps the engine's projection, as post-export scoring needs (its plans read years after 2025), so a new caller that reads a later year gets the engine's own projected inputs rather than inputs the engine carries forward or a formula-owned column read as zero. Tests pin the policyengine-us formulas that offset a period forward or look up a holder, each reviewed, and the policyengine-core rule that fills a period missing from a dataset, so an engine bump that adds or changes either fails until it is reviewed; the adapter test also compares every array both windows hold through 2024, in every branch. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 50942139aa..1c53bcf62a 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -232,6 +232,14 @@ 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. +- 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 + `PERIOD` alone instead: the six in-build sites (target frame, JCT reforms, + ACA source inputs, Medicaid, SNAP and December SSI) ask + `_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. diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py index 6af604504b..ef2cff31f5 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/measure_simulation.py @@ -2,6 +2,7 @@ from __future__ import annotations +import functools import json import warnings from collections.abc import Mapping @@ -87,6 +88,9 @@ from microcosm.frame import Frame, MassChangeRecord, Weights from microcosm.frame.adapters.policyengine_uk import ( frame_isa_income_contract, + uk_dataset_through, + uk_rebalancing_years_through, + uk_whole_rebalancing_years, validate_uc_claimant_input, ) @@ -479,6 +483,15 @@ def _cgt_model_measure(variable: str, default_year: int) -> tuple[str, int] | No return None +def _dated_measure_year(variable: str) -> int | None: + """The year a measure dated by its name is computed at, else None.""" + + match = UK_CGT_DATED_MEASURE.fullmatch(variable) + if match: + return int(match[1]) + return company_car_dated_benefit_year(variable) + + def _uc_calibration_composition( frame: Any, simulation: Any, year: int ) -> tuple[np.ndarray, np.ndarray]: @@ -1072,7 +1085,10 @@ def __init__( identifier_universe=engine_identifier_universe, ) write_uk_national_frame(engine_frame, source_path) + _project_scratch_engine_input(source_path, self.year) mode = "scratch_frame_export" + # The scratch engine holds no year after the resolver's. + simulation_end_year: int | None = self.year else: if self._engine_weight_scale is not None: raise ValueError( @@ -1087,12 +1103,16 @@ def __init__( dropped = () source_path = Path(simulation_source) mode = "direct_h5" + # A release is scored as users load it: policyengine-uk's whole + # projection and its checks on every year. + simulation_end_year = None if frame is None: frame, _provenance = load_uk_national_frame(source_path) self.frame = frame self._engine_scratch_dropped_columns = tuple(dropped) self._factory = factory self._source_path = source_path + self._simulation_end_year = simulation_end_year self._counterfactuals: dict[tuple[str, str | None], Any] = {} self._counterfactual_measures: dict[str, dict[str, Any]] = {} # The domestic energy measures, computed together on first read. @@ -1137,7 +1157,7 @@ def __init__( "DfE spring-term measures must not be persisted as source inputs: " f"{persisted_spring_term}" ) - self.simulation = factory(dataset=str(source_path)) + self.simulation = self._new_simulation() validate_uc_claimant_input(self.simulation, frame.table("person"), self.year) self.contract_targets = _uk_contract_targets() bound_cgt_periods = {} @@ -1340,7 +1360,34 @@ def entity_for(self, variable: str) -> str | None: return None return str(definition.entity.key) + def _refuse_dated_measure_after_window(self, variable: str) -> None: + """Refuse a measure dated after the last year a scratch engine holds. + + A scratch engine stops at the resolver's year: its dataset is projected + no further, and policyengine-uk's Universal Credit rebalancing loop + did not run for a later year. policyengine-uk still answers a read + there, from the last year's inputs, with other values than a release + gives. A direct H5 keeps the whole projection and answers every year. + :meth:`knows` still answers for the measure, so the refusal reaches + the operator with its reason, not as an unknown variable. + """ + + end_year = getattr(self, "_simulation_end_year", None) + if end_year is None: + return + measure_year = _dated_measure_year(variable) + if measure_year is not None and measure_year > end_year: + raise ValueError( + f"{variable} is measured in {measure_year}, but this resolver's " + f"scratch engine holds no year after {end_year}: the engine's " + "projection and its Universal Credit rebalancing loop stop " + "there, so the values would not be the ones a release gives. " + "Measure it from a direct H5 source, or with a resolver whose " + f"year is {measure_year} or later." + ) + def compute(self, entity: str, variable: str) -> tuple[np.ndarray, str]: + self._refuse_dated_measure_after_window(variable) if variable in UK_ANNUAL_INCOME_MEASURES: return self._annual_income_measure(entity, variable) if variable in UK_HOUSEHOLD_ENERGY_MEASURES: @@ -1389,6 +1436,7 @@ def counterfactual_delta( folded = binding.get("folded_into") folded = None if folded is None else str(folded) output = str(binding["output_variable"]) + self._refuse_dated_measure_after_window(output) entity = str(binding.get("from_entity") or "person") direction = str(binding.get("output_delta", "counterfactual_minus_baseline")) if direction not in ( @@ -1630,6 +1678,25 @@ def _dataset_year(self) -> int: return int(period) return self.year + def _new_simulation(self) -> Any: + """A new engine simulation of the resolver's source. + + In scratch mode the source holds the frame's year through the + resolver's year (:func:`_project_scratch_engine_input`), and + policyengine-uk's Universal Credit rebalancing loop stops at the + resolver's year while the simulation is built: the measures read no + later year, and :meth:`_refuse_dated_measure_after_window` refuses one + that would. A direct H5 keeps the engine's whole projection, and is + built where no cut of that loop is in force + (:func:`~microcosm.frame.adapters.policyengine_uk.uk_whole_rebalancing_years`). + """ + + if self._simulation_end_year is None: + with uk_whole_rebalancing_years(): + return self._factory(dataset=str(self._source_path)) + with uk_rebalancing_years_through(self._simulation_end_year): + return self._factory(dataset=str(self._source_path)) + def _annual_income_simulation(self) -> Any: """The simulation of each person's year, built once from the same source. @@ -1649,7 +1716,7 @@ def _annual_income_simulation(self) -> Any: if self._annual_income_simulation_cache is not None: return self._annual_income_simulation_cache person = self.frame.table("person") - simulation = self._factory(dataset=str(self._source_path)) + simulation = self._new_simulation() annual_inputs: dict[str, np.ndarray] = {} for name, share_column, other_column in _ANNUAL_INCOME_INPUTS: current = _values(self.simulation.calculate(name, self.year)).astype(float) @@ -1734,7 +1801,7 @@ def _counterfactual_simulation(self, zeroed: str, folded: str | None) -> Any: key = (zeroed, folded) if key in self._counterfactuals: return self._counterfactuals[key] - simulation = self._factory(dataset=str(self._source_path)) + simulation = self._new_simulation() amount = np.asarray(self.simulation.calculate(zeroed, self.year), dtype=float) if not np.isfinite(amount).all(): raise ValueError(f"{zeroed} must be finite to substitute it.") @@ -2056,6 +2123,42 @@ def _policyengine_uk_module() -> Any: return policyengine_uk +@functools.lru_cache(maxsize=1) +def _current_law_parameters() -> Any: + """policyengine-uk's current-law parameter tree, built once per process. + + The scratch projection only reads it. A ``CountryTaxBenefitSystem`` built + for each resolver cost time, and memory the process never got back, so + one tree serves every resolver. + """ + + return _policyengine_uk_module().CountryTaxBenefitSystem().parameters + + +def _project_scratch_engine_input(path: Path, end_year: int) -> None: + """Rewrite the one-year scratch H5 at ``path`` through ``end_year``. + + policyengine-uk projects a one-year file to its ``PROJECTION_END_YEAR`` + (2032) when it loads it. The measure step reads only the frame's year and + the resolver's, so the scratch file becomes a multi-year H5 of those years + alone, projected by policyengine-uk's own uprating on current-law + parameters (:func:`~microcosm.frame.adapters.policyengine_uk.uk_dataset_through`). + policyengine-uk loads a multi-year file as given. + """ + + from policyengine_uk.data import UKSingleYearDataset + + one_year = UKSingleYearDataset(file_path=str(path)) + projected = uk_dataset_through(one_year, end_year, _current_law_parameters()) + with warnings.catch_warnings(): + # PyTables warns once per table that a year ("2025") is no Python + # identifier; policyengine-uk's multi-year layout names tables so. + warnings.filterwarnings( + "ignore", message="object name is not a valid Python identifier" + ) + projected.save(str(path)) + + def _uk_contract_targets() -> dict[str, Any]: payload = ( importlib_resources.files("microcosm.build.uk") diff --git a/packages/microcosm-build/tests/engine/uk/test_uk_engine_year_window.py b/packages/microcosm-build/tests/engine/uk/test_uk_engine_year_window.py new file mode 100644 index 0000000000..f864385280 --- /dev/null +++ b/packages/microcosm-build/tests/engine/uk/test_uk_engine_year_window.py @@ -0,0 +1,463 @@ +"""policyengine-uk simulations in the build hold no year after the one read. + +Given a one-year dataset, policyengine-uk projects it to 2032 and every +constructor runs the Universal Credit rebalancing loop over 2026-2032. The +spine adapter and the measure resolver's scratch engines read only the +frame's year and the year they measure, so they stop the projection and the +loop there (``uk_dataset_through``, ``uk_rebalancing_years_through``). + +These tests build each simulation both ways on a synthetic frame where the +Universal Credit health element is paid, and compare every requested output +and every array the simulation and its baseline hold for a period up to the +year read. Release scoring (a direct H5) keeps the whole projection. + +Two guards go with the cut. A scratch resolver refuses a measure dated after +its year, which policyengine-uk would answer from the last year's inputs. A +direct H5 is built only where no cut of the loop is in force +(``uk_whole_rebalancing_years``). +""" + +from __future__ import annotations + +import hashlib +import inspect +from contextlib import nullcontext + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.uk_runtime import measure_simulation +from microcosm.build.uk_runtime.measure_simulation import UKMeasureResolver +from microcosm.build.uk_runtime.national_frame import uk_national_frame +from microcosm.frame import WeightKind +from microcosm.frame.adapters import policyengine_uk as adapter_module +from microcosm.frame.adapters.policyengine_uk import ( + PolicyEngineUKEngine, + uk_dataset_through, + uk_whole_rebalancing_years, +) +from test_support.microcosm_build.uk_engine_window import stub_scratch_engine_window + +#: The policyengine-uk sources the rebalancing cut rests on, hashed as +#: microcosm#1538's engine population declaration hashes its pins (the text +#: ``inspect.getsource`` returns). A new digest means policyengine-uk changed +#: the loop or the formula that reads its years: re-check the cut, then re-pin. +_REVIEWED_UC_REFORM_SOURCES = { + "add_universal_credit_reform": ( + "ca13079bb2043c8965dd2cc9397c13c58b7f98f8e58b2c678ab7602f72a55935" + ), + "_add_inactive_health_element_formula": ( + "8f20a36b13458b140caeb8d6f06f1fdad4bf0ba28d17a04f7f5b4a325b2ad907" + ), +} + +#: (the frame's year, the year read): the spine reads 2024 data at 2024 and +#: at 2025, and the measure step reads a 2024 or 2025 frame at 2025. +_CASES = [(2024, 2024), (2024, 2025), (2025, 2025)] + +_OUTPUTS = ( + "universal_credit", + "uc_LCWRA_element", + "income_tax", + "national_insurance", + "capital_gains_tax", + "pension_credit", + "child_benefit", + "state_pension", + "household_net_income", +) + + +def _frame(data_year: int): + """Eight people in seven households, invented for the test. + + Two working-age claimants have limited capability for work-related + activity, so their Universal Credit awards carry the health element the + rebalancing loop rewrites from 2026. The others pay income tax, capital + gains tax and National Insurance, draw pensions and Pension Credit, and + receive Child Benefit. + """ + + people = 8 + person = pd.DataFrame( + { + "person_id": np.arange(people, dtype=np.int64), + "person_benunit_id": np.asarray([0, 1, 2, 3, 3, 5, 6, 7], dtype=np.int64), + "person_household_id": np.asarray([0, 1, 2, 3, 3, 5, 6, 7], dtype=np.int64), + "age": [45.0, 38.0, 33.0, 29.0, 6.0, 72.0, 80.0, 51.0], + "employment_income": [ + 0.0, + 6_000.0, + 32_000.0, + 11_000.0, + 0.0, + 0.0, + 0.0, + 125_000.0, + ], + "self_employment_income": [0.0] * people, + "private_pension_income": [0.0] * 5 + [500.0, 38_000.0, 0.0], + "state_pension_reported": [0.0] * 5 + [7_000.0, 11_500.0, 0.0], + "uc_limited_capability_for_WRA": [True, True] + [False] * 6, + "capital_gains": [0.0, 0.0, 18_000.0] + [0.0] * 4 + [60_000.0], + "savings_interest_income": [0.0, 0.0, 1_200.0, 0.0, 0.0, 300.0] + + [2_000.0, 4_000.0], + "dividend_income": [0.0] * 7 + [15_000.0], + "pension_contributions_via_salary_sacrifice": [0.0, 0.0, 2_000.0] + + [0.0] * 4 + + [10_000.0], + "is_benunit_head": [True] * 4 + [False] + [True] * 3, + "is_parent": [False] * 3 + [True] + [False] * 4, + # Each adult's whole year at today's rates (the annual measures). + "employment_income_annual_share": [1.0] * people, + "employment_income_other_spells": [0.0] * people, + "self_employment_income_annual_share": [1.0] * people, + "self_employment_income_other_spells": [0.0] * people, + "private_pension_income_annual_share": [1.0] * people, + "contributory_benefits_annual_share": [1.0] * people, + } + ) + benunits = [0, 1, 2, 3, 5, 6, 7] + benunit = pd.DataFrame( + { + "benunit_id": np.asarray(benunits, dtype=np.int64), + "would_claim_uc": [True] * 4 + [False] * 3, + } + ) + household = pd.DataFrame( + { + "household_id": np.asarray(benunits, dtype=np.int64), + "household_weight": [1.0] * len(benunits), + "region": [ + "NORTH_EAST", + "WALES", + "LONDON", + "SCOTLAND", + "SOUTH_WEST", + "NORTH_WEST", + "SOUTH_EAST", + ], + "council_tax": [1_400.0, 1_500.0, 1_700.0, 1_300.0, 1_900.0] + + [2_100.0, 3_200.0], + "rent": [5_200.0, 0.0, 0.0, 5_600.0, 0.0, 0.0, 0.0], + "tenure_type": [ + "RENT_FROM_COUNCIL", + "OWNED_OUTRIGHT", + "OWNED_WITH_MORTGAGE", + "RENT_FROM_HA", + "OWNED_OUTRIGHT", + "OWNED_OUTRIGHT", + "OWNED_OUTRIGHT", + ], + "main_residence_value": [0.0, 180_000.0, 420_000.0, 0.0] + + [260_000.0, 310_000.0, 900_000.0], + } + ) + return uk_national_frame( + person=person, + benunit=benunit, + household=household, + time_period=str(data_year), + weight_kind=WeightKind.DESIGN, + ) + + +def _held(simulation, last_year: int) -> dict[tuple[str, str], np.ndarray]: + """Every array the simulation's default branch holds up to ``last_year``.""" + + from policyengine_core import periods + + held = {} + for population in simulation.populations.values(): + for name, holder in population._holders.items(): + for key, array in holder._memory_storage._arrays.items(): + branch, period_text = key.split(":", 1) + if branch != "default": + continue + if periods.period(period_text).start.year > last_year: + continue + held[(name, period_text)] = np.asarray(array) + return held + + +def _assert_same_up_to(today, cut, last_year: int, label: str) -> set: + """The two simulations hold the same arrays up to ``last_year``. + + A key one of them holds and the other does not is a value the other has + not computed yet; computed there, it must be the same. Returns those keys. + """ + + held_today = _held(today, last_year) + held_cut = _held(cut, last_year) + assert held_today and held_cut, label + for key in sorted(held_today.keys() & held_cut.keys()): + np.testing.assert_array_equal( + held_cut[key], held_today[key], err_msg=f"{label}: {key}" + ) + only_one = held_today.keys() ^ held_cut.keys() + for key in sorted(only_one): + held, other = (held_today, cut) if key in held_today else (held_cut, today) + np.testing.assert_array_equal( + np.asarray(other.calculate(*key)), held[key], err_msg=f"{label}: {key}" + ) + return only_one + + +def _today(monkeypatch) -> None: + """Restore policyengine-uk's own projection and loop, as before the cut.""" + + monkeypatch.setattr( + adapter_module, + "uk_dataset_through", + lambda dataset, end_year, parameters: dataset, + ) + monkeypatch.setattr( + adapter_module, "uk_rebalancing_years_through", lambda end_year: nullcontext() + ) + + +def _adapter_run(frame, data_year: int, read_year: int): + engine = PolicyEngineUKEngine() + simulations = [] + build = engine._read_year_simulation + + def recording(microsimulation_class, dataset, period): + simulation = build(microsimulation_class, dataset, period) + simulations.append(simulation) + return simulation + + engine._read_year_simulation = recording + outputs = engine.materialize( + frame, + [name for name in _OUTPUTS if name in engine._tax_benefit_system().variables], + read_year, + dataset_period=None if data_year == read_year else data_year, + ) + (simulation,) = simulations + return outputs, simulation + + +@pytest.mark.parametrize(("data_year", "read_year"), _CASES) +def test_the_adapter_cut_holds_what_the_whole_projection_holds( + monkeypatch, data_year, read_year +) -> None: + frame = _frame(data_year) + outputs, cut = _adapter_run(frame, data_year, read_year) + with monkeypatch.context() as patched: + _today(patched) + today_outputs, today = _adapter_run(frame, data_year, read_year) + + assert sorted(cut.dataset.years) == list(range(data_year, read_year + 1)) + assert sorted(today.dataset.years)[-1] > read_year + # The health element is paid, so the loop had awards to rewrite, and + # each programme the frame is built to reach pays someone. + assert (np.asarray(outputs["uc_LCWRA_element"]) > 0).sum() == 2 + for name in ("capital_gains_tax", "pension_credit", "child_benefit"): + assert np.asarray(outputs[name]).any(), name + assert outputs.keys() == today_outputs.keys() + for name, values in outputs.items(): + np.testing.assert_array_equal(values, today_outputs[name], err_msg=name) + extra = _assert_same_up_to(today, cut, read_year, "simulation") + extra |= _assert_same_up_to(today.baseline, cut.baseline, read_year, "baseline") + assert len(extra) <= 1, sorted(extra) + + +def _resolver_run(frame, read_year: int, scratch): + resolver = UKMeasureResolver( + simulation_source=None, scratch_dir=scratch, year=read_year, frame=frame + ) + measures = { + name: np.asarray(resolver.compute("person", name)[0]) + for name in ("income_tax", "employment_income_annual") + } + measures |= { + name: np.asarray(resolver.compute("benunit", name)[0]) + for name in ("universal_credit", "uc_LCWRA_element") + } + counterfactual = resolver._counterfactual_simulation( + "pension_contributions_via_salary_sacrifice", "employment_income" + ) + # The counterfactual is the one simulation the resolver changes after it + # is built, so outputs read on it are compared too, not only what it holds. + for name in ("income_tax", "universal_credit", "household_net_income"): + measures[f"counterfactual {name}"] = np.asarray( + counterfactual.calculate(name, read_year) + ) + measures["household_net_income"] = np.asarray( + resolver.simulation.calculate("household_net_income", read_year) + ) + simulations = { + "main": resolver.simulation, + "annual income": resolver._annual_income_simulation(), + "counterfactual": counterfactual, + } + return measures, simulations + + +@pytest.mark.parametrize(("data_year", "read_year"), _CASES) +def test_the_resolver_scratch_cut_holds_what_the_whole_projection_holds( + monkeypatch, tmp_path, data_year, read_year +) -> None: + from policyengine_uk.data import UKMultiYearDataset + + frame = _frame(data_year) + measures, cut = _resolver_run(frame, read_year, tmp_path / "cut") + scratch = tmp_path / "cut" / "simulation-input.h5" + assert UKMultiYearDataset.validate_file_path(str(scratch)) + assert sorted(UKMultiYearDataset(str(scratch)).years) == list( + range(data_year, read_year + 1) + ) + with monkeypatch.context() as patched: + stub_scratch_engine_window(patched) + today_measures, today = _resolver_run(frame, read_year, tmp_path / "today") + + assert (measures["uc_LCWRA_element"] > 0).sum() == 2 + # The substitution moves net income, so the counterfactual's outputs are + # its own and not the main simulation's. + assert not np.array_equal( + measures["counterfactual household_net_income"], + measures["household_net_income"], + ) + for name, values in measures.items(): + np.testing.assert_array_equal(values, today_measures[name], err_msg=name) + extra = set() + for label, simulation in cut.items(): + assert sorted(simulation.dataset.years) == list(range(data_year, read_year + 1)) + assert sorted(today[label].dataset.years)[-1] > read_year + extra |= _assert_same_up_to(today[label], simulation, read_year, label) + extra |= _assert_same_up_to( + today[label].baseline, simulation.baseline, read_year, f"{label} baseline" + ) + assert len(extra) <= 1, sorted(extra) + + +def test_a_direct_h5_keeps_the_whole_projection_and_loop(tmp_path) -> None: + from policyengine_uk.data import UKSingleYearDataset + from policyengine_uk.data.economic_assumptions import PROJECTION_END_YEAR + from policyengine_uk.scenarios import uc_reform + + frame = _frame(2024) + path = tmp_path / "release.h5" + measure_simulation.write_uk_national_frame(frame, path) + assert UKSingleYearDataset.validate_file_path(str(path), False) + resolver = UKMeasureResolver( + simulation_source=path, scratch_dir=tmp_path / "scratch", year=2025, frame=frame + ) + + assert sorted(resolver.simulation.dataset.years)[-1] == PROJECTION_END_YEAR + held = _held(resolver.simulation, PROJECTION_END_YEAR) + assert all( + ("uc_LCWRA_element", str(year)) in held for year in uc_reform.REBALANCING_YEARS + ) + # It holds the years after the resolver's, so it measures them. + gains, route = resolver.compute("person", "cgt_2026_gains") + assert route.startswith("engine_period:2026:") + assert np.asarray(gains).sum() > 0 + + +def test_a_scratch_resolver_refuses_a_measure_dated_after_its_year(tmp_path) -> None: + """policyengine-uk answers a year the scratch engine does not hold from the + last year's inputs, with no error, so the resolver refuses the read.""" + + frame = _frame(2024) + resolver = UKMeasureResolver( + simulation_source=None, scratch_dir=tmp_path, year=2025, frame=frame + ) + + for name in ("cgt_2026_gains", "company_car_benefit_2026"): + with pytest.raises(ValueError, match="holds no year after 2025"): + resolver.compute("person", name) + # The frame's year and the resolver's are held, and measured. + people = len(frame.table("person")) + for name in ("cgt_2024_gains", "cgt_2025_gains", "company_car_benefit_2024"): + values, _route = resolver.compute("person", name) + assert np.asarray(values).shape == (people,), name + assert np.asarray(resolver.compute("person", "cgt_2024_gains")[0]).sum() > 0 + + +def test_a_direct_h5_is_refused_while_a_rebalancing_cut_is_left( + monkeypatch, tmp_path +) -> None: + """A release is scored on the whole loop: a cut that anything left in the + process would shorten it with no error.""" + + from policyengine_uk.scenarios import uc_reform + + frame = _frame(2024) + path = tmp_path / "release.h5" + measure_simulation.write_uk_national_frame(frame, path) + first = uc_reform.FIRST_REBALANCING_YEAR + monkeypatch.setattr(uc_reform, "REBALANCING_YEARS", range(first, first)) + + with pytest.raises(RuntimeError, match="a cut was left"): + UKMeasureResolver( + simulation_source=path, + scratch_dir=tmp_path / "scratch", + year=2025, + frame=frame, + ) + + +def test_uk_dataset_through_builds_the_data_year_to_the_end_year() -> None: + engine = PolicyEngineUKEngine() + parameters = engine._tax_benefit_system().parameters + dataset = engine._build_dataset(_frame(2024), 2024) + + assert sorted(uk_dataset_through(dataset, 2024, parameters).years) == [2024] + assert sorted(uk_dataset_through(dataset, 2025, parameters).years) == [2024, 2025] + assert sorted(uk_dataset_through(dataset, 2027, parameters).years) == [ + 2024, + 2025, + 2026, + 2027, + ] + + +def test_a_nan_the_whole_projection_refuses_is_refused_at_the_data_year() -> None: + """policyengine-uk checks a dataset for NaN only on the years it projects. + A dataset read at its own year projects none, so the cut checks the year + itself: a NaN in a column the engine does not read, which its loader + ignores, raises as the whole projection raises it.""" + + from policyengine_uk import Microsimulation + from policyengine_uk.data.economic_assumptions import extend_single_year_dataset + + engine = PolicyEngineUKEngine() + parameters = engine._tax_benefit_system().parameters + dataset = engine._build_dataset(_frame(2024), 2024) + dataset.person["unread_note"] = np.nan + + with pytest.raises(ValueError, match="'unread_note' contains NaN"): + extend_single_year_dataset(dataset, parameters) + for end_year in (2024, 2025): + with pytest.raises(ValueError, match="'unread_note' contains NaN"): + uk_dataset_through(dataset, end_year, parameters) + # The spine adapter's route, at the data's own year. + with pytest.raises(ValueError, match="'unread_note' contains NaN"): + engine._read_year_simulation(Microsimulation, dataset, 2024) + + +def test_the_rebalancing_years_are_still_a_range_to_the_projection_end() -> None: + from policyengine_uk.data.economic_assumptions import PROJECTION_END_YEAR + from policyengine_uk.scenarios import uc_reform + + assert isinstance(uc_reform.REBALANCING_YEARS, range) + assert uc_reform.REBALANCING_YEARS == range( + uc_reform.FIRST_REBALANCING_YEAR, PROJECTION_END_YEAR + 1 + ) + # The whole-loop block reads both years off the loop's own module. + assert uc_reform.PROJECTION_END_YEAR == PROJECTION_END_YEAR + with uk_whole_rebalancing_years(): + pass + + +@pytest.mark.parametrize("name", sorted(_REVIEWED_UC_REFORM_SOURCES)) +def test_the_uc_reform_sources_are_the_reviewed_ones(name) -> None: + from policyengine_uk.scenarios import uc_reform + + source = inspect.getsource(getattr(uc_reform, name)) + assert ( + hashlib.sha256(source.encode("utf-8")).hexdigest() + == _REVIEWED_UC_REFORM_SOURCES[name] + ), f"policyengine-uk changed {name}; re-check the rebalancing cut, then re-pin." diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_cgt_observation_period.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_cgt_observation_period.py index 13382d72d8..543be883ab 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_cgt_observation_period.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_cgt_observation_period.py @@ -2,6 +2,7 @@ # ruff: noqa: F403, F405 from test_support.microcosm_build.uk_cgt_observation_period import * +from test_support.microcosm_build.uk_engine_window import stub_scratch_engine_window from test_support.microcosm_build.uk_local_rowwise import COMMITTED_BINDING_NOW @@ -18,6 +19,7 @@ def test_dated_cgt_fit_restores_base2024_values_with_fitted_weights( "_policyengine_uk_module", lambda: SimpleNamespace(__version__="test"), ) + stub_scratch_engine_window(monkeypatch) def resolver_factory(**kwargs): kwargs.setdefault("simulation_source", None) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_measure_simulation.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_measure_simulation.py index 8f4f41c0b2..6a762e5b93 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_measure_simulation.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_measure_simulation.py @@ -24,6 +24,7 @@ UK_ISA_INCOME_CONTRACT_ATTR, UK_LEGACY_ISA_INCOME_CONTRACT, ) +from test_support.microcosm_build.uk_engine_window import stub_scratch_engine_window class FrameStub: @@ -1162,6 +1163,7 @@ def test_employer_nics_are_a_measured_diagnostic(): def test_measure_resolver_direct_and_scratch_receipts(monkeypatch, tmp_path: Path): + projections = stub_scratch_engine_window(monkeypatch) created = [] class FakeMicrosimulation: @@ -1207,6 +1209,123 @@ def __init__(self, *, dataset): str(tmp_path / "input.h5"), str(tmp_path / "simulation-input.h5"), ] + # Only the scratch engine's file is projected, and only to the resolver's year. + assert projections == [("simulation-input.h5", 2025)] + + +def test_a_scratch_resolver_refuses_a_measure_dated_after_its_year( + monkeypatch, tmp_path: Path +): + """A scratch engine holds no year after the resolver's. policyengine-uk + would still answer a later year from the last year's inputs, so a measure + dated there is refused, not read. A direct H5 keeps every year.""" + + stub_scratch_engine_window(monkeypatch) + sim = SimulationStub( + { + "capital_gains": ("person", np.array([3000.0, 5000.0, 20000.0])), + "capital_gains_tax": ("person", np.array([0.0, 400.0, 3400.0])), + "company_car_benefit": ("person", np.array([0.0, 900.0, 3_000.0])), + } + ) + monkeypatch.setitem( + sys.modules, + "policyengine_uk", + SimpleNamespace(__version__="9.9.9", Microsimulation=lambda *, dataset: sim), + ) + monkeypatch.setattr( + measure_simulation, "write_uk_national_frame", lambda frame, path: path + ) + scratch = UKMeasureResolver( + simulation_source=None, + scratch_dir=tmp_path, + year=2025, + frame=ReleaseIdentifierFrameStub(), + ) + direct = UKMeasureResolver( + simulation_source=tmp_path / "input.h5", + scratch_dir=tmp_path, + year=2025, + frame=ReleaseIdentifierFrameStub(), + ) + sim.calls.clear() + + for name in ("cgt_2026_gains", "cgt_2030_tax", "company_car_benefit_2026"): + assert scratch.knows("person", name) + with pytest.raises(ValueError, match="holds no year after 2025"): + scratch.compute("person", name) + with pytest.raises(ValueError, match="holds no year after 2025"): + scratch.counterfactual_delta( + { + "kind": "input_substitution_counterfactual", + "zeroed_input": "pension_contributions_via_salary_sacrifice", + "folded_into": "employment_income", + "output_variable": "cgt_2026_tax", + }, + 2025, + ) + # A refused measure reads nothing from the engine. + assert sim.calls == [] + + # The years the scratch engine holds are measured as before. + for name, year in ( + ("cgt_2024_gains", 2024), + ("cgt_2025_gains", 2025), + ("company_car_benefit_2025", 2025), + ): + _, route = scratch.compute("person", name) + assert route.startswith(f"engine_period:{year}:") + # A direct H5 keeps the whole projection, so it measures a later year. + _, route = direct.compute("person", "cgt_2026_gains") + assert route == "engine_period:2026:capital_gains:native" + _, route = direct.compute("person", "company_car_benefit_2026") + assert route == "engine_period:2026:company_car_benefit:native" + + +def test_scratch_projections_share_one_current_law_parameter_tree( + monkeypatch, tmp_path: Path +): + """Each scratch resolver used to build a CountryTaxBenefitSystem only to + read its parameters. One tree now serves every projection in a process.""" + + systems = [] + + class CountryTaxBenefitSystem: + def __init__(self): + systems.append(self) + self.parameters = SimpleNamespace(system=len(systems)) + + projections = [] + + def through(dataset, end_year, parameters): + projections.append((dataset.file_path, end_year, parameters)) + return SimpleNamespace(save=lambda path: None) + + monkeypatch.setattr( + measure_simulation, + "_policyengine_uk_module", + lambda: SimpleNamespace(CountryTaxBenefitSystem=CountryTaxBenefitSystem), + ) + monkeypatch.setattr(measure_simulation, "uk_dataset_through", through) + monkeypatch.setitem( + sys.modules, + "policyengine_uk.data", + SimpleNamespace( + UKSingleYearDataset=lambda file_path: SimpleNamespace(file_path=file_path) + ), + ) + measure_simulation._current_law_parameters.cache_clear() + try: + for name in ("first.h5", "second.h5"): + measure_simulation._project_scratch_engine_input(tmp_path / name, 2025) + finally: + measure_simulation._current_law_parameters.cache_clear() + + assert len(systems) == 1 + assert projections == [ + (str(tmp_path / "first.h5"), 2025, systems[0].parameters), + (str(tmp_path / "second.h5"), 2025, systems[0].parameters), + ] def test_scratch_engine_input_leaves_property_wealth_to_the_engine( @@ -1216,6 +1335,7 @@ def test_scratch_engine_input_leaves_property_wealth_to_the_engine( sum of the three property components and is never uprated, so the scratch H5 the calibration engine loads drops it, as the release export does. The resolver's own frame keeps it, and the receipt names what was left out.""" + stub_scratch_engine_window(monkeypatch) from microcosm.build.uk_runtime.national_frame import uk_national_frame @@ -1556,6 +1676,7 @@ def test_scratch_engine_input_leaves_the_native_alias_codes_behind( so the scratch export the engine loads drops them like the release export does. The first K=25 dense build from main (2026-10-04) failed on exactly this at ``uk.full.measures``.""" + stub_scratch_engine_window(monkeypatch) loaded = [] class FakeMicrosimulation: @@ -1599,6 +1720,7 @@ def __init__(self, *, dataset): def test_scratch_engine_input_without_aliases_is_the_frame_itself( monkeypatch, tmp_path ): + stub_scratch_engine_window(monkeypatch) monkeypatch.setitem( sys.modules, "policyengine_uk", @@ -1791,6 +1913,7 @@ def test_engine_scratch_frame_scales_household_weights_for_the_engine_only(): def test_resolver_writes_the_scaled_engine_frame_and_records_the_scale( monkeypatch, tmp_path: Path ): + stub_scratch_engine_window(monkeypatch) created = [] class FakeMicrosimulation: diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_measurement_period_routes.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_measurement_period_routes.py index 2459f61a0b..34a2ed05ca 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_measurement_period_routes.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_measurement_period_routes.py @@ -21,6 +21,7 @@ from microcosm.build.uk_runtime.national_frame import uk_national_frame from microcosm.calibrate import TargetRegistry, TargetSpec from microcosm.frame import WeightKind +from test_support.microcosm_build.uk_engine_window import stub_scratch_engine_window STORED = np.array([100.0, 0.0, 200.0]) GROWTH = 1.034 @@ -105,6 +106,7 @@ def test_both_routes_measure_the_stored_value_at_the_calibration_period( "_policyengine_uk_module", lambda: SimpleNamespace(__version__="test"), ) + stub_scratch_engine_window(monkeypatch) def resolver_factory(**kwargs): kwargs.setdefault("simulation_source", None) 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 01f8de7da1..a39d843e6e 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 @@ -11178,7 +11178,10 @@ def fake_dataset_from_frame( zero_variables=(), system=None, assert_no_formula_owned_columns=True, + period_only=False, ): + # The base simulation and the reform read PERIOD alone. + assert period_only datasets.append( ( frame_arg, @@ -15529,6 +15532,7 @@ def fake_dataset_from_frame( zero_variables=(), system=None, assert_no_formula_owned_columns=True, + period_only=False, ): return {"frame": frame_arg, "zero_variables": tuple(zero_variables)} 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 02e047a902..c45b8db3a4 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 @@ -1885,3 +1885,28 @@ def spy(probe): assert { (probe.budget_measure, int(probe.period or builder.PERIOD)) for probe in probes } <= {(variable, period) for variable, period, _ in keys} + + +def test_scorer_dataset_keeps_the_engine_projection( + builder, monkeypatch, tmp_path +) -> None: + """Consumer plans read years after PERIOD, so the scorer's default + dataset keeps policyengine-us's projection: it does not ask for PERIOD + alone, as the in-build simulations do.""" + calls: list[dict[str, object]] = [] + + def recording_dataset_from_frame(frame, **kwargs): + calls.append(kwargs) + return frame + + monkeypatch.setattr(builder, "_dataset_from_frame", recording_dataset_from_frame) + scorer = builder._HouseholdBatchedPostExportScorer( + _written_h5(tmp_path), + maximum_microsim_batch_size=3, + microsimulation_cls=_fake_engine(_EngineLog()), + load_frame=lambda path, *, expected_sha256: _nested_frame(), + ) + first_batch = scorer._batches()[0] + + assert scorer._dataset_from_frame(first_batch) is first_batch + assert calls == [{"assert_no_formula_owned_columns": False}] diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_batched_target_materialization.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_batched_target_materialization.py index ffdd302815..21e4f2263d 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_batched_target_materialization.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_batched_target_materialization.py @@ -272,3 +272,145 @@ def test_population_aggregate_list_matches_installed_engine_sources() -> None: assert triaged_digest == ( "f26eb560e474207fc1fa1d8828b62ba4791fb763089ea2ce7a85b57a259f2755" ), triaged_digest + + +def test_forward_reads_match_the_reviewed_engine_sources() -> None: + """Pin the formulas that may read a later period than the one asked. + + In-build simulations hold PERIOD alone, and the adapter holds the read + year alone, so a formula that read a later year's stored data would get + nothing there. The scan marks forward period offsets and holder lookups in + US Variable classes and the helpers they call. Each one found is reviewed + here and its source is pinned, so an engine that adds or changes one fails + until it is reviewed. It is a tripwire, not a proof. + """ + source_digests = {} + found = _engine_forward_read_sources(source_digests=source_digests) + reviewed = { + # The offset dates a parameter lookup, not a data read. + "sc_cdcc_potential": {".offset(max_decoupled_year_offset"}, + "md_dependent_care_subtraction": {".offset(max_decoupled_year_offset"}, + # The twelve months of the year asked. + "tx_ceap_eligible": {".offset(month_offset"}, + # The holder is read only at the period asked. + "has_tin": {"get_holder(", "get_known_periods(", "get_array("}, + # The holder gives the filing-status enum, not a stored value. + "gross_medicare_part_b_premium": {"get_holder("}, + # The holder sets an input at the period asked, on a branch. + "tob_revenue_oasdi": {"get_holder("}, + "tob_revenue_medicare_hi": {"get_holder("}, + # Over a dataset, county returns its last stored year's array when the + # year asked holds none. A dataset that holds county holds it at the + # year the build reads, so that read never reaches the lookup. + "county": {"get_holder(", "get_known_periods(", "get_array("}, + } + assert {name: set(evidence) for name, evidence in found.items()} == reviewed + reviewed_digest = hashlib.sha256( + "\n".join(f"{name}:{source_digests[name]}" for name in sorted(reviewed)).encode() + ).hexdigest() + assert reviewed_digest == ( + "4c3a61a320e3d7d57f887ba3a364293d59b9cc363e2e38e7aecd8fac13409d5e" + ), reviewed_digest + + +def test_core_fills_a_missing_period_only_from_earlier_ones() -> None: + """policyengine-core fills an input missing at the period asked from the + latest earlier stored period (uprated), or carries the last stored period + over only when it is not later than the period asked; a later one gives + the default. So a dataset cut at the year read and the engine's projection + agree at that year. A new digest means core changed the rule (in + ``Simulation._calculate``): re-check the cut, then re-pin.""" + import inspect + + from policyengine_core.simulations import Simulation + + source = inspect.getsource(Simulation._calculate) + assert hashlib.sha256(source.encode()).hexdigest() == ( + "3a36c798f58eced1d61812cd374997ac1732fa1a1beaff74ba6b7e6588aa3269" + ) + + +def test_in_build_datasets_hold_period_alone_and_match_the_projection( + monkeypatch, +) -> None: + """In-build simulations read only PERIOD, so they ask for datasets that + stop there; by default a dataset keeps policyengine-us's projection. + + Values must match policyengine-us's own projection to later years: the + target frame with one JCT reform family (a reform system on the cut + dataset), the ACA source inputs, Medicaid and SNAP eligibility, and + December SSI amounts. + """ + from policyengine_us.data import USMultiYearDataset, USSingleYearDataset + + builder = _load_builder_module() + # One real family stands for the others: each neutralizes one deduction + # on the same reform path. + (salt,) = ( + reform + for reform in builder.US_JCT_TAX_EXPENDITURE_REFORMS + if reform.neutralized_variable == "salt_deduction" + ) + monkeypatch.setattr(builder, "US_JCT_TAX_EXPENDITURE_REFORMS", (salt,)) + frame = _real_engine_frame() + cut = builder._dataset_from_frame( + frame, assert_no_formula_owned_columns=False, period_only=True + ) + projected = builder._dataset_from_frame(frame, assert_no_formula_owned_columns=False) + assert isinstance(cut, USMultiYearDataset) + assert cut.years == [builder.PERIOD] + assert isinstance(projected, USSingleYearDataset) + + targets = ( + _soi("agi_amount", "adjusted_gross_income"), + _soi("wages", "employment_income"), + _population_age("pop_18_to_65", 18, 65), + _variable("snap_amount", base_variable="snap"), + _variable("ssi_recipients", base_variable="ssi", measure_mode="indicator_sum"), + _spec("ca_state_income_tax", "state_income_tax", {"state_fips": "06"}), + _spec("md_state_income_tax", "state_income_tax", {"state_fips": "24"}), + _spec("eitc", "fixture"), + _spec("jct_salt", "jct", measure=salt.measure), + ) + + def run() -> dict[str, object]: + target_frame, _, compilation = builder._materialize_target_frame(frame, targets) + batching = compilation["target_materialization_batching"] + assert batching["jct_reform_families_simulated"] == 1 + return { + "targets": target_frame.table("household"), + "aca": builder._aca_source_tax_unit_table(frame, {}), + "medicaid": builder._medicaid_person_eligibility(frame), + "snap": builder._snap_spm_unit_eligibility(frame), + "ssi": builder._ssi_person_uncapped_amount(frame), + } + + dataset_from_frame = builder._dataset_from_frame + asked: list[bool] = [] + + def recording(*args, **kwargs): + asked.append(kwargs.get("period_only", False)) + return dataset_from_frame(*args, **kwargs) + + def projecting(*args, **kwargs): + # The in-build sites ask for PERIOD alone; give them the projection. + return dataset_from_frame(*args, **{**kwargs, "period_only": False}) + + monkeypatch.setattr(builder, "_dataset_from_frame", recording) + with_cut = run() + # Every site run here asked for PERIOD alone: the target frame, the JCT + # reform, the ACA source inputs, Medicaid, SNAP and December SSI. + assert len(asked) >= 6 and all(asked), asked + monkeypatch.setattr(builder, "_dataset_from_frame", projecting) + with_projection = run() + + assert with_cut["targets"]["income_tax"].to_numpy().any() + assert salt.measure in with_cut["targets"].columns + for name in ("targets", "aca"): + pd.testing.assert_frame_equal( + with_cut[name], with_projection[name], check_exact=True, obj=name + ) + for name in ("medicaid", "snap", "ssi"): + np.testing.assert_array_equal( + with_cut[name], with_projection[name], err_msg=name + ) 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 74f767dc36..7721dc0c67 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 @@ -150,7 +150,8 @@ def smoke(simulate): (first_batch, _) = scorer._batches() engine = Microsimulation( dataset=builder._dataset_from_frame( - first_batch, assert_no_formula_owned_columns=False + first_batch, + assert_no_formula_owned_columns=False, ), spm=dict(US_RELEASE_SPM_SELECTION), ) diff --git a/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_uk.py b/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_uk.py index 7a28f03f49..a5c3942bc1 100644 --- a/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_uk.py +++ b/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_uk.py @@ -8,7 +8,10 @@ from __future__ import annotations import json -from collections.abc import Mapping, Sequence +import sys +import threading +from collections.abc import Iterator, Mapping, Sequence +from contextlib import contextmanager from importlib import metadata from pathlib import Path from types import MappingProxyType @@ -39,8 +42,11 @@ "UK_SCHEMA", "frame_isa_income_contract", "frame_savings_income_projection", + "uk_dataset_through", "uk_isa_income_contract_from", + "uk_rebalancing_years_through", "uk_savings_income_projection_from", + "uk_whole_rebalancing_years", "validate_uc_claimant_input", ] @@ -171,6 +177,165 @@ def frame_savings_income_projection(bundle: Frame) -> str: return uk_savings_income_projection_from(declared) +def uk_dataset_through(dataset: Any, end_year: int | str, parameters: Any) -> Any: + """A one-year ``UKSingleYearDataset`` projected only to ``end_year``. + + policyengine-uk's ``Simulation`` projects a one-year dataset (an object, + or a path to a one-year H5) with its own uprating to + ``PROJECTION_END_YEAR`` (2032) and holds every year, whatever years the + caller reads. ``extend_single_year_dataset`` with ``end_year`` returns + that projection from the dataset's year through ``end_year`` alone, as a + ``UKMultiYearDataset``, which ``Simulation`` takes as given. + policyengine-uk builds each year only from earlier years, so the kept + years are the ones the full projection holds. ``parameters`` is the + parameter tree the uprating reads: current law in a build. + + The dataset's own ``validate()`` runs first. policyengine-uk runs it only + on the years it projects, so a dataset read at its own year, which + projects nothing, would go unchecked: a NaN in a column the engine does + not read would pass, where the whole projection refuses it. + """ + + from policyengine_uk.data.economic_assumptions import extend_single_year_dataset + + end_year = int(end_year) + data_year = int(str(dataset.time_period)[:4]) + if end_year < data_year: + raise ValueError( + f"end_year {end_year} is before the dataset's year {data_year}; " + "policyengine-uk projects a dataset forward only." + ) + dataset.validate() + return extend_single_year_dataset(dataset, parameters, end_year=end_year) + + +#: One cut of policyengine-uk's rebalancing loop at a time. The cut patches the +#: engine's module, which every thread reads, so a second thread waits here +#: until the first has restored the installed range. +_REBALANCING_LOCK = threading.RLock() +#: The cut in force, empty when there is none: the range the engine had +#: installed, the end year, the cut range, and how many open blocks share it. +_REBALANCING_CUT: dict[str, Any] = {} + + +@contextmanager +def uk_rebalancing_years_through(end_year: int | str) -> Iterator[range]: + """Run policyengine-uk's Universal Credit rebalancing loop only to ``end_year``. + + Every policyengine-uk constructor runs ``add_universal_credit_reform`` + (``scenarios/uc_reform.py``). For each year of the module's + ``REBALANCING_YEARS``, 2026 to ``PROJECTION_END_YEAR``, it computes + ``uc_LCWRA_element`` and the arrays behind it, whatever years the dataset + holds. Inside the block that range stops at ``end_year`` (it is empty for + 2024 and 2025), and it never gains a year. On exit, on success or on error, + the installed range is restored. The range is built from + ``PROJECTION_END_YEAR`` when the module is imported, so a patch of that + constant would not reach the loop. + + The patch is process-wide, so one cut is in force at a time. A block on + another thread waits until this one has restored the range. A block + opened inside this one on the same thread shares the cut when it names + the same year, and the range is restored when the last of them exits, + whatever the order; one that names another year is refused, since its + simulation would get this block's loop. A range that something else + changed inside the block is refused on exit, after the installed one is + restored: the simulation may not have run the loop it asked for. + """ + + from policyengine_uk.scenarios import uc_reform + + end_year = int(end_year) + with _REBALANCING_LOCK: + cut = _REBALANCING_CUT + if not cut: + installed = uc_reform.REBALANCING_YEARS + if not isinstance(installed, range) or installed.step != 1: + raise TypeError( + "policyengine-uk's uc_reform.REBALANCING_YEARS is no longer a " + f"range of consecutive years ({installed!r}); review the " + "rebalancing cut against the installed engine." + ) + years = range(installed.start, min(installed.stop, end_year + 1)) + uc_reform.REBALANCING_YEARS = years + cut.update(installed=installed, end_year=end_year, years=years, blocks=0) + elif cut["end_year"] != end_year: + raise RuntimeError( + "policyengine-uk's rebalancing loop is cut at " + f"{cut['end_year']} for a simulation that is being built; a " + f"simulation through {end_year} cannot be built inside that " + "block, because the cut is process-wide." + ) + years = cut["years"] + cut["blocks"] += 1 + found: Any = years + try: + yield years + finally: + cut["blocks"] -= 1 + if not cut["blocks"]: + found = uc_reform.REBALANCING_YEARS + uc_reform.REBALANCING_YEARS = cut["installed"] + cut.clear() + if not (isinstance(found, range) and found == years): + raise RuntimeError( + "policyengine-uk's uc_reform.REBALANCING_YEARS changed inside the " + f"rebalancing cut at {end_year}: something else set it to " + f"{found!r}. The installed range is restored, but the simulation " + "built in the block may not have run the loop it asked for." + ) + + +@contextmanager +def uk_whole_rebalancing_years() -> Iterator[None]: + """Build a simulation that needs policyengine-uk's whole rebalancing loop. + + A simulation built outside :func:`uk_rebalancing_years_through` runs the + Universal Credit rebalancing loop over the range the engine's module holds + at that moment. A release is scored as users load it, on every year of + that range, so its simulation is built inside this block, where no cut is + in force: a cut on another thread is waited for and none starts before the + block exits, and a cut open on this thread is refused. A loaded engine + module whose range is not the one policyengine-uk builds from its own + ``FIRST_REBALANCING_YEAR`` and ``PROJECTION_END_YEAR`` is refused too, so + a cut that anything left in the process cannot shorten the loop without an + error. An engine module that was never imported still has its own range. + """ + + with _REBALANCING_LOCK: + if _REBALANCING_CUT: + raise RuntimeError( + "policyengine-uk's rebalancing loop is cut at " + f"{_REBALANCING_CUT['end_year']} for a simulation that is being " + "built; a simulation that needs the whole loop cannot be built " + "inside that block." + ) + uc_reform = sys.modules.get("policyengine_uk.scenarios.uc_reform") + if uc_reform is not None: + installed = getattr(uc_reform, "REBALANCING_YEARS", None) + first = getattr(uc_reform, "FIRST_REBALANCING_YEAR", None) + last = getattr(uc_reform, "PROJECTION_END_YEAR", None) + if ( + not isinstance(installed, range) + or type(first) is not int + or type(last) is not int + ): + raise TypeError( + "policyengine-uk's uc_reform no longer builds REBALANCING_YEARS " + "as a range from FIRST_REBALANCING_YEAR to PROJECTION_END_YEAR " + f"({installed!r}, {first!r}, {last!r}); review the rebalancing " + "cut against the installed engine." + ) + if installed != range(first, last + 1): + raise RuntimeError( + "policyengine-uk's uc_reform.REBALANCING_YEARS is " + f"{installed!r}, not the engine's own " + f"{range(first, last + 1)!r}: a cut was left in this process. " + "A simulation built now would skip the Universal Credit " + "rebalancing loop in the missing years." + ) + yield + + _PERSON_TABLE = "person" _GROUP_TABLES = ("benunit", "household") _DTYPE_KIND_BY_VALUE_TYPE: dict[type, str] = { @@ -261,6 +426,9 @@ def materialize( ``dataset_period`` where they belong to an earlier year: the dataset is then stamped with that year and policyengine-uk projects it forward to ``period`` as it does a released file (``extend_single_year_dataset``). + + The simulation reads only ``period``, so it holds no later year + (:meth:`_read_year_simulation`). """ microsimulation_class = self._import_policyengine_uk().Microsimulation @@ -272,7 +440,7 @@ def materialize( dataset = self._build_dataset( bundle, period if dataset_period is None else dataset_period ) - simulation = microsimulation_class(dataset=dataset) + simulation = self._read_year_simulation(microsimulation_class, dataset, period) validate_uc_claimant_input(simulation, bundle.table("person"), period) results: dict[str, np.ndarray] = {} for name in variables: @@ -309,6 +477,26 @@ def write_dataset( "write_uk_national_frame." ) + def _read_year_simulation( + self, microsimulation_class: Any, dataset: Any, period: int | str + ) -> Any: + """A simulation of a one-year ``dataset`` that holds no year after ``period``. + + The dataset's year through ``period`` is projected by policyengine-uk's + own uprating on the adapter's current-law parameters + (:func:`uk_dataset_through`), and the Universal Credit rebalancing + loop stops at ``period`` while the simulation is built + (:func:`uk_rebalancing_years_through`). A later year would change no + value at ``period``: policyengine-uk builds each year only from + earlier ones. + """ + + projected = uk_dataset_through( + dataset, period, self._tax_benefit_system().parameters + ) + with uk_rebalancing_years_through(period): + return microsimulation_class(dataset=projected) + def _import_policyengine_uk(self) -> Any: try: import policyengine_uk diff --git a/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py b/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py index 7094fe1800..268e5fc9e9 100644 --- a/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py +++ b/packages/microcosm-frame/src/microcosm/frame/adapters/policyengine_us.py @@ -932,9 +932,11 @@ def materialize( ) -> Mapping[str, np.ndarray]: """Compute ``variables`` for ``period`` with a Microsimulation. - Builds a ``USSingleYearDataset`` from the bundle's entity tables + Builds a dataset for ``period`` from the bundle's entity tables (with the bundle's household weights as ``household_weight``), runs a - ``Microsimulation`` over it, and calculates each variable. + ``Microsimulation`` over it, and calculates each variable. The + simulation holds ``period`` alone, not policyengine-us's projection + to later years (see :meth:`_read_year_dataset`). Args: bundle: A US-schema bundle. @@ -953,7 +955,7 @@ def materialize( """ microsimulation_class = self._import_policyengine_us().Microsimulation tables = self._engine_tables(bundle) - dataset = self._build_dataset(tables, period) + dataset = self._read_year_dataset(tables, period) simulation = microsimulation_class( dataset=dataset, **({"spm": dict(self._spm)} if self._spm is not None else {}), @@ -1133,6 +1135,22 @@ def _build_dataset( time_period=int(period), ) + def _read_year_dataset( + self, tables: Mapping[str, pd.DataFrame], period: int | str + ) -> Any: + """The tables as an engine dataset whose years end at ``period``. + + Given a ``USSingleYearDataset``, ``Microsimulation`` extends it with + an uprated copy of each later year up to the last year of the CPI-U + parameter (2035 on policyengine-us 2.2.1). The engine then stores + every year's inputs, and each branch it opens (federal itemization, + some state taxes) copies all of them again. ``materialize`` reads + only ``period``, which is the dataset's own year, and no + policyengine-us formula reads a later year's data. So the adapter + stops the extension at ``period`` (:func:`us_dataset_through`). + """ + return us_dataset_through(self._build_dataset(tables, period), int(period)) + def _default_entity(self, column: str) -> str: """Owning table for a defaulted column, from PolicyEngine metadata. @@ -1387,6 +1405,22 @@ def uprating_series( return totals, indices, column_series +def us_dataset_through(dataset: Any, end_year: int) -> Any: + """A one-year ``USSingleYearDataset`` extended only to ``end_year``. + + Given a ``USSingleYearDataset``, ``Microsimulation`` adds an uprated copy + of each later year up to the last year of the CPI-U parameter and stores + every year's inputs; a simulation that reads no year after ``end_year`` + pays for those years in memory and gains nothing. policyengine-us's own + ``extend_single_year_dataset`` with ``end_year`` returns a + ``USMultiYearDataset`` holding the dataset's year through ``end_year``, + which ``Microsimulation`` takes as already extended. + """ + from policyengine_us.data import extend_single_year_dataset + + return extend_single_year_dataset(dataset, end_year=int(end_year)) + + def multi_year_dataset( bundle: Frame, base_year: int, diff --git a/packages/microcosm-frame/tests/engine_free/uk/test_policyengine_uk_adapter.py b/packages/microcosm-frame/tests/engine_free/uk/test_policyengine_uk_adapter.py index 4c9e5c5f98..1e93588009 100644 --- a/packages/microcosm-frame/tests/engine_free/uk/test_policyengine_uk_adapter.py +++ b/packages/microcosm-frame/tests/engine_free/uk/test_policyengine_uk_adapter.py @@ -61,6 +61,15 @@ def calculate(name, *args, **kwargs): "_import_policyengine_uk", lambda: SimpleNamespace(Microsimulation=lambda **kwargs: simulation), ) + # The engine's year window needs policyengine-uk itself; the stand-in + # engine is built from the dataset as it is. + monkeypatch.setattr( + engine, + "_read_year_simulation", + lambda microsimulation_class, dataset, period: microsimulation_class( + dataset=dataset + ), + ) bundle = SimpleNamespace( table=lambda entity: pd.DataFrame({"is_uc_claimant": [True]}), n=lambda entity: 1, @@ -104,6 +113,15 @@ def calculate(name, *args, **kwargs): "_import_policyengine_uk", lambda: SimpleNamespace(Microsimulation=lambda **kwargs: simulation), ) + # The engine's year window needs policyengine-uk itself; the stand-in + # engine is built from the dataset as it is. + monkeypatch.setattr( + engine, + "_read_year_simulation", + lambda microsimulation_class, dataset, period: microsimulation_class( + dataset=dataset + ), + ) bundle = SimpleNamespace( table=lambda entity: pd.DataFrame(_SUPPLIED), n=lambda entity: 2 ) @@ -152,3 +170,334 @@ def test_adapter_accepts_person_type_roles_the_model_reads(monkeypatch): ) engine.materialize(bundle, ["income_tax"], 2025) assert calls == [*_ROLES, "income_tax"] + + +def _stand_in_engine_modules(monkeypatch, path: str, **attributes) -> None: + """Install stand-in policyengine-uk modules down to ``path``.""" + + import sys + from types import ModuleType + + parts = path.split(".") + parent = None + for depth in range(1, len(parts) + 1): + name = ".".join(parts[:depth]) + module = ModuleType(name) + monkeypatch.setitem(sys.modules, name, module) + if parent is not None: + setattr(parent, parts[depth - 1], module) + parent = module + for key, value in attributes.items(): + setattr(parent, key, value) + + +def test_uk_dataset_through_asks_policyengine_uk_for_the_years_to_end_year( + monkeypatch, +): + from microcosm.frame.adapters.policyengine_uk import uk_dataset_through + + calls = [] + + def extend_single_year_dataset(dataset, parameters, end_year=None): + calls.append((dataset, parameters, end_year)) + return list(range(int(dataset.time_period), end_year + 1)) + + _stand_in_engine_modules( + monkeypatch, + "policyengine_uk.data.economic_assumptions", + extend_single_year_dataset=extend_single_year_dataset, + ) + dataset = SimpleNamespace( + time_period="2024", validate=lambda: calls.append("validate") + ) + parameters = object() + + assert uk_dataset_through(dataset, "2025", parameters) == [2024, 2025] + assert uk_dataset_through(dataset, 2024, parameters) == [2024] + # The dataset is checked before every projection, even one of no year. + assert calls == [ + "validate", + (dataset, parameters, 2025), + "validate", + (dataset, parameters, 2024), + ] + with pytest.raises(ValueError, match="forward only"): + uk_dataset_through(dataset, 2023, parameters) + assert len(calls) == 4 + + +def test_uk_dataset_through_refuses_a_dataset_its_check_refuses(monkeypatch): + """policyengine-uk checks a dataset only on the years it projects, so a + dataset read at its own year is checked here; a refusal stops the + projection.""" + + from microcosm.frame.adapters.policyengine_uk import uk_dataset_through + + projected = [] + _stand_in_engine_modules( + monkeypatch, + "policyengine_uk.data.economic_assumptions", + extend_single_year_dataset=lambda *args, **kwargs: projected.append(args), + ) + + def validate(): + raise ValueError("Column 'note' contains NaN values.") + + dataset = SimpleNamespace(time_period="2024", validate=validate) + for end_year in (2024, 2025): + with pytest.raises(ValueError, match="'note' contains NaN"): + uk_dataset_through(dataset, end_year, object()) + assert projected == [] + + +def _stand_in_rebalancing(monkeypatch, years, **constants): + _stand_in_engine_modules( + monkeypatch, + "policyengine_uk.scenarios.uc_reform", + REBALANCING_YEARS=years, + **constants, + ) + import sys + + return sys.modules["policyengine_uk.scenarios.uc_reform"] + + +#: The years policyengine-uk builds its ``REBALANCING_YEARS`` from. +_ENGINE_YEARS = {"FIRST_REBALANCING_YEAR": 2026, "PROJECTION_END_YEAR": 2032} + + +@pytest.mark.parametrize( + ("end_year", "inside"), + [ + (2024, range(2026, 2026)), + (2025, range(2026, 2026)), + (2027, range(2026, 2028)), + (2040, range(2026, 2033)), + ], +) +def test_rebalancing_years_stop_at_end_year_inside_the_block( + monkeypatch, end_year, inside +): + from microcosm.frame.adapters.policyengine_uk import uk_rebalancing_years_through + + installed = range(2026, 2033) + uc_reform = _stand_in_rebalancing(monkeypatch, installed) + + with uk_rebalancing_years_through(end_year) as years: + assert uc_reform.REBALANCING_YEARS == inside + assert years == inside + + assert uc_reform.REBALANCING_YEARS is installed + + +def test_rebalancing_years_are_restored_when_the_block_raises(monkeypatch): + from microcosm.frame.adapters.policyengine_uk import uk_rebalancing_years_through + + installed = range(2026, 2033) + uc_reform = _stand_in_rebalancing(monkeypatch, installed) + + with pytest.raises(RuntimeError, match="construction failed"): + with uk_rebalancing_years_through(2025): + assert uc_reform.REBALANCING_YEARS == range(2026, 2026) + raise RuntimeError("construction failed") + + assert uc_reform.REBALANCING_YEARS is installed + + +@pytest.mark.parametrize("installed", [(2026, 2027), range(2026, 2033, 2)]) +def test_rebalancing_years_refuse_a_changed_engine(monkeypatch, installed): + from microcosm.frame.adapters.policyengine_uk import uk_rebalancing_years_through + + uc_reform = _stand_in_rebalancing(monkeypatch, installed) + + with pytest.raises(TypeError, match="REBALANCING_YEARS"): + with uk_rebalancing_years_through(2025): + pass + + assert uc_reform.REBALANCING_YEARS is installed + + +def test_rebalancing_years_are_restored_when_blocks_exit_out_of_order(monkeypatch): + from microcosm.frame.adapters.policyengine_uk import uk_rebalancing_years_through + + installed = range(2026, 2033) + uc_reform = _stand_in_rebalancing(monkeypatch, installed) + + first = uk_rebalancing_years_through(2027) + second = uk_rebalancing_years_through(2027) + first.__enter__() + second.__enter__() + first.__exit__(None, None, None) + # The second block is still open, so its simulation still gets the cut. + assert uc_reform.REBALANCING_YEARS == range(2026, 2028) + second.__exit__(None, None, None) + + assert uc_reform.REBALANCING_YEARS is installed + + +def test_a_block_for_another_year_is_refused_inside_an_open_block(monkeypatch): + from microcosm.frame.adapters.policyengine_uk import uk_rebalancing_years_through + + installed = range(2026, 2033) + uc_reform = _stand_in_rebalancing(monkeypatch, installed) + + with uk_rebalancing_years_through(2027): + for other_year in (2025, 2030): + with pytest.raises(RuntimeError, match="cut at 2027"): + with uk_rebalancing_years_through(other_year): + pass + # The refusal leaves the open block's cut in force. + assert uc_reform.REBALANCING_YEARS == range(2026, 2028) + with uk_rebalancing_years_through("2027") as years: + assert years == range(2026, 2028) + assert uc_reform.REBALANCING_YEARS == range(2026, 2028) + + assert uc_reform.REBALANCING_YEARS is installed + + +def test_a_block_on_another_thread_waits_for_the_open_block(monkeypatch): + import threading + + from microcosm.frame.adapters.policyengine_uk import uk_rebalancing_years_through + + installed = range(2026, 2033) + uc_reform = _stand_in_rebalancing(monkeypatch, installed) + entered = threading.Event() + seen = [] + + def other_thread(): + with uk_rebalancing_years_through(2027) as years: + entered.set() + seen.append((years, uc_reform.REBALANCING_YEARS)) + + thread = threading.Thread(target=other_thread) + with uk_rebalancing_years_through(2025): + thread.start() + # The other thread cannot cut the range while this block is open. + assert not entered.wait(0.2) + assert uc_reform.REBALANCING_YEARS == range(2026, 2026) + thread.join(timeout=10) + + assert not thread.is_alive() + # It cut the engine's own range, not this block's cut of it. + assert seen == [(range(2026, 2028), range(2026, 2028))] + assert uc_reform.REBALANCING_YEARS is installed + + +def test_a_range_changed_inside_the_block_is_refused_and_restored(monkeypatch): + from microcosm.frame.adapters.policyengine_uk import uk_rebalancing_years_through + + installed = range(2026, 2033) + uc_reform = _stand_in_rebalancing(monkeypatch, installed) + + with pytest.raises(RuntimeError, match="changed inside"): + with uk_rebalancing_years_through(2025): + uc_reform.REBALANCING_YEARS = range(2026, 2030) + + assert uc_reform.REBALANCING_YEARS is installed + with uk_rebalancing_years_through(2027) as years: + assert years == range(2026, 2028) + assert uc_reform.REBALANCING_YEARS is installed + + +def test_the_whole_loop_block_accepts_the_engines_own_range(monkeypatch): + from microcosm.frame.adapters.policyengine_uk import uk_whole_rebalancing_years + + installed = range(2026, 2033) + uc_reform = _stand_in_rebalancing(monkeypatch, installed, **_ENGINE_YEARS) + + with uk_whole_rebalancing_years(): + assert uc_reform.REBALANCING_YEARS is installed + + assert uc_reform.REBALANCING_YEARS is installed + + +def test_the_whole_loop_block_accepts_an_engine_that_was_never_imported(monkeypatch): + import sys + + from microcosm.frame.adapters.policyengine_uk import uk_whole_rebalancing_years + + monkeypatch.delitem( + sys.modules, "policyengine_uk.scenarios.uc_reform", raising=False + ) + + with uk_whole_rebalancing_years(): + assert "policyengine_uk.scenarios.uc_reform" not in sys.modules + + +@pytest.mark.parametrize("left", [range(2026, 2026), range(2026, 2028)]) +def test_the_whole_loop_block_refuses_a_range_left_cut(monkeypatch, left): + from microcosm.frame.adapters.policyengine_uk import uk_whole_rebalancing_years + + uc_reform = _stand_in_rebalancing(monkeypatch, left, **_ENGINE_YEARS) + + with pytest.raises(RuntimeError, match="a cut was left"): + with uk_whole_rebalancing_years(): + pass + + assert uc_reform.REBALANCING_YEARS is left + + +def test_the_whole_loop_block_is_refused_inside_an_open_cut(monkeypatch): + from microcosm.frame.adapters.policyengine_uk import ( + uk_rebalancing_years_through, + uk_whole_rebalancing_years, + ) + + installed = range(2026, 2033) + uc_reform = _stand_in_rebalancing(monkeypatch, installed, **_ENGINE_YEARS) + + with uk_rebalancing_years_through(2025): + with pytest.raises(RuntimeError, match="needs the whole loop"): + with uk_whole_rebalancing_years(): + pass + assert uc_reform.REBALANCING_YEARS == range(2026, 2026) + with uk_whole_rebalancing_years(): + assert uc_reform.REBALANCING_YEARS is installed + + +def test_the_whole_loop_block_waits_for_a_cut_on_another_thread(monkeypatch): + import threading + + from microcosm.frame.adapters.policyengine_uk import ( + uk_rebalancing_years_through, + uk_whole_rebalancing_years, + ) + + installed = range(2026, 2033) + uc_reform = _stand_in_rebalancing(monkeypatch, installed, **_ENGINE_YEARS) + entered = threading.Event() + seen = [] + + def other_thread(): + with uk_whole_rebalancing_years(): + entered.set() + seen.append(uc_reform.REBALANCING_YEARS) + + thread = threading.Thread(target=other_thread) + with uk_rebalancing_years_through(2025): + thread.start() + # A simulation that needs the whole loop is not built during the cut. + assert not entered.wait(0.2) + thread.join(timeout=10) + + assert not thread.is_alive() + assert seen == [installed] + + +@pytest.mark.parametrize( + "constants", + [ + {}, + {"FIRST_REBALANCING_YEAR": 2026}, + {"FIRST_REBALANCING_YEAR": 2026, "PROJECTION_END_YEAR": "2032"}, + ], +) +def test_the_whole_loop_block_refuses_a_changed_engine(monkeypatch, constants): + from microcosm.frame.adapters.policyengine_uk import uk_whole_rebalancing_years + + _stand_in_rebalancing(monkeypatch, range(2026, 2033), **constants) + + with pytest.raises(TypeError, match="FIRST_REBALANCING_YEAR"): + with uk_whole_rebalancing_years(): + pass diff --git a/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py b/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py index dc459ddce3..6440b93296 100644 --- a/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py +++ b/packages/microcosm-frame/tests/engine_workflow/us/test_policyengine_us_adapter.py @@ -683,6 +683,29 @@ def test_no_take_up_flag_is_dead_in_pinned_engine(self, adapter) -> None: assert dead == [], f"unexpected dead take-up flags: {dead}" +def _held_through(simulation, last_year: int) -> dict[tuple[str, str, str], object]: + """Every array a simulation and its branches hold for a period up to + ``last_year``, by branch, variable and period.""" + + from policyengine_core import periods + + held = {} + pending = [("", simulation)] + while pending: + path, current = pending.pop() + for population in current.populations.values(): + for name, holder in population._holders.items(): + for key, array in holder._memory_storage._arrays.items(): + branch, period_text = key.split(":", 1) + if periods.period(period_text).start.year > last_year: + continue + held[(f"{path}{branch}", name, period_text)] = np.asarray(array) + pending.extend( + (f"{path}{name}/", branch) for name, branch in current.branches.items() + ) + return held + + class _RecordingMicrosimulation: """Stands in for ``policyengine_us.Microsimulation`` and records kwargs.""" @@ -742,3 +765,70 @@ def test_each_simulation_receives_its_own_copy(self, us_bundle) -> None: first, second = _RecordingMicrosimulation.calls assert first["spm"] == second["spm"] == {"geography_kind": "national"} assert first["spm"] is not second["spm"] + + +class TestReadYearWindow: + """The engine holds the read year alone, not its projection to later years. + + Given a single-year dataset, ``Microsimulation`` adds an uprated copy of + each year up to the last CPI-U year and stores all of them. ``materialize`` + reads only the dataset's own year, so the adapter stops the extension there. + """ + + @pytest.mark.parametrize("period", [2024, 2026]) + def test_the_engine_receives_the_read_year_alone( + self, adapter, us_bundle, monkeypatch, period + ) -> None: + import policyengine_us + from policyengine_us.data import USMultiYearDataset + + _RecordingMicrosimulation.calls = [] + monkeypatch.setattr( + policyengine_us, "Microsimulation", _RecordingMicrosimulation + ) + + adapter.materialize(us_bundle, ["household_net_income"], period=period) + + (call,) = _RecordingMicrosimulation.calls + dataset = call["dataset"] + assert isinstance(dataset, USMultiYearDataset) + assert dataset.years == [period] + + def test_values_match_the_engine_default_window(self, adapter, us_bundle) -> None: + from policyengine_us import Microsimulation + + variables = [ + "employment_income", + "ssi", + "snap", + "income_tax", + "state_income_tax", + "household_net_income", + ] + tables = adapter._engine_tables(us_bundle) + default = Microsimulation(dataset=adapter._build_dataset(tables, 2024)) + # The comparison is only meaningful while the engine still extends. + assert len(default.get_holder("age").get_known_periods()) > 1 + + results = adapter.materialize(us_bundle, variables, period=2024) + + for name in variables: + np.testing.assert_array_equal( + results[name], + np.asarray(default.calculate(name, period=2024)), + err_msg=name, + ) + + # Every array both engines hold through 2024, in every branch, is the + # same: a formula that read a later year's data, or core filling 2024 + # from a later year, would show here and not only in the six outputs. + cut = Microsimulation(dataset=adapter._read_year_dataset(tables, 2024)) + for name in variables: + cut.calculate(name, period=2024) + held_cut = _held_through(cut, 2024) + held_default = _held_through(default, 2024) + assert held_cut.keys() == held_default.keys() + for key in sorted(held_default): + np.testing.assert_array_equal( + held_cut[key], held_default[key], err_msg=str(key) + ) diff --git a/test_support/microcosm_build/uk_engine_window.py b/test_support/microcosm_build/uk_engine_window.py new file mode 100644 index 0000000000..e9466421db --- /dev/null +++ b/test_support/microcosm_build/uk_engine_window.py @@ -0,0 +1,33 @@ +"""Engine-free stand-ins for the UK measure resolver's engine year window. + +A scratch-mode ``UKMeasureResolver`` rewrites its one-year scratch H5 as a +multi-year H5 through its year (policyengine-uk's own uprating) and builds +each simulation inside ``uk_rebalancing_years_through``. Both steps need +policyengine-uk itself, so a test that stands a fake engine in for it keeps +the one-year file and the installed rebalancing loop, and records the +projections the resolver asked for. +""" + +from __future__ import annotations + +from contextlib import nullcontext +from pathlib import Path + +from microcosm.build.uk_runtime import measure_simulation + + +def stub_scratch_engine_window(monkeypatch) -> list[tuple[str, int]]: + """Stub both window steps; returns the ``(file name, end year)`` requests.""" + + projections: list[tuple[str, int]] = [] + + def project(path, end_year): + projections.append((Path(path).name, int(end_year))) + + monkeypatch.setattr(measure_simulation, "_project_scratch_engine_input", project) + monkeypatch.setattr( + measure_simulation, + "uk_rebalancing_years_through", + lambda end_year: nullcontext(), + ) + return projections diff --git a/test_support/microcosm_build/us_batched_target_materialization.py b/test_support/microcosm_build/us_batched_target_materialization.py index 93434d1fd6..78731fc729 100644 --- a/test_support/microcosm_build/us_batched_target_materialization.py +++ b/test_support/microcosm_build/us_batched_target_materialization.py @@ -259,6 +259,7 @@ def fake_dataset_from_frame( zero_variables=(), system=None, assert_no_formula_owned_columns=True, + period_only=False, ): return {"frame": frame_arg, "zero_variables": tuple(zero_variables)} @@ -747,6 +748,79 @@ def _engine_population_aggregate_sources( return found +# A period offset whose amount is not negative (a later month or year), and a +# holder lookup, which can read any stored period. +_FORWARD_PERIOD_READ = re.compile(r"\.offset\(\s*(?!-)[\w.]+") +_HOLDER_LOOKUP = re.compile(r"\b(?:get_known_periods|get_holder|get_array)\(|\b_holders\b") + + +def _engine_forward_read_sources( + root: Path | None = None, + *, + source_digests: dict[str, str] | None = None, +) -> dict[str, list[str]]: + """Scan package Variable classes and module helpers for later-period reads. + + A forward offset or a holder lookup marks a formula to inspect: it may read + a year after the one asked, which a dataset cut at that year does not hold. + A match proves nothing either way, and a formula can build a later period + in other ways. + """ + if root is None: + spec = importlib.util.find_spec("policyengine_us") + root = Path(next(iter(spec.submodule_search_locations))) + modules = [] + for path in sorted(root.rglob("*.py")): + relative = path.relative_to(root) + if "tests" in relative.parts or path.name.startswith("test_"): + continue + source = path.read_text() + modules.append((source, ast.parse(source))) + + def markers(body: str) -> list[str]: + return [ + match.group(0) + for pattern in (_FORWARD_PERIOD_READ, _HOLDER_LOOKUP) + for match in pattern.finditer(body) + ] + + helpers: dict[str, list[str]] = {} + for source, tree in modules: + for node in tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + helpers.setdefault(node.name, []).append( + ast.get_source_segment(source, node) + ) + reaching = {name for name, bodies in helpers.items() if any(map(markers, bodies))} + grew = True + while grew: + grew = False + for name, bodies in helpers.items(): + if name not in reaching and any( + re.search(rf"\b{other}\(", body) for body in bodies for other in reaching + ): + reaching.add(name) + grew = True + + found: dict[str, list[str]] = {} + for source, tree in modules: + for node in ast.walk(tree): + if not _is_variable_class(node): + continue + body = ast.get_source_segment(source, node) + called = sorted( + helper for helper in reaching if re.search(rf"\b{helper}\(", body) + ) + evidence = markers(body) + [f"{helper}()" for helper in called] + if not evidence: + continue + found[node.name] = evidence + if source_digests is not None: + sources = [body] + [text for helper in called for text in helpers[helper]] + source_digests[node.name] = hashlib.sha256( + "\n".join(sorted(sources)).encode() + ).hexdigest() + return found # These inspected 2.2.1 formulas compare a record's status or geography with diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index e560f543e1..52a529d014 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -455,6 +455,7 @@ from microcosm.frame.adapters.policyengine_us import ( PolicyEngineUSEngine, PolicyEngineUSVariableMetadataIndex, + us_dataset_through, ) from microcosm.frame.units import US_SCHEMA @@ -3973,6 +3974,7 @@ def _aca_source_tax_unit_table_batched( dataset=_dataset_from_frame( batch_frame, assert_no_formula_owned_columns=False, + period_only=True, ) ) batch_tax_unit = _aca_source_tax_unit_table_from_simulation( @@ -4187,6 +4189,7 @@ def _medicaid_person_eligibility( dataset=_dataset_from_frame( batch_frame, assert_no_formula_owned_columns=False, + period_only=True, ) ) batch_eligible = ( @@ -4274,6 +4277,7 @@ def calculate(active_simulation) -> np.ndarray: dataset=_dataset_from_frame( batch_frame, assert_no_formula_owned_columns=False, + period_only=True, ) ) batch_uncapped = calculate(batch_simulation) @@ -4489,6 +4493,7 @@ def _snap_spm_unit_eligibility( dataset=_dataset_from_frame( batch_frame, assert_no_formula_owned_columns=False, + period_only=True, ) ) batch_eligible = ( @@ -4575,7 +4580,22 @@ def _dataset_from_frame( zero_variables: Iterable[str] = (), system=None, assert_no_formula_owned_columns: bool = True, + period_only: bool = False, ): + """The frame as a policyengine-us dataset for ``PERIOD``. + + By default the dataset is the one year, and policyengine-us projects it + as a user's load does: it adds an uprated copy of every later year to its + last CPI-U year, stores them all, and copies them again into each branch + it opens. A read at a later year then gets the engine's own projected + inputs; post-export scoring plans keys in later years. + + ``period_only`` holds ``PERIOD`` alone (``us_dataset_through``), for an + in-build simulation that reads only ``PERIOD`` (``_calculate_array``, and + the December SSI month). A later read on that dataset is not refused: the + engine carries or uprates leaf inputs itself and reads a stored + formula-owned column as its default, so only such a caller may ask. + """ if assert_no_formula_owned_columns: _assert_no_formula_owned_columns(frame) @@ -4589,7 +4609,7 @@ def _dataset_from_frame( if entity is not None and variable_name in tables[entity]: tables[entity][variable_name] = 0 tables["household"]["household_weight"] = frame.weights_for("household").values - return USSingleYearDataset( + dataset = USSingleYearDataset( person=tables["person"], household=tables["household"], tax_unit=tables["tax_unit"], @@ -4598,6 +4618,9 @@ def _dataset_from_frame( marital_unit=tables["marital_unit"], time_period=PERIOD, ) + if not period_only: + return dataset + return us_dataset_through(dataset, PERIOD) def _calculate_array( @@ -5352,6 +5375,9 @@ def __init__( if dataset_from_frame is None: def dataset_from_frame(batch_frame: Frame): + # Consumer plans read years after PERIOD (reform validation + # reaches past 2025), so the scorer keeps the engine's + # projection: it does not ask for PERIOD alone. return _dataset_from_frame( batch_frame, assert_no_formula_owned_columns=False, @@ -5751,6 +5777,7 @@ def _reform_household_income_tax( zero_variables=(reform_spec.neutralized_variable,), system=system, assert_no_formula_owned_columns=False, + period_only=True, ) reformed = microsimulation_cls( tax_benefit_system=reform_system, @@ -7118,6 +7145,7 @@ def _materialize_base_simulation_columns( dataset=_dataset_from_frame( batch_frame, assert_no_formula_owned_columns=False, + period_only=True, ) ) try: