diff --git a/changelog.d/us-post-calibration-pass-reuse.changed.md b/changelog.d/us-post-calibration-pass-reuse.changed.md new file mode 100644 index 0000000000..84a2040efe --- /dev/null +++ b/changelog.d/us-post-calibration-pass-reuse.changed.md @@ -0,0 +1 @@ +The US fiscal-refresh release tool no longer reruns policyengine-us over every household for the post-calibration December SSI candidate amounts and Medicaid eligibility. Each pre-calibration pass keeps its per-person values and a digest of each household's rows: IDs, membership, row order, and every column the engine can read for `uncapped_ssi` or `is_medicaid_eligible`. That is the engine's static dependency graph, plus the variables named in strings in a listed formula's source, constants or closure (branch simulations, `get_holder` reads, `all_of_variables` lists and generated state flags) and the state flags that programs are `defined_for`. After calibration, households whose digest is unchanged take their earlier values, matched by person ID. The tool runs policyengine-us on the households whose inputs changed, one batch at a time, and on one batch of unchanged households spread over the frame as a check; if that check disagrees, it runs every household again. The counts are printed and sent with the build's telemetry. The Medicaid reuse runs every household when a positive `medicaid_claiming_tax_unit_id` points outside its own household, and an unbatched build reruns in one selection. Neither variable reads weights or a population-wide sum, so calibrated weights and L0's dropped households change no remaining value. No column written between the two SSI passes is an SSI input. Between the Medicaid passes, SNAP take-up and the other-health-insurance premium attribution change some households' inputs, and those households are rerun. Reruns of selected households switch the population-aggregate refusal on, and `household_batches.one_pass_garbage_collection` gives a reuse's rerun batches one full collection, as a full pass has. The new country-neutral helper is `microcosm.build.household_pass_reuse`; `microcosm.build.us_runtime.household_pass_inputs` lists a policyengine-us pass's input columns. diff --git a/packages/microcosm-build/src/microcosm/build/household_pass_reuse.py b/packages/microcosm-build/src/microcosm/build/household_pass_reuse.py new file mode 100644 index 0000000000..d341a4bfb1 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/household_pass_reuse.py @@ -0,0 +1,535 @@ +"""Reuse a household-batched engine pass for households whose inputs are unchanged. + +A pass computes one value per person by running an engine over batches of +whole households. When each person's value depends only on the rows of their +own household (the IDs and membership of its people and group units, the +order of those rows, and the columns the engine can read for the pass's +variable), a later pass over a changed frame can take the earlier value of +every person whose household's rows are unchanged, and run the engine only on +the other households. + +The caller guarantees the conditions that make this hold: the variable reads +no weight and nothing summed over the simulated population, every group unit +belongs to one household, and the input list names every column the engine +can read for the variable. :class:`HouseholdPassRecord` keeps the values, the +person IDs and a 128-bit digest of each household's rows; it keeps no frame. + +A reuse also runs the engine on some unchanged households, spread over the +frame, and compares the results byte for byte with the recorded values. If any differ (an input list +that misses a column the engine reads, say), it runs every household again, +so the values it returns are those of a full pass. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Callable +from dataclasses import dataclass + +import numpy as np +import pandas as pd + +from microcosm.frame import Frame + +__all__ = [ + "HouseholdPassInputs", + "HouseholdPassRecord", + "HouseholdPassReuse", + "PassInputColumn", + "household_input_digests", + "record_household_pass", + "reuse_household_pass", +] + + +@dataclass(frozen=True) +class PassInputColumn: + """One column the engine can read for a pass's variable. + + Attributes: + name: Column (engine variable) name. + entity: Frame table the engine reads it from. + default: The value the engine uses when the column is absent. + absent_reads_default: Whether a stored ``default`` gives the engine + the same input as no column. False for a column the engine would + otherwise compute (a stored value replaces the formula) and for a + default the engine would change when it is stored (uprating, or + division into months). When False, a column that appears or + disappears changes every household's digest. + """ + + name: str + entity: str + default: object + absent_reads_default: bool + + +@dataclass(frozen=True) +class HouseholdPassInputs: + """Every column one pass's engine variable can read, and where.""" + + variable: str + columns: tuple[PassInputColumn, ...] + #: Where the list came from, for messages. + description: str = "" + household_entity: str = "household" + + +@dataclass(frozen=True) +class HouseholdPassRecord: + """One pass's per-person values and the household digests they came from.""" + + inputs: HouseholdPassInputs + household_ids: np.ndarray + #: ``(households, 2)`` unsigned 64-bit digest halves. + household_digests: np.ndarray + person_ids: np.ndarray + values: np.ndarray + #: Why the recorded frame's households are not independent for this + #: pass, if the caller found a reason; a reuse of this record then runs + #: the whole frame. + reuse_refused: str | None = None + + +@dataclass(frozen=True) +class HouseholdPassReuse: + """The values a later pass returns, and how many households it reran.""" + + values: np.ndarray + reused_households: int + recomputed_households: int + checked_households: int + #: True when the check disagreed and every household was run again. + check_failed: bool + #: Set when the record or the caller refused reuse and the whole frame + #: was run: the reason. + reuse_refused: str | None = None + + +# Two digest halves. Numbers are digested from their bits, so the halves +# differ by salt; strings are also hashed with a different key per half. +_LANES = ("household_pass_a", "household_pass_b") + + +def _salt(lane: str, label: str) -> np.uint64: + digest = hashlib.blake2b(f"{lane}\0{label}".encode(), digest_size=8).digest() + return np.uint64(int.from_bytes(digest, "little")) + + +def _mixed(values: np.ndarray) -> np.ndarray: + """A bijective scramble of unsigned 64-bit values (the splitmix64 finalizer).""" + + mixed = np.array(values, dtype=np.uint64, copy=True) + with np.errstate(over="ignore"): + mixed ^= mixed >> np.uint64(30) + mixed *= np.uint64(0xBF58476D1CE4E5B9) + mixed ^= mixed >> np.uint64(27) + mixed *= np.uint64(0x94D049BB133111EB) + mixed ^= mixed >> np.uint64(31) + return mixed + + +def _canonical(values: np.ndarray | pd.Series) -> np.ndarray: + """Values widened so equal numbers stored at different widths agree. + + Booleans and signed integers become int64, unsigned integers uint64 and + floats float64; anything else becomes an object array. Widening is exact, + so values that differ stay different (and ``-0.0`` keeps its sign bit). + """ + + if isinstance(values, pd.Series): + numpy_values = values.to_numpy() + if numpy_values.dtype.kind not in "biuf": + return values.astype(object).to_numpy() + values = numpy_values + values = np.asarray(values) + kind = values.dtype.kind + if kind in "bi": + return values.astype(np.int64) + if kind == "u": + return values.astype(np.uint64) + if kind == "f": + return values.astype(np.float64) + return values.astype(object) + + +def _value_bits(values: np.ndarray, lane: str) -> np.ndarray: + """One unsigned 64-bit value per element: exact bits for numbers.""" + + if values.dtype.kind in "iuf": + return values.view(np.uint64) + return pd.util.hash_array(values, hash_key=lane, categorize=True) + + +def _differs_from_default(values: np.ndarray, default: object) -> np.ndarray: + """Elements whose stored value is not exactly the engine's default.""" + + if values.dtype.kind in "iuf": + try: + stored_default = np.asarray([default], dtype=values.dtype) + except (TypeError, ValueError, OverflowError): + return np.ones(len(values), dtype=bool) + if isinstance(default, str) or stored_default[0] != default: + return np.ones(len(values), dtype=bool) + return values.view(np.uint64) != stored_default.view(np.uint64)[0] + equal = pd.Series(values, dtype=object).eq(default) + return ~equal.fillna(False).to_numpy(dtype=bool) + + +def _row_household_positions( + frame: Frame, entity: str, household_entity: str +) -> np.ndarray: + """Each row's position in the household table, for one entity table.""" + + schema = frame.schema + households = pd.Index( + frame.table(household_entity)[schema.id_column(household_entity)] + ) + if entity == household_entity: + return np.arange(len(households), dtype=np.int64) + person = frame.table(schema.person_entity) + person_households = person[schema.membership_column(household_entity)].to_numpy() + if entity == schema.person_entity: + positions = households.get_indexer(person_households) + else: + membership = pd.DataFrame( + { + "unit": person[schema.membership_column(entity)].to_numpy(), + "household": person_households, + } + ).drop_duplicates() + if membership["unit"].duplicated().any(): + examples = membership.loc[membership["unit"].duplicated(), "unit"] + raise ValueError( + f"{entity} units must each belong to one {household_entity}; " + f"examples: {examples.head(5).tolist()}." + ) + unit_households = membership.set_index("unit")["household"].reindex( + frame.table(entity)[schema.id_column(entity)].to_numpy() + ) + if unit_households.isna().any(): + raise ValueError(f"{entity} units without a member person.") + positions = households.get_indexer(unit_households.to_numpy()) + if (positions < 0).any(): + raise ValueError(f"{entity} rows reference unknown {household_entity} IDs.") + return positions.astype(np.int64) + + +def _structural_columns(frame: Frame, entity: str) -> list[str]: + """ID, membership and role columns the engine builds its entities from.""" + + schema = frame.schema + table = frame.table(entity) + columns = [schema.entity_id_column(entity)] + if entity == schema.person_entity: + for group in schema.group_entities: + columns.append(schema.membership_column(group)) + role = f"{schema.person_entity}_{group}_role" + if role in table: + columns.append(role) + if "role" in table: + columns.append("role") + return columns + + +def household_input_digests( + frame: Frame, inputs: HouseholdPassInputs +) -> tuple[np.ndarray, np.ndarray]: + """Household IDs and a ``(households, 2)`` digest of each household's rows. + + A household's digest covers, for each of its rows in every entity table: + the row's ID and membership (and role) columns, its place among its + household's rows of that table, and each input column. An input whose + absent column reads as its default contributes only where the stored + value differs from that default, so writing the default is no change. + Other inputs contribute on every row whenever the column is present. + """ + + schema = frame.schema + household_entity = inputs.household_entity + household_ids = frame.table(household_entity)[ + schema.id_column(household_entity) + ].to_numpy() + columns_by_entity: dict[str, list[PassInputColumn]] = {} + for column in inputs.columns: + if column.entity not in frame.entities: + raise ValueError( + f"Input {column.name!r} belongs to {column.entity!r}, which the " + f"frame does not have ({list(frame.entities)})." + ) + columns_by_entity.setdefault(column.entity, []).append(column) + + digests = np.zeros((len(household_ids), len(_LANES)), dtype=np.uint64) + for entity in frame.entities: + table = frame.table(entity) + positions = _row_household_positions(frame, entity, household_entity) + place = pd.Series(positions).groupby(positions).cumcount().to_numpy() + structural = { + f"structure:{name}": _canonical(table[name]) + for name in _structural_columns(frame, entity) + } + structural[f"structure:{household_entity}"] = _canonical( + household_ids[positions] + ) + structural["structure:place"] = place.astype(np.int64) + # Unsigned sums wrap around, which is what a digest wants. + row_sums = np.zeros((len(_LANES), len(table)), dtype=np.uint64) + with np.errstate(over="ignore"): + for label, values in structural.items(): + for lane_index, lane in enumerate(_LANES): + row_sums[lane_index] += _mixed( + _value_bits(values, lane) ^ _salt(lane, f"{entity}:{label}") + ) + for column in columns_by_entity.get(entity, ()): + if column.name not in table: + continue + values = _canonical(table[column.name]) + if column.absent_reads_default: + rows = np.flatnonzero(_differs_from_default(values, column.default)) + values = values[rows] + else: + rows = slice(None) + if not len(values): + continue + for lane_index, lane in enumerate(_LANES): + row_sums[lane_index, rows] += _mixed( + _value_bits(values, lane) + ^ _salt(lane, f"{entity}:input:{column.name}") + ) + for lane_index, lane in enumerate(_LANES): + row_digests = _mixed( + row_sums[lane_index] ^ _salt(lane, f"{entity}:row") + ) + lane_digests = np.zeros(len(household_ids), dtype=np.uint64) + np.add.at(lane_digests, positions, row_digests) + digests[:, lane_index] += lane_digests + return household_ids.copy(), digests + + +def record_household_pass( + frame: Frame, + values: np.ndarray, + inputs: HouseholdPassInputs, + *, + reuse_refused: str | None = None, +) -> HouseholdPassRecord: + """Keep a pass's values with the digests of the households they came from. + + ``reuse_refused`` is the caller's reason, if any, why one household's + value on ``frame`` can depend on another household's rows (a cross- + household link the pass reads); a reuse of the record then runs the whole + frame. + """ + + values = np.asarray(values) + person = frame.table(frame.schema.person_entity) + if values.shape != (len(person),): + raise ValueError( + f"A {inputs.variable} pass record needs one value per person: " + f"{len(person)} people, values of shape {values.shape}." + ) + household_ids, digests = household_input_digests(frame, inputs) + return HouseholdPassRecord( + inputs=inputs, + household_ids=household_ids, + household_digests=digests, + person_ids=person[frame.schema.person_id_column].to_numpy().copy(), + values=values.copy(), + reuse_refused=reuse_refused, + ) + + +def _checked_household_positions(unchanged: np.ndarray, count: int) -> np.ndarray: + """Up to ``count`` unchanged households, spread evenly over the frame. + + Pools are concatenated from source blocks (one spine, then another), so a + sample from one end of the frame would check one source only. + """ + + unchanged_positions = np.flatnonzero(unchanged) + count = min(max(int(count), 0), len(unchanged_positions)) + if not count: + return np.zeros(0, dtype=np.int64) + picks = (np.arange(count, dtype=np.int64) * len(unchanged_positions)) // count + return unchanged_positions[picks] + + +def _run_households( + frame: Frame, + run_households: np.ndarray, + person_households: np.ndarray, + recompute: Callable[[Frame], np.ndarray], + *, + variable: str, + dtype: np.dtype, + batch_household_count: int, +) -> np.ndarray: + """The engine's values for the people of the marked households. + + Returns a person-aligned array whose entries for people outside those + households are unset. With every household marked, ``recompute`` gets + ``frame`` itself and batches it as a full pass does. Otherwise it gets one + selection of at most ``batch_household_count`` marked households at a + time, so no more than one batch's rows are copied at once. + """ + + schema = frame.schema + person_ids = frame.table(schema.person_entity)[schema.person_id_column].to_numpy() + values = np.empty(len(person_ids), dtype=dtype) + positions = np.flatnonzero(run_households) + if len(positions) == len(run_households): + batches = [None] + else: + size = max(int(batch_household_count), 1) + batches = [ + positions[start : start + size] for start in range(0, len(positions), size) + ] + for batch in batches: + if batch is None: + batch_people = np.ones(len(person_ids), dtype=bool) + batch_frame = frame + else: + in_batch = np.zeros(len(run_households), dtype=bool) + in_batch[batch] = True + batch_people = in_batch[person_households] + batch_frame = frame.select(batch_people) + batch_person_ids = batch_frame.table(schema.person_entity)[ + schema.person_id_column + ].to_numpy() + batch_values = np.asarray(recompute(batch_frame)) + if batch_values.shape != (len(batch_person_ids),): + raise ValueError( + f"The {variable} pass must return one value per person: " + f"{len(batch_person_ids)} people, values of shape " + f"{batch_values.shape}." + ) + if batch_values.dtype != dtype: + raise ValueError( + f"The {variable} pass returned dtype {batch_values.dtype}; the " + f"record holds {dtype}." + ) + order = pd.Index(batch_person_ids).get_indexer(person_ids[batch_people]) + if (order < 0).any(): + raise ValueError(f"The {variable} pass dropped people from its frame.") + values[batch_people] = batch_values[order] + del batch_frame, batch_values + return values + + +def reuse_household_pass( + record: HouseholdPassRecord, + frame: Frame, + *, + recompute: Callable[[Frame], np.ndarray], + checked_household_count: int, + batch_household_count: int, + reuse_refused: str | None = None, +) -> HouseholdPassReuse: + """Values of ``record``'s pass on ``frame``, rerunning only what changed. + + ``recompute`` runs the pass on a frame of whole households and returns + one value per person of that frame. It runs on the households whose + digest differs from the record or that the record lacks, together with + ``checked_household_count`` unchanged households spread over the frame, + in selections of at most ``batch_household_count`` households. If any + checked person's value differs from the recorded one, ``recompute`` runs + on the whole frame and those values are returned. ``recompute`` also runs + on the whole frame, with nothing reused, when the record or the caller + (``reuse_refused``, for ``frame``) gives a reason the households are not + independent. + """ + + schema = frame.schema + variable = record.inputs.variable + dtype = record.values.dtype + refusal = record.reuse_refused or reuse_refused + if refusal is not None: + household_count = frame.n(record.inputs.household_entity) + person_households = pd.Index( + frame.table(record.inputs.household_entity)[ + schema.id_column(record.inputs.household_entity) + ] + ).get_indexer( + frame.table(schema.person_entity)[ + schema.membership_column(record.inputs.household_entity) + ].to_numpy() + ) + return HouseholdPassReuse( + values=_run_households( + frame, + np.ones(household_count, dtype=bool), + person_households, + recompute, + variable=variable, + dtype=dtype, + batch_household_count=batch_household_count, + ), + reused_households=0, + recomputed_households=household_count, + checked_households=0, + check_failed=False, + reuse_refused=refusal, + ) + household_ids, digests = household_input_digests(frame, record.inputs) + stored = pd.Index(record.household_ids).get_indexer(household_ids) + unchanged = stored >= 0 + unchanged[unchanged] = np.all( + record.household_digests[stored[unchanged]] == digests[unchanged], axis=1 + ) + + person = frame.table(schema.person_entity) + person_ids = person[schema.person_id_column].to_numpy() + person_households = pd.Index(household_ids).get_indexer( + person[schema.membership_column(record.inputs.household_entity)].to_numpy() + ) + person_reused = unchanged[person_households] + stored_people = pd.Index(record.person_ids).get_indexer(person_ids) + if (stored_people[person_reused] < 0).any(): + raise ValueError( + f"A household whose {variable} digest matches has a person the " + "record lacks." + ) + values = np.empty(len(person), dtype=dtype) + values[person_reused] = record.values[stored_people[person_reused]] + + checked = np.zeros(len(household_ids), dtype=bool) + checked[_checked_household_positions(unchanged, checked_household_count)] = True + run_households = ~unchanged | checked + if run_households.any(): + run_people = run_households[person_households] + run_values = _run_households( + frame, + run_households, + person_households, + recompute, + variable=variable, + dtype=dtype, + batch_household_count=batch_household_count, + ) + checked_people = run_people & person_reused + if values[checked_people].tobytes() != run_values[checked_people].tobytes(): + del run_values + return HouseholdPassReuse( + values=_run_households( + frame, + np.ones(len(household_ids), dtype=bool), + person_households, + recompute, + variable=variable, + dtype=dtype, + batch_household_count=batch_household_count, + ), + reused_households=0, + recomputed_households=len(household_ids), + checked_households=int(checked.sum()), + check_failed=True, + ) + rerun_people = run_people & ~person_reused + values[rerun_people] = run_values[rerun_people] + return HouseholdPassReuse( + values=values, + reused_households=int(unchanged.sum()), + recomputed_households=int((~unchanged).sum()), + checked_households=int(checked.sum()), + check_failed=False, + ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/household_batches.py b/packages/microcosm-build/src/microcosm/build/us_runtime/household_batches.py index b64a6807c4..aacb8db301 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/household_batches.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/household_batches.py @@ -25,6 +25,8 @@ :func:`collect_pass_garbage` are the garbage-collection pattern of a batch loop: no automatic collection inside a batch, a youngest-generation collection after it, and one full collection when the pass ends. + :func:`one_pass_garbage_collection` runs several calls of a pass function + as one pass, with one full collection at the end. A population-aggregate variable is a policyengine-us formula that sums or ranks over every person or household in its engine @@ -66,6 +68,7 @@ "group_to_household_positions", "household_batch_plan", "household_position_batches", + "one_pass_garbage_collection", "record_engine_branches", "refuse_batch_population_aggregates", "select_households_by_position", @@ -375,12 +378,42 @@ def collect_pass_garbage() -> None: CPython's own full collections are throttled against the build's multi-GB long-lived heap, so without an explicit sweep the skeletons accumulate for the run's lifetime. One full collection per pass (a target family, - an input stage) is cheap next to the pass's engine work. + an input stage) is cheap next to the pass's engine work. Inside + :func:`one_pass_garbage_collection` it leaves the collection to the end. """ + if _PASS_GARBAGE_DEFERRED: + return gc.collect() +#: While set, :func:`collect_pass_garbage` leaves the full collection to +#: :func:`one_pass_garbage_collection`. +_PASS_GARBAGE_DEFERRED = False + + +@contextmanager +def one_pass_garbage_collection() -> Iterator[None]: + """Run the pass calls inside as one pass: one full collection at the end. + + A reuse of an earlier pass (``microcosm.build.household_pass_reuse``) + calls the pass function once per batch of households it reruns, and each + call ends with :func:`collect_pass_garbage`; a full pass collects once. + Nested uses collect once, when the outermost ends, also after an + exception. + """ + + global _PASS_GARBAGE_DEFERRED + already_deferred = _PASS_GARBAGE_DEFERRED + _PASS_GARBAGE_DEFERRED = True + try: + yield + finally: + _PASS_GARBAGE_DEFERRED = already_deferred + if not already_deferred: + gc.collect() + + @contextmanager def automatic_gc_suspended() -> Iterator[None]: """Avoid surprise full-graph cyclic GC inside memory-heavy PE batches.""" diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/household_pass_inputs.py b/packages/microcosm-build/src/microcosm/build/us_runtime/household_pass_inputs.py new file mode 100644 index 0000000000..0fe026a2c4 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/household_pass_inputs.py @@ -0,0 +1,208 @@ +"""The columns a household-batched policyengine-us pass can read. + +``microcosm.build.household_pass_reuse`` reuses a pass's values for +households whose input columns are unchanged. For policyengine-us those +columns are every variable the pass's variable can read, the variable itself +included, because a stored column replaces a formula. The list starts from +the static dependency graph +(``PolicyEngineUSVariableMetadataIndex.variable_dependency_closure``: every +variable its formulas read through ``entity(...)``, ``add`` and similar +calls, on any branch and in any period). That graph does not follow some +reads, so the list adds, until nothing new appears: + +* every string in a listed variable's class source, or among its formula + functions' constants and closure values, that names an engine variable, + with each such variable's own graph. That covers + ``simulation.get_branch(...).calculate("...")``, + ``simulation.get_holder("...")``, ``all_of_variables([...])`` and formulas + generated at import without a class source (the state flags such as ``CA`` + read ``state_code_str`` this way); +* each listed variable's ``defined_for`` variable (state programs name their + state flag as a ``StateCode`` member, not a string). + +A string that names a variable without reading it only adds a column to the +digest, which can rerun a household but never reuses a wrong value. + +Reads inside module-level helper functions are not followed: in +policyengine-us 2.2.1 the only variables those helpers read outside the list +are behavioral-response measurements (``household_net_income``, +``marginal_tax_rate`` and similar), which a simulation without a reform does +not compute. ``test_us_household_pass_inputs.py`` pins that set, so an engine +whose helpers read anything else fails until it is reviewed. +""" + +from __future__ import annotations + +import ast +import enum +import inspect +import textwrap +import types +from functools import cache + +from microcosm.build.household_pass_reuse import HouseholdPassInputs, PassInputColumn +from microcosm.frame.adapters.policyengine_us import PolicyEngineUSVariableMetadataIndex + +__all__ = ["us_household_pass_inputs"] + + +def _stored_default(definition) -> object: + """The default as a dataset stores it: Enum members by name.""" + + default = definition.default_value + if isinstance(default, enum.Enum): + return default.name + return default + + +def _absent_reads_default(definition) -> bool: + """Whether a stored default gives the engine the same input as no column. + + Not for a variable the engine computes (a formula, or an ``adds`` or + ``subtracts`` sum): a stored value replaces it. Not for a nonzero numeric + default either: the engine uprates a stored value it reads at a later + period and divides a yearly value into months, while an absent column + reads the default unchanged. + """ + + computed = ( + bool(definition.formulas) + or bool(getattr(definition, "adds", None)) + or bool(getattr(definition, "subtracts", None)) + ) + if computed: + return False + if definition.value_type in (int, float): + return definition.default_value == 0 + return True + + +def us_household_pass_inputs( + variable: str, + *, + metadata_index: PolicyEngineUSVariableMetadataIndex, + system, +) -> HouseholdPassInputs: + """Every engine variable ``variable``'s pass can read, with its table. + + ``system`` is the installed policyengine-us tax-benefit system; it gives + each variable's entity, default and whether it has a formula. Graph nodes + the system does not define (a few parameter paths the static index reads + as names) are left out, because the engine reads no column by those names. + """ + + closure = metadata_index.variable_dependency_closure(variable) + names = _readable_variables(variable, metadata_index=metadata_index, system=system) + columns = tuple( + PassInputColumn( + name=name, + entity=system.variables[name].entity.key, + default=_stored_default(system.variables[name]), + absent_reads_default=_absent_reads_default(system.variables[name]), + ) + for name in names + ) + return HouseholdPassInputs( + variable=variable, + columns=columns, + description=( + f"policyengine-us {closure.engine_version}: {len(columns)} variables " + f"{variable} can read (dependency graph sha256 {closure.sha256}, " + "with string and defined_for reads)" + ), + ) + + +def _graph_variables( + name: str, *, metadata_index: PolicyEngineUSVariableMetadataIndex, system +) -> set[str]: + try: + closure = metadata_index.variable_dependency_closure(name) + except ValueError: + # A variable the static index does not define (one generated at + # import) has no graph to add; its own name is still listed. + return {name} + return { + node + for node in (*closure.input_leaves, *closure.formula_nodes) + if node in system.variables + } + + +@cache +def _class_string_constants(variable_class: type) -> frozenset[str]: + try: + source = inspect.getsource(variable_class) + except (OSError, TypeError): + # A class generated at import has no class source; its formula + # functions' constants are read in _formula_strings. + return frozenset() + return frozenset( + node.value + for node in ast.walk(ast.parse(textwrap.dedent(source))) + if isinstance(node, ast.Constant) and isinstance(node.value, str) + ) + + +def _code_strings(code: types.CodeType) -> set[str]: + strings = set() + for constant in code.co_consts: + if isinstance(constant, str): + strings.add(constant) + elif isinstance(constant, types.CodeType): + strings |= _code_strings(constant) + return strings + + +def _formula_strings(definition) -> set[str]: + """Strings among the formula functions' constants and closure values.""" + + strings: set[str] = set() + for formula in definition.formulas.values(): + code = getattr(formula, "__code__", None) + if code is not None: + strings |= _code_strings(code) + for cell in getattr(formula, "__closure__", None) or (): + try: + value = cell.cell_contents + except ValueError: + continue + if isinstance(value, str): + strings.add(value) + elif isinstance(value, (list, tuple, set, frozenset)): + strings |= {item for item in value if isinstance(item, str)} + return strings + + +def _extra_reads(definition, system) -> set[str]: + """Variables ``definition`` reads that its static graph may not show.""" + + reads = { + value + for value in ( + _class_string_constants(type(definition)) | _formula_strings(definition) + ) + if value in system.variables + } + defined_for = getattr(definition, "defined_for", None) + if defined_for is not None: + reads.add(getattr(defined_for, "name", defined_for)) + reads.discard(definition.name) + return {read for read in reads if read in system.variables} + + +def _readable_variables( + variable: str, *, metadata_index: PolicyEngineUSVariableMetadataIndex, system +) -> list[str]: + names = _graph_variables(variable, metadata_index=metadata_index, system=system) + names.add(variable) + pending = sorted(names) + while pending: + definition = system.variables[pending.pop()] + for read in sorted(_extra_reads(definition, system) - names): + added = {read} | _graph_variables( + read, metadata_index=metadata_index, system=system + ) + pending.extend(sorted(added - names)) + names |= added + return sorted(names) diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_household_pass_inputs.py b/packages/microcosm-build/tests/engine_contract/us/test_us_household_pass_inputs.py new file mode 100644 index 0000000000..caa38ea813 --- /dev/null +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_household_pass_inputs.py @@ -0,0 +1,201 @@ +"""The input columns of a household-batched policyengine-us pass. + +``us_household_pass_inputs`` lists every variable a pass's formulas can +read, the variable itself included, with the table it is stored in and the +value an absent column reads as: the engine's static dependency graph, plus +the reads that graph does not follow (names in strings, such as a branch +simulation's ``calculate("income_tax")``, ``get_holder("has_itin")`` and +``all_of_variables([...])``, and ``defined_for`` state flags). +``microcosm.build.household_pass_reuse`` digests these columns per household +to decide which households a later pass can take from an earlier one. +``engine_workflow/us/test_us_post_calibration_take_up_inputs.py`` checks the +list against the names the engine reads while it computes each variable. +""" + +from __future__ import annotations + +import pytest + +from microcosm.build.household_pass_reuse import PassInputColumn +from microcosm.build.us_runtime.household_pass_inputs import us_household_pass_inputs +from microcosm.frame.adapters.policyengine_us import PolicyEngineUSVariableMetadataIndex + + +@pytest.fixture(scope="module") +def metadata_index() -> PolicyEngineUSVariableMetadataIndex: + return PolicyEngineUSVariableMetadataIndex() + + +@pytest.fixture(scope="module") +def system(): + from policyengine_us.system import system + + return system + + +@pytest.mark.parametrize("variable", ["uncapped_ssi", "is_medicaid_eligible"]) +def test_pass_inputs_are_every_engine_variable_in_the_graph( + variable, metadata_index, system +) -> None: + closure = metadata_index.variable_dependency_closure(variable) + inputs = us_household_pass_inputs( + variable, metadata_index=metadata_index, system=system + ) + + # The graph also names a few parameter paths; the engine reads no column + # by those names. + graph = { + name + for name in {*closure.input_leaves, *closure.formula_nodes} + if name in system.variables + } + names = [column.name for column in inputs.columns] + assert inputs.variable == variable + assert names == sorted(set(names)) + assert graph <= set(names) + assert variable in names + assert closure.sha256 in inputs.description + for column in inputs.columns: + assert column.entity == system.variables[column.name].entity.key + + +def test_pass_inputs_add_the_reads_the_static_graph_does_not_follow( + metadata_index, system +) -> None: + def added(variable: str) -> set[str]: + closure = metadata_index.variable_dependency_closure(variable) + listed = { + column.name + for column in us_household_pass_inputs( + variable, metadata_index=metadata_index, system=system + ).columns + } + return listed - {*closure.input_leaves, *closure.formula_nodes} + + assert added("uncapped_ssi") == set() + medicaid_added = added("is_medicaid_eligible") + # tax_liability_if_itemizing computes income_tax in a branch simulation; + # has_tin reads a stored has_itin through get_holder; is_adult_for_medicaid + # combines its _fc and _nfc variables with all_of_variables; state + # programs are defined_for a state flag. + for name in ( + "income_tax", + "has_itin", + "is_adult_for_medicaid_fc", + "is_military", + "refundable_payroll_tax_credit", + "CA", + "NY", + ): + assert name in medicaid_added, name + + +def test_only_plain_inputs_with_neutral_defaults_read_as_absent( + metadata_index, system +) -> None: + """A stored value equal to the default is the same as no column only for + an input without a formula whose default survives the engine's monthly + division and uprating: a non-numeric value, a boolean, or zero.""" + + columns = { + column.name: column + for variable in ("uncapped_ssi", "is_medicaid_eligible") + for column in us_household_pass_inputs( + variable, metadata_index=metadata_index, system=system + ).columns + } + + assert columns["employment_income_before_lsr"] == PassInputColumn( + "employment_income_before_lsr", "person", default=0, absent_reads_default=True + ) + assert columns["takes_up_snap_if_eligible"] == PassInputColumn( + "takes_up_snap_if_eligible", "spm_unit", default=True, absent_reads_default=True + ) + # Enum defaults are stored by member name. + assert columns["immigration_status_str"] == PassInputColumn( + "immigration_status_str", "person", default="CITIZEN", absent_reads_default=True + ) + assert columns["county_fips"] == PassInputColumn( + "county_fips", "household", default="", absent_reads_default=True + ) + # Nonzero numeric defaults: a stored default is uprated or divided. + assert columns["age"].absent_reads_default is False + assert columns["state_fips"] == PassInputColumn( + "state_fips", "household", default=6, absent_reads_default=False + ) + # A stored value replaces a formula, including an ``adds`` sum. + assert columns["uncapped_ssi"].absent_reads_default is False + medically_needy_expenses = columns["medicaid_medically_needy_medical_expenses"] + assert medically_needy_expenses.absent_reads_default is False + + +#: Variables that module-level helper functions of listed formulas read and +#: the list leaves out. Each is a behavioral-response measurement, read by +#: ``get_behavioral_response_measurements``, ``calculate_income_lsr_effect`` or +#: ``calculate_substitution_lsr_effect`` only when the simulation has a +#: baseline branch and nonzero elasticities; the passes build no reform, and +#: the engine-workflow trace finds none of them read. +_REVIEWED_HELPER_READS = { + "household_net_income", + "income_elasticity", + "marginal_tax_rate", + "marginal_tax_rate_on_capital_gains", + "substitution_elasticity", +} + + +def _code_strings_and_names(code): + strings, names = set(), set(code.co_names) + for constant in code.co_consts: + if isinstance(constant, str): + strings.add(constant) + elif isinstance(constant, type(code)): + nested_strings, nested_names = _code_strings_and_names(constant) + strings |= nested_strings + names |= nested_names + return strings, names + + +@pytest.mark.parametrize("variable", ["uncapped_ssi", "is_medicaid_eligible"]) +def test_helper_functions_read_no_unreviewed_variable_outside_the_list( + variable, metadata_index, system +) -> None: + """The list does not follow module-level helpers; this pins what they read. + + Walks every policyengine-us function a listed formula calls by global + name, and the functions those call, and collects the strings in their + code that name engine variables. + """ + + import types + + listed = { + column.name + for column in us_household_pass_inputs( + variable, metadata_index=metadata_index, system=system + ).columns + } + helper_reads: set[str] = set() + for name in listed: + for formula in system.variables[name].formulas.values(): + _, names = _code_strings_and_names(formula.__code__) + pending = [formula.__globals__.get(global_name) for global_name in names] + seen = set() + while pending: + helper = pending.pop() + if ( + not isinstance(helper, types.FunctionType) + or not helper.__module__.startswith("policyengine_us") + or helper in seen + ): + continue + seen.add(helper) + strings, names = _code_strings_and_names(helper.__code__) + helper_reads |= { + value for value in strings if value in system.variables + } + pending.extend( + helper.__globals__.get(global_name) for global_name in names + ) + + assert helper_reads - listed == _REVIEWED_HELPER_READS diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_post_calibration_take_up_inputs.py b/packages/microcosm-build/tests/engine_contract/us/test_us_post_calibration_take_up_inputs.py new file mode 100644 index 0000000000..da9975c510 --- /dev/null +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_post_calibration_take_up_inputs.py @@ -0,0 +1,303 @@ +"""Which columns written between the release tool's repeated passes reach them. + +``tools/build_us_fiscal_refresh_release.py`` computes December +``uncapped_ssi`` and ``is_medicaid_eligible`` for every person on the +pre-calibration frame and again on the calibrated export frame. These tests +intersect each variable's static dependency graph in the installed engine +(``variable_dependency_closure``: every variable its formulas can read, on any +branch and in any period) with the columns the stages between the two passes +write. + +On policyengine-us 2.2.1: + +* No column written between the two SSI passes is a node of December + ``uncapped_ssi``'s graph, and the graph reads no weight and no population + aggregate. +* Between the two Medicaid passes, the SNAP take-up stage's + ``takes_up_snap_if_eligible`` and three outputs of the other-health-insurance + stage are inputs of ``is_medicaid_eligible``. SNAP take-up reaches it only + through the Medicaid work-requirement formulas, which ``is_medicaid_eligible`` + reads only when a work requirement applies, and none applies in 2024. The + other-health outputs also reach it through formulas that run in 2024. + +``engine_workflow/us/test_us_post_calibration_take_up_inputs.py`` runs the +release tool's passes on a small frame to confirm both results. +""" + +from __future__ import annotations + +import ast +from collections import defaultdict +from pathlib import Path + +import pytest + +from microcosm.build.us_runtime.household_pass_inputs import us_household_pass_inputs +from microcosm.frame.adapters.policyengine_us import ( + PolicyEngineUSVariableMetadataIndex, + VariableDependencyClosure, +) +from test_support.microcosm_build.us_batched_target_materialization import ( + _load_builder_module, +) +from test_support.microcosm_build.us_post_calibration_take_up_inputs import ( + MEDICAID_PASS_VARIABLE, + SSI_PASS_VARIABLE, + StageOutputs, + main_frame_assignments, + stages_between_medicaid_passes, + stages_between_ssi_passes, +) + +#: The variables ``is_medicaid_eligible`` reads only inside +#: ``if .applies:`` blocks. +_WORK_REQUIREMENT_READS = ( + "ar_medicaid_work_requirement_eligible", + "is_medicaid_work_requirement_applicable_adult", + "medicaid_work_requirement_eligible", +) +#: Formulas the population-aggregate scan in +#: ``test_us_batched_target_materialization.py`` marks and its review accepts +#: as joins within one household: each person's claiming tax unit is in the +#: person's own household. A selection of whole households keeps them. +_HOUSEHOLD_CLAIMING_JOINS = ( + "medicaid_has_known_claiming_tax_unit", + "medicaid_household_income", + "medicaid_household_size", +) + + +@pytest.fixture(scope="module") +def builder(): + return _load_builder_module() + + +@pytest.fixture(scope="module") +def metadata_index() -> PolicyEngineUSVariableMetadataIndex: + return PolicyEngineUSVariableMetadataIndex() + + +def _closure_identity(closure: VariableDependencyClosure) -> tuple: + return ( + closure.engine_version, + len(closure.input_leaves), + len(closure.formula_nodes), + len(closure.edges), + closure.sha256, + ) + + +def _graph_nodes_written( + closure: VariableDependencyClosure, stages: tuple[StageOutputs, ...] +) -> dict[str, tuple[str, ...]]: + nodes = set(closure.input_leaves) | set(closure.formula_nodes) + return {stage.name: tuple(sorted(set(stage.columns) & nodes)) for stage in stages} + + +def _listed_columns_written( + variable: str, + stages: tuple[StageOutputs, ...], + metadata_index: PolicyEngineUSVariableMetadataIndex, +) -> dict[str, tuple[str, ...]]: + """The same intersection with the reuse's full input list, which adds the + reads the static graph does not follow.""" + + from policyengine_us.system import system + + listed = { + column.name + for column in us_household_pass_inputs( + variable, metadata_index=metadata_index, system=system + ).columns + } + return {stage.name: tuple(sorted(set(stage.columns) & listed)) for stage in stages} + + +def _reachable( + closure: VariableDependencyClosure, + *, + without_edges: set[tuple[str, str]], +) -> set[str]: + dependencies: dict[str, set[str]] = defaultdict(set) + for consumer, dependency in closure.edges: + if (consumer, dependency) not in without_edges: + dependencies[consumer].add(dependency) + reached: set[str] = set() + pending = [closure.root] + while pending: + variable = pending.pop() + if variable in reached: + continue + reached.add(variable) + pending.extend(dependencies[variable] - reached) + return reached + + +def _applies_block_lines(source_path: Path) -> list[range]: + """Line ranges of ``if .applies:`` bodies in one source file.""" + + tree = ast.parse(source_path.read_text()) + ranges = [] + for node in ast.walk(tree): + if ( + isinstance(node, ast.If) + and isinstance(node.test, ast.Attribute) + and node.test.attr == "applies" + ): + ranges.append(range(node.body[0].lineno, node.body[-1].end_lineno + 1)) + return ranges + + +def test_release_tool_runs_these_stages_between_the_ssi_passes(builder) -> None: + """The stage list the other tests use is the one ``_main`` runs. + + Every ``base_frame = f(...)`` between the first December SSI pass and the + second names its stage, in build order, and the export frame is the + calibrated-weight copy of ``base_frame``. A new stage between the passes + fails here until its columns are checked. + """ + + assignments = main_frame_assignments(builder) + between = [ + called + for line, called in assignments.base_frame_calls + if assignments.first_ssi_pass_line < line < assignments.second_ssi_pass_line + ] + + assert between == [ + stage.builder_call for stage in stages_between_ssi_passes(builder) + ] + assert assignments.ssi_pass_frames == ("base_frame", "export_frame") + export_calls = [ + (line, called) + for line, called in assignments.export_frame_calls + if line < assignments.second_ssi_pass_line + ] + assert sorted(called for _, called in export_calls) == [ + "_with_calibrated_weights", + "_with_l0_refit_weights", + ] + last_stage_line = max( + line + for line, _ in assignments.base_frame_calls + if line < assignments.second_ssi_pass_line + ) + assert all(line > last_stage_line for line, _ in export_calls) + assert [stage.builder_call for stage in stages_between_medicaid_passes()] == ( + between[between.index("_with_medicaid_take_up_outputs") :] + ) + + +def test_no_column_written_between_the_ssi_passes_reaches_december_uncapped_ssi( + builder, metadata_index +) -> None: + closure = metadata_index.variable_dependency_closure(SSI_PASS_VARIABLE) + # A new engine graph needs this review again. + assert _closure_identity(closure) == ( + "2.2.1", + 53, + 61, + 183, + "703cfdf988d2fbecf05ea020f94d879e90f7553d449e165542afa070a86b6043", + ) + + stages = stages_between_ssi_passes(builder) + assert _graph_nodes_written(closure, stages) == {stage.name: () for stage in stages} + assert _listed_columns_written(SSI_PASS_VARIABLE, stages, metadata_index) == { + stage.name: () for stage in stages + } + + +def test_snap_take_up_and_other_health_outputs_are_medicaid_eligibility_inputs( + metadata_index, +) -> None: + closure = metadata_index.variable_dependency_closure(MEDICAID_PASS_VARIABLE) + assert _closure_identity(closure) == ( + "2.2.1", + 481, + 2179, + 7733, + "f771a669de6b5e94310b44f249eb6ab09f93fe4e4bd854eb64257311af08f17a", + ) + + expected = { + "medicaid_take_up": (), + "snap_state_take_up": ("takes_up_snap_if_eligible",), + "other_health_insurance": ( + "health_insurance_premiums", + "health_insurance_premiums_without_medicare_part_b", + "is_self_employed", + ), + } + stages = stages_between_medicaid_passes() + assert _graph_nodes_written(closure, stages) == expected + assert ( + _listed_columns_written(MEDICAID_PASS_VARIABLE, stages, metadata_index) + == expected + ) + + +def test_snap_take_up_reaches_medicaid_eligibility_only_through_work_requirements( + builder, metadata_index +) -> None: + """In 2024, SNAP take-up cannot change Medicaid eligibility; the + other-health outputs still can. + + ``is_medicaid_eligible`` reads the three work-requirement variables only + inside ``if .applies:`` blocks, and both parameters are + false in the release year. Without those three reads the graph no longer + reaches ``takes_up_snap_if_eligible``, and it still reaches every + other-health output that the full graph reaches. + """ + + import policyengine_us + from policyengine_us import CountryTaxBenefitSystem + + # Receipt paths are relative to the installed package directory. + package_root = Path(policyengine_us.__file__).parent + closure = metadata_index.variable_dependency_closure(MEDICAID_PASS_VARIABLE) + for variable in _WORK_REQUIREMENT_READS: + receipts = [ + receipt + for receipt in metadata_index.consumer_receipts(variable) + if receipt.consumer == MEDICAID_PASS_VARIABLE + ] + assert receipts, variable + for receipt in receipts: + applies_blocks = _applies_block_lines(package_root / receipt.path) + assert any(receipt.line in block for block in applies_blocks), receipt + + parameters = CountryTaxBenefitSystem().parameters(f"{builder.PERIOD}-01-01") + assert parameters.gov.hhs.medicaid.eligibility.work_requirements.applies is False + assert parameters.gov.states.ar.dhs.medicaid.work_requirements.applies is False + + reached = _reachable( + closure, + without_edges={ + (MEDICAID_PASS_VARIABLE, variable) for variable in _WORK_REQUIREMENT_READS + }, + ) + assert "takes_up_snap_if_eligible" not in reached + assert { + "health_insurance_premiums", + "health_insurance_premiums_without_medicare_part_b", + "is_self_employed", + } <= reached + + +def test_neither_pass_variable_reads_weights_or_population_aggregates( + builder, metadata_index +) -> None: + """New weights leave both values unchanged, and so does dropping other + households: no formula in either graph reads a weight or aggregates over + the simulation's population.""" + + for variable, household_joins in ( + (SSI_PASS_VARIABLE, set()), + (MEDICAID_PASS_VARIABLE, set(_HOUSEHOLD_CLAIMING_JOINS)), + ): + closure = metadata_index.variable_dependency_closure(variable) + nodes = set(closure.input_leaves) | set(closure.formula_nodes) + assert not nodes & set(builder.US_POPULATION_AGGREGATE_VARIABLES), variable + assert not {node for node in nodes if node.endswith("_weight")}, variable + assert nodes & set(_HOUSEHOLD_CLAIMING_JOINS) == household_joins, variable diff --git a/packages/microcosm-build/tests/engine_free/shared/test_household_pass_reuse.py b/packages/microcosm-build/tests/engine_free/shared/test_household_pass_reuse.py new file mode 100644 index 0000000000..8144df1cb4 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_household_pass_reuse.py @@ -0,0 +1,439 @@ +"""Reusing a household-batched pass for households whose inputs are unchanged. + +``microcosm.build.household_pass_reuse`` keeps a pass's per-person values and +a digest of each household's rows (entity IDs, membership, row order and the +pass's input columns). A later pass over a changed frame takes the earlier +value for every household whose digest matches, runs the engine on the other +households plus a few unchanged ones as a check, and runs every household +again if that check disagrees. + +These tests stand in for the engine with a function of each household's rows. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.household_pass_reuse import ( + HouseholdPassInputs, + PassInputColumn, + record_household_pass, + reuse_household_pass, +) +from microcosm.frame import EntitySchema, Frame, MassChange, WeightKind, Weights + +_SCHEMA = EntitySchema(group_entities=("household", "tax_unit")) + +_INPUTS = HouseholdPassInputs( + variable="benefit", + columns=( + PassInputColumn("income", "person", default=0.0, absent_reads_default=True), + PassInputColumn( + "is_disabled", "person", default=False, absent_reads_default=True + ), + PassInputColumn( + "claims_credit", "tax_unit", default=False, absent_reads_default=True + ), + PassInputColumn( + "region", "household", default="NONE", absent_reads_default=True + ), + # A column the engine computes when it is absent: a stored value + # replaces the formula, so its presence matters. + PassInputColumn( + "countable_income", "person", default=0.0, absent_reads_default=False + ), + ), +) + + +def _frame( + *, + income=(100.0, 0.0, 250.0, 0.0, 40.0, 0.0, 0.0), + tax_units=(10, 10, 20, 30, 30, 40, 50), + person_ids=(1, 2, 3, 4, 5, 6, 7), + households=(1, 1, 2, 3, 3, 4, 5), +) -> Frame: + person = pd.DataFrame( + { + "person_id": np.asarray(person_ids, dtype="int64"), + "person_household_id": np.asarray(households, dtype="int64"), + "person_tax_unit_id": np.asarray(tax_units, dtype="int64"), + "income": np.asarray(income, dtype=np.float64), + "unrelated_note": np.arange(len(person_ids), dtype=np.float64), + } + ) + tax_unit_ids = np.unique(person["person_tax_unit_id"].to_numpy()) + household_ids = np.unique(person["person_household_id"].to_numpy()) + tables = { + "person": person, + "tax_unit": pd.DataFrame( + { + "tax_unit_id": tax_unit_ids, + "claims_credit": tax_unit_ids % 20 == 0, + } + ), + "household": pd.DataFrame( + { + "household_id": household_ids, + "region": np.asarray( + [ + "NORTH" if household % 2 else "SOUTH" + for household in household_ids + ], + dtype=object, + ), + } + ), + } + return Frame( + tables, + _SCHEMA, + { + "household": Weights( + np.arange(1.0, len(household_ids) + 1.0), WeightKind.DESIGN + ) + }, + ) + + +def _with_tables(frame: Frame, **tables: pd.DataFrame) -> Frame: + return Frame( + {entity: tables.get(entity, frame.table(entity)) for entity in frame.entities}, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + ) + + +class _StandInEngine: + """A per-household function of the rows, recording the households it saw.""" + + def __init__(self, *, offset: float = 0.0) -> None: + self.offset = offset + self.calls: list[list[int]] = [] + + def __call__(self, frame: Frame) -> np.ndarray: + person = frame.table("person") + tax_unit = frame.table("tax_unit").set_index("tax_unit_id") + household = frame.table("household").set_index("household_id") + self.calls.append(sorted(household.index.tolist())) + income = person["income"].to_numpy(dtype=np.float64) + if "countable_income" in person: + income = person["countable_income"].to_numpy(dtype=np.float64) + unit_total = person.groupby("person_tax_unit_id")["income"].transform("sum") + credit = tax_unit["claims_credit"].reindex(person["person_tax_unit_id"]) + region = household["region"].reindex(person["person_household_id"]) + disabled = ( + person["is_disabled"].to_numpy(dtype=bool) + if "is_disabled" in person + else np.zeros(len(person), dtype=bool) + ) + # Each person's place among the people of their household, so the + # order of rows inside a household matters as it can to an engine. + place_in_household = person.groupby("person_household_id").cumcount() + return ( + income + + 0.5 * unit_total.to_numpy() + + 1_000.0 * credit.to_numpy(dtype=bool) + + 10.0 * (region.to_numpy() == "NORTH") + + 7.0 * disabled + + 0.25 * place_in_household.to_numpy() + + self.offset + ) + + +def _record(frame: Frame, engine: _StandInEngine): + return record_household_pass(frame, engine(frame), _INPUTS) + + +def _reuse( + record, + frame: Frame, + engine: _StandInEngine, + *, + checked: int = 1, + batch: int = 100, +): + return reuse_household_pass( + record, + frame, + recompute=engine, + checked_household_count=checked, + batch_household_count=batch, + ) + + +def test_unchanged_households_take_their_recorded_values() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + + result = _reuse(record, frame, engine, checked=2) + + assert result.values.tobytes() == engine(frame).tobytes() + assert (result.reused_households, result.recomputed_households) == (5, 0) + assert result.checked_households == 2 + assert result.check_failed is False + # One run over the two checked households only, spread over the frame. + assert engine.calls[1] == [1, 3] + + +def test_reruns_take_one_batch_of_households_at_a_time() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + person = frame.table("person").copy() + person.loc[person["person_id"].isin([1, 4, 7]), "income"] = 33.0 + changed = _with_tables(frame, person=person) + + result = _reuse(record, changed, engine, checked=0, batch=2) + + # Households 1, 3 and 5 changed; selections of at most two households. + assert engine.calls[1:3] == [[1, 3], [5]] + assert result.values.tobytes() == engine(changed).tobytes() + + +def test_a_changed_input_reruns_only_its_household() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + person = frame.table("person").copy() + person.loc[person["person_id"] == 4, "income"] = 75.0 + changed = _with_tables(frame, person=person) + + result = _reuse(record, changed, engine, checked=0) + + assert result.values.tobytes() == engine(changed).tobytes() + assert (result.reused_households, result.recomputed_households) == (4, 1) + assert engine.calls[1] == [3] + + +def test_columns_outside_the_inputs_are_not_changes() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + person = frame.table("person").copy() + person["unrelated_note"] = -1.0 + person["another_column"] = 5 + household = frame.table("household").copy() + household["household_weight_copy"] = 3.0 + + result = _reuse( + record, + _with_tables(frame, person=person, household=household), + engine, + checked=0, + ) + + assert (result.reused_households, result.recomputed_households) == (5, 0) + assert len(engine.calls) == 1 + + +def test_an_absent_input_reads_as_its_default() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + + person = frame.table("person").copy() + person["is_disabled"] = False + defaults_written = _with_tables(frame, person=person) + result = _reuse(record, defaults_written, engine, checked=0) + assert (result.reused_households, result.recomputed_households) == (5, 0) + + person.loc[person["person_id"] == 6, "is_disabled"] = True + one_changed = _with_tables(frame, person=person) + result = _reuse(record, one_changed, engine, checked=0) + assert (result.reused_households, result.recomputed_households) == (4, 1) + assert result.values.tobytes() == engine(one_changed).tobytes() + + +def test_a_stored_computed_column_reruns_every_household() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + person = frame.table("person").copy() + # Zero everywhere, so it differs from the formula only where income is + # positive, but any stored value replaces the formula. + person["countable_income"] = 0.0 + stored = _with_tables(frame, person=person) + + result = _reuse(record, stored, engine, checked=0) + + assert (result.reused_households, result.recomputed_households) == (0, 5) + assert result.values.tobytes() == engine(stored).tobytes() + + +def test_group_and_household_inputs_count_for_their_household() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + tax_unit = frame.table("tax_unit").copy() + tax_unit.loc[tax_unit["tax_unit_id"] == 30, "claims_credit"] = True + household = frame.table("household").copy() + household.loc[household["household_id"] == 5, "region"] = "SOUTH" + changed = _with_tables(frame, tax_unit=tax_unit, household=household) + + result = _reuse(record, changed, engine, checked=0) + + assert (result.reused_households, result.recomputed_households) == (3, 2) + assert engine.calls[1] == [3, 5] + assert result.values.tobytes() == engine(changed).tobytes() + + +def test_new_weights_and_dropped_households_reuse_values_by_person_id() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + kept = frame.table("person")["person_household_id"].isin([1, 3, 5]).to_numpy() + selected = frame.select(kept) + reweighted = selected.with_weights( + "household", + Weights(np.asarray([9.0, 0.5, 2.0]), WeightKind.CALIBRATED), + mass=MassChange(factor=11.5 / 9.0, reason="test calibration"), + ) + + result = _reuse(record, reweighted, engine, checked=0) + + expected = pd.Series(engine(frame), index=frame.table("person")["person_id"]) + person_ids = reweighted.table("person")["person_id"].to_numpy() + assert result.values.tobytes() == expected.reindex(person_ids).to_numpy().tobytes() + assert (result.reused_households, result.recomputed_households) == (3, 0) + + +@pytest.mark.parametrize( + "change", + [ + # Two people in household 1 swap incomes. + dict(income=(0.0, 100.0, 250.0, 0.0, 40.0, 0.0, 0.0)), + # Person 5 moves to a new tax unit inside household 3. + dict(tax_units=(10, 10, 20, 30, 31, 40, 50)), + # Household 3's two people change places in the table. + dict( + person_ids=(1, 2, 3, 5, 4, 6, 7), + income=(100.0, 0.0, 250.0, 40.0, 0.0, 0.0, 0.0), + tax_units=(10, 10, 20, 30, 30, 40, 50), + ), + # Income of -0.0 instead of 0.0: the same number, different bits. + dict(income=(100.0, 0.0, 250.0, -0.0, 40.0, 0.0, 0.0)), + ], + ids=["swapped_values", "moved_tax_unit", "reordered_rows", "negative_zero"], +) +def test_changes_inside_a_household_rerun_it(change) -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + changed = _frame(**change) + + result = _reuse(record, changed, engine, checked=0) + + assert result.recomputed_households == 1 + assert result.values.tobytes() == engine(changed).tobytes() + + +def test_wider_storage_of_the_same_values_is_not_a_change() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + person = frame.table("person").copy() + person["income"] = person["income"].astype(np.float32) + tax_unit = frame.table("tax_unit").copy() + tax_unit["claims_credit"] = tax_unit["claims_credit"].astype(np.int8) + + result = _reuse( + record, _with_tables(frame, person=person, tax_unit=tax_unit), engine, checked=0 + ) + + assert (result.reused_households, result.recomputed_households) == (5, 0) + + +def test_households_missing_from_the_record_are_rerun() -> None: + frame = _frame() + engine = _StandInEngine() + record = _record(frame, engine) + grown = _frame( + income=(100.0, 0.0, 250.0, 0.0, 40.0, 0.0, 0.0, 30.0), + tax_units=(10, 10, 20, 30, 30, 40, 50, 60), + person_ids=(1, 2, 3, 4, 5, 6, 7, 8), + households=(1, 1, 2, 3, 3, 4, 5, 6), + ) + + result = _reuse(record, grown, engine, checked=0) + + assert (result.reused_households, result.recomputed_households) == (5, 1) + assert engine.calls[1] == [6] + + +def test_a_failed_check_reruns_every_household() -> None: + """The recorded values disagree with a fresh run on a checked household, + as they would if the pass read a column missing from its input list.""" + + frame = _frame() + record = _record(frame, _StandInEngine()) + engine = _StandInEngine(offset=1.0) + + result = _reuse(record, frame, engine, checked=1) + + assert result.check_failed is True + # The check ran on household 1, then every household ran again. + assert engine.calls == [[1], [1, 2, 3, 4, 5]] + assert result.values.tobytes() == engine(frame).tobytes() + + +@pytest.mark.parametrize("refused_by", ["record", "reuse"]) +def test_a_refusal_runs_the_whole_frame(refused_by) -> None: + """A caller that knows one household's value can depend on another's + rows (a link across households) refuses reuse, at record time for the + recorded frame or at reuse time for the new one.""" + + frame = _frame() + engine = _StandInEngine() + reason = "a claiming link crosses households" + record = record_household_pass( + frame, + engine(frame), + _INPUTS, + reuse_refused=reason if refused_by == "record" else None, + ) + + result = reuse_household_pass( + record, + frame, + recompute=engine, + checked_household_count=1, + batch_household_count=100, + reuse_refused=reason if refused_by == "reuse" else None, + ) + + assert result.reuse_refused == reason + assert (result.reused_households, result.recomputed_households) == (0, 5) + assert result.checked_households == 0 + assert engine.calls[1] == [1, 2, 3, 4, 5] + assert result.values.tobytes() == engine(frame).tobytes() + + +def test_record_and_reuse_refuse_misaligned_values() -> None: + frame = _frame() + engine = _StandInEngine() + with pytest.raises(ValueError, match="one value per person"): + record_household_pass(frame, engine(frame)[:-1], _INPUTS) + + record = _record(frame, engine) + person = frame.table("person").copy() + person.loc[person["person_id"] == 4, "income"] = 75.0 + with pytest.raises(ValueError, match="one value per person"): + reuse_household_pass( + record, + _with_tables(frame, person=person), + recompute=lambda run_frame: np.zeros(1, dtype=np.float64), + checked_household_count=0, + batch_household_count=100, + ) + with pytest.raises(ValueError, match="dtype"): + reuse_household_pass( + record, + _with_tables(frame, person=person), + recompute=lambda run_frame: np.zeros(run_frame.n("person"), dtype=bool), + checked_household_count=0, + batch_household_count=100, + ) 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 99af81e33a..610b73768b 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 @@ -9220,10 +9220,16 @@ def fake_ssi_uncapped_amount( *, simulation=None, maximum_microsim_batch_size=None, + refuse_population_aggregates=None, ): + captured.setdefault("ssi_uncapped_refusals", []).append( + refuse_population_aggregates + ) captured["ssi_uncapped_stage_called"] = True captured["ssi_uncapped_batch_size"] = maximum_microsim_batch_size - return np.zeros(4, dtype=np.float64) + values = np.zeros(4, dtype=np.float64) + captured.setdefault("ssi_uncapped_calls", []).append((frame, values)) + return values fake_band_targets = { "under_18": 1_001_922.0, @@ -9303,6 +9309,74 @@ def fake_ssi_take_up_gate(diagnostics, *, targets): "_ssi_person_uncapped_amount", fake_ssi_uncapped_amount, ) + + # The post-calibration passes reuse the pre-calibration pass records. The + # stand-ins keep the frame and values each record was made from, and the + # reuse runs its recompute on the frame it was given, as a real reuse + # does for changed households, so the assertions below can check which + # frame, values and pass function main() wired to each variable. + def fake_household_pass_record(frame, values, *, variable, reuse_refused=None): + captured.setdefault("household_pass_records", []).append( + (variable, frame, values, reuse_refused) + ) + return SimpleNamespace(variable=variable) + + def fake_reuse_household_pass( + record, + frame, + *, + recompute, + maximum_microsim_batch_size, + description, + telemetry=None, + telemetry_stage="take_up_final_diagnostics", + reuse_refused=None, + ): + captured.setdefault("household_pass_reuses", []).append( + ( + record.variable, + frame, + maximum_microsim_batch_size, + telemetry_stage, + reuse_refused, + ) + ) + values = recompute(frame) + # A real reuse also hands the pass a selection of some households. + recompute(rerun_selection) + captured.setdefault("household_pass_values", {})[record.variable] = values + return SimpleNamespace(values=values) + + rerun_selection = SimpleNamespace(name="selection of rerun households") + + def fake_medicaid_person_eligibility( + frame, + *, + simulation=None, + maximum_microsim_batch_size=None, + refuse_population_aggregates=None, + ): + values = np.zeros(4, dtype=bool) + captured.setdefault("medicaid_eligibility_calls", []).append( + (frame, maximum_microsim_batch_size, refuse_population_aggregates) + ) + return values + + monkeypatch.setattr( + builder, "_medicaid_person_eligibility", fake_medicaid_person_eligibility + ) + + # A reason per frame, so the assertions can check which frame's claiming + # links each Medicaid record and reuse was judged on. + def fake_medicaid_claim_crossing(frame): + return f"claim-crossing:{id(frame)}" + + monkeypatch.setattr( + builder, "_medicaid_claim_crossing", fake_medicaid_claim_crossing + ) + + monkeypatch.setattr(builder, "_household_pass_record", fake_household_pass_record) + monkeypatch.setattr(builder, "_reuse_household_pass", fake_reuse_household_pass) monkeypatch.setattr(builder, "with_us_ssi_take_up", fake_with_ssi_take_up) monkeypatch.setattr(builder, "us_ssi_take_up_gate", fake_ssi_take_up_gate) # The digest reads the persisted flag column, which the stub above never @@ -9456,8 +9530,14 @@ def fake_with_medicaid_outputs( seed, substitutions=(), maximum_microsim_batch_size=None, + eligibility_recorder=None, ): captured["health_stage_events"].append("medicaid") + captured["medicaid_first_pass_frame"] = frame + if eligibility_recorder is not None: + eligibility = np.zeros(4, dtype=bool) + captured["medicaid_first_pass_eligibility"] = eligibility + eligibility_recorder(frame, eligibility) return frame, {} def fake_medicaid_gate(diagnostics): @@ -9757,6 +9837,8 @@ def fake_final_ssi_diagnostics( reporter_source_ids, ): captured["final_ssi_diagnostics_called"] = True + captured["final_ssi_frame"] = frame + captured["ssi_final_uncapped"] = uncapped_ssi captured["final_ssi_diagnostics_targets"] = dict(targets) captured["final_ssi_diagnostics_assignment_priors"] = dict(assignment_priors) captured["final_ssi_diagnostics_prior_basis"] = prior_basis @@ -9770,8 +9852,11 @@ def fake_final_medicaid_diagnostics( seed, substitutions, maximum_microsim_batch_size=None, + eligibility=None, ): captured["final_medicaid_diagnostics_called"] = True + captured["final_medicaid_frame"] = frame + captured["final_medicaid_eligibility"] = eligibility return {} monkeypatch.setattr(builder, "_with_l0_refit_weights", fake_l0_refit_weights) @@ -10532,6 +10617,63 @@ def fake_release_gate_failures(*args, **kwargs): assert "final_medicaid_diagnostics_called" not in captured else: assert captured["final_medicaid_diagnostics_called"] is True + # Both pre-calibration passes leave a record of the frame they ran on and + # the values they returned; the post-calibration values come from reusing + # them on the export frame with the matching pass function; a quarantined + # Medicaid evaluation reuses nothing. + batch_size = builder.DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE + (first_ssi_frame, first_ssi_values), *later_ssi_calls = captured[ + "ssi_uncapped_calls" + ] + (ssi_record, medicaid_record) = captured["household_pass_records"] + assert ssi_record[0] == "uncapped_ssi" + assert ssi_record[1] is first_ssi_frame + assert ssi_record[2] is first_ssi_values + assert ssi_record[3] is None + assert medicaid_record[0] == "is_medicaid_eligible" + assert medicaid_record[1] is captured["medicaid_first_pass_frame"] + assert medicaid_record[2] is captured["medicaid_first_pass_eligibility"] + assert medicaid_record[3] == ( + f"claim-crossing:{id(captured['medicaid_first_pass_frame'])}" + ) + export_frame = captured["final_ssi_frame"] + reuses = captured["household_pass_reuses"] + assert reuses[0][0] == "uncapped_ssi" + assert reuses[0][1] is export_frame + assert reuses[0][2:] == (batch_size, "take_up_final_diagnostics", None) + # The SSI recompute is the SSI pass, run on the export frame. + assert len(later_ssi_calls) == 2 + assert later_ssi_calls[0][0] is export_frame + assert later_ssi_calls[1][0] is rerun_selection + # The whole export frame keeps the pass's own refusal rule; a selection + # of households holds part of the population and refuses aggregates. + assert captured["ssi_uncapped_refusals"] == [None, None, True] + assert ( + captured["ssi_final_uncapped"] + is captured["household_pass_values"]["uncapped_ssi"] + ) + if terminal_mode == "integrity": + assert len(reuses) == 1 + assert "medicaid_eligibility_calls" not in captured + else: + assert captured["final_medicaid_frame"] is export_frame + assert reuses[1][0] == "is_medicaid_eligible" + assert reuses[1][1] is export_frame + assert reuses[1][2:] == ( + batch_size, + "medicaid_final_diagnostics", + f"claim-crossing:{id(export_frame)}", + ) + # The Medicaid recompute is the Medicaid pass, run on the export frame. + (export_call, selection_call) = captured["medicaid_eligibility_calls"] + assert export_call[0] is export_frame + assert export_call[1:] == (batch_size, None) + assert selection_call[0] is rerun_selection + assert selection_call[1:] == (batch_size, True) + assert ( + captured["final_medicaid_eligibility"] + is captured["household_pass_values"]["is_medicaid_eligible"] + ) assert captured["voluntary_filing_stage_called"] is True assert captured["voluntary_filing_seed"] == 0 assert captured["voluntary_filing_gate_called"] is True diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_calibration_pass_reuse_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_calibration_pass_reuse_tool.py new file mode 100644 index 0000000000..a302af35f9 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_calibration_pass_reuse_tool.py @@ -0,0 +1,246 @@ +"""The release tool's wrappers around the household pass reuse. + +``tools/build_us_fiscal_refresh_release.py`` reuses its pre-calibration +December SSI and Medicaid eligibility passes after calibration through +``_reuse_household_pass``, and refuses the Medicaid reuse for a frame whose +Medicaid claiming links cross households (``_medicaid_claim_crossing``). +These tests use a stand-in for the pass and a record made with +``microcosm.build.household_pass_reuse`` directly, so they need no engine. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.household_pass_reuse import ( + HouseholdPassInputs, + PassInputColumn, + record_household_pass, +) +from microcosm.build.us_runtime import household_batches +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights +from test_support.microcosm_build.us_batched_target_materialization import ( + _load_builder_module, +) + +_INPUTS = HouseholdPassInputs( + variable="is_medicaid_eligible", + columns=( + PassInputColumn("income", "person", default=0.0, absent_reads_default=True), + ), +) + + +@pytest.fixture(scope="module") +def builder(): + return _load_builder_module() + + +def _frame(*, income=(10.0, 0.0, 20.0, 30.0), claims=None) -> Frame: + person = pd.DataFrame( + { + "person_id": np.asarray([1, 2, 3, 4], dtype="int64"), + "person_household_id": np.asarray([1, 1, 2, 3], dtype="int64"), + "person_tax_unit_id": np.asarray([10, 11, 20, 30], dtype="int64"), + "person_spm_unit_id": np.asarray([100, 100, 200, 300], dtype="int64"), + "person_family_id": np.asarray([1000, 1000, 2000, 3000], dtype="int64"), + "person_marital_unit_id": np.asarray([1, 2, 3, 4], dtype="int64"), + "income": np.asarray(income, dtype=np.float64), + } + ) + if claims is not None: + person["medicaid_claiming_tax_unit_id"] = np.asarray(claims, dtype="int64") + tables = {"person": person} + for entity in ("tax_unit", "spm_unit", "family", "marital_unit"): + ids = np.unique(person[f"person_{entity}_id"].to_numpy()) + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + tables["household"] = pd.DataFrame( + {"household_id": np.asarray([1, 2, 3], dtype="int64")} + ) + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.ones(3), WeightKind.DESIGN)}, + ) + + +class _StandInPass: + def __init__(self) -> None: + self.household_sets: list[list[int]] = [] + + def __call__(self, frame: Frame) -> np.ndarray: + self.household_sets.append( + sorted(frame.table("household")["household_id"].tolist()) + ) + return frame.table("person")["income"].to_numpy() > 15.0 + + +class _RecordingTelemetry: + def __init__(self, *, fail: bool = False) -> None: + self.events: list[tuple[str, str, dict]] = [] + self.fail = fail + + def stage(self, stage, *, message=None, status="running", **details): + if self.fail: + raise OSError("telemetry write failed") + self.events.append((stage, message, details)) + + +def test_claims_inside_households_allow_reuse(builder) -> None: + assert builder._medicaid_claim_crossing(_frame()) is None + # Person 2 is claimed by tax unit 10, in their own household. + assert builder._medicaid_claim_crossing(_frame(claims=(0, 10, 0, 0))) is None + + +def test_a_claim_across_households_refuses_reuse(builder) -> None: + # Person 3, in household 2, is claimed by tax unit 10 in household 1. + reason = builder._medicaid_claim_crossing(_frame(claims=(0, 0, 10, 0))) + + assert reason is not None and "own household" in reason + + +def test_reuse_reports_its_stage_before_and_after(builder) -> None: + frame = _frame() + stand_in = _StandInPass() + record = record_household_pass(frame, stand_in(frame), _INPUTS) + changed = _frame(income=(10.0, 0.0, 20.0, 5.0)) + telemetry = _RecordingTelemetry() + + reuse = builder._reuse_household_pass( + record, + changed, + recompute=stand_in, + maximum_microsim_batch_size=1, + description="Medicaid eligibility", + telemetry=telemetry, + telemetry_stage="medicaid_final_diagnostics", + ) + + assert reuse.values.tobytes() == stand_in(changed).tobytes() + assert [stage for stage, _, _ in telemetry.events] == [ + "medicaid_final_diagnostics", + "medicaid_final_diagnostics", + ] + assert telemetry.events[1][2]["household_pass_reuse"] == { + "variable": "is_medicaid_eligible", + "reused_households": 2, + "recomputed_households": 1, + "checked_households": 1, + "check_failed": False, + "reuse_refused": None, + } + + +def test_a_telemetry_failure_does_not_stop_the_reuse(builder, capsys) -> None: + frame = _frame() + stand_in = _StandInPass() + record = record_household_pass(frame, stand_in(frame), _INPUTS) + + reuse = builder._reuse_household_pass( + record, + frame, + recompute=stand_in, + maximum_microsim_batch_size=2, + description="Medicaid eligibility", + telemetry=_RecordingTelemetry(fail=True), + ) + + assert reuse.values.tobytes() == stand_in(frame).tobytes() + assert "did not reach telemetry" in capsys.readouterr().out + + +def test_an_unbatched_build_reruns_in_one_selection(builder) -> None: + frame = _frame() + stand_in = _StandInPass() + record = record_household_pass(frame, stand_in(frame), _INPUTS) + changed = _frame(income=(11.0, 0.0, 21.0, 31.0)) + + reuse = builder._reuse_household_pass( + record, + changed, + recompute=stand_in, + maximum_microsim_batch_size=0, + description="Medicaid eligibility", + ) + + assert stand_in.household_sets[1:] == [[1, 2, 3]] + assert reuse.recomputed_households == 3 + + +def test_a_refused_reuse_runs_the_whole_export_frame(builder, capsys) -> None: + frame = _frame() + stand_in = _StandInPass() + record = record_household_pass(frame, stand_in(frame), _INPUTS) + + reuse = builder._reuse_household_pass( + record, + frame, + recompute=stand_in, + maximum_microsim_batch_size=2, + description="Medicaid eligibility", + reuse_refused="a claim crosses households", + ) + + assert reuse.reuse_refused == "a claim crosses households" + assert (reuse.reused_households, reuse.recomputed_households) == (0, 3) + assert stand_in.household_sets[1:] == [[1, 2, 3]] + assert "without reuse: a claim crosses households" in capsys.readouterr().out + + +def test_one_pass_garbage_collection_collects_once_and_restores(monkeypatch) -> None: + collections: list[int] = [] + monkeypatch.setattr( + household_batches.gc, "collect", lambda *args: collections.append(1) + ) + + with household_batches.one_pass_garbage_collection(): + household_batches.collect_pass_garbage() + with household_batches.one_pass_garbage_collection(): + household_batches.collect_pass_garbage() + assert collections == [] + assert collections == [1] + assert household_batches._PASS_GARBAGE_DEFERRED is False + + with pytest.raises(RuntimeError): + with household_batches.one_pass_garbage_collection(): + raise RuntimeError("pass failed") + assert collections == [1, 1] + assert household_batches._PASS_GARBAGE_DEFERRED is False + household_batches.collect_pass_garbage() + assert collections == [1, 1, 1] + + +def test_a_reuse_runs_one_full_collection_for_all_its_batches( + builder, monkeypatch +) -> None: + """Each pass call ends with a full collection; a reuse of several batches + runs one, as a full pass does.""" + + collections: list[int] = [] + monkeypatch.setattr( + household_batches.gc, "collect", lambda *args: collections.append(1) + ) + frame = _frame() + stand_in = _StandInPass() + record = record_household_pass(frame, stand_in(frame), _INPUTS) + # Household 1 changes; household 2 is the one checked household. + changed = _frame(income=(11.0, 0.0, 20.0, 30.0)) + + def pass_with_collection(run_frame): + values = stand_in(run_frame) + builder.collect_pass_garbage() + return values + + builder._reuse_household_pass( + record, + changed, + recompute=pass_with_collection, + maximum_microsim_batch_size=1, + description="Medicaid eligibility", + ) + + # Two pass calls, one per batch of one household, and one collection. + assert stand_in.household_sets[1:] == [[1], [2]] + assert collections == [1] 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 5502c44aba..94d1c35e97 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 @@ -362,6 +362,9 @@ "gate_shadow.py", "geography_ladder.py", "hours_worked.py", + # Lists the engine columns a household pass reads, from the installed + # policyengine-us; reads no frame and treats no population. + "household_pass_inputs.py", "h5_io.py", # US artifact I/O; no population treatment. # Household batches for the release's policyengine-us passes: the # partition, the frame checks, the population-aggregate refusal and diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_calibration_take_up_inputs.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_calibration_take_up_inputs.py new file mode 100644 index 0000000000..5cbe18fbfe --- /dev/null +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_calibration_take_up_inputs.py @@ -0,0 +1,310 @@ +"""The release tool's repeated December SSI and Medicaid passes on a small frame. + +``tools/build_us_fiscal_refresh_release.py`` computes December +``uncapped_ssi`` (``_ssi_person_uncapped_amount``) and ``is_medicaid_eligible`` +(``_medicaid_person_eligibility``) for every person before calibration and +again on the calibrated export frame. These tests run those two functions, in +household batches, on seven households, and compare the arrays byte for byte: + +* after writing every column the stages between the passes write, in two + different value sets; +* after calibrated weights, and after an L0 selection that drops households + (compared by person ID). + +``engine_contract/us/test_us_post_calibration_take_up_inputs.py`` checks the +same columns against the engine's static dependency graphs. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import numpy as np +import pytest + +from test_support.microcosm_build.us_batched_target_materialization import ( + _load_builder_module, +) +from test_support.microcosm_build.us_post_calibration_take_up_inputs import ( + DISABLED_WORKER_PERSON_ID, + SELF_EMPLOYED_PERSON_ID, + by_person_id, + stages_between_medicaid_passes, + stages_between_ssi_passes, + take_up_pass_frame, + with_person_columns, + with_stage_outputs, +) + +#: Three household batches over the seven households. +_BATCH_SIZE = 3 + + +@pytest.fixture(scope="module") +def builder(): + return _load_builder_module() + + +@pytest.fixture(scope="module") +def system(): + from policyengine_us import CountryTaxBenefitSystem + + return CountryTaxBenefitSystem() + + +def _december_uncapped_ssi(builder, frame, batch_size=_BATCH_SIZE) -> np.ndarray: + return builder._ssi_person_uncapped_amount( + frame, maximum_microsim_batch_size=batch_size + ) + + +def _medicaid_eligibility(builder, frame, batch_size=_BATCH_SIZE) -> np.ndarray: + return builder._medicaid_person_eligibility( + frame, maximum_microsim_batch_size=batch_size + ) + + +def _changed_person_ids(frame, before, after) -> list[int]: + changed = by_person_id(frame, after) != by_person_id(frame, before) + return changed.index[changed.to_numpy()].tolist() + + +def test_columns_written_between_the_ssi_passes_leave_december_ssi_unchanged( + builder, system +) -> None: + frame = take_up_pass_frame() + stages = stages_between_ssi_passes(builder) + before = _december_uncapped_ssi(builder, frame) + # The aged single person, the aged couple and the disabled worker. + assert np.count_nonzero(before > 0) >= 3 + + for variant in (0, 1): + staged = with_stage_outputs(frame, stages, variant=variant, system=system) + after = _december_uncapped_ssi(builder, staged) + assert after.dtype == before.dtype + assert after.tobytes() == before.tobytes(), variant + + # An input of the graph does change the array, so the comparison can fail. + more_earnings = with_person_columns( + frame, DISABLED_WORKER_PERSON_ID, employment_income_before_lsr=9_000.0 + ) + assert _changed_person_ids( + frame, before, _december_uncapped_ssi(builder, more_earnings) + ) == [DISABLED_WORKER_PERSON_ID] + + +def test_snap_take_up_leaves_medicaid_eligibility_unchanged_in_2024( + builder, system +) -> None: + frame = take_up_pass_frame() + medicaid_take_up, snap_state_take_up, _ = stages_between_medicaid_passes() + before = _medicaid_eligibility(builder, frame) + assert before.any() and not before.all() + + for variant in (0, 1): + staged = with_stage_outputs( + frame, + (medicaid_take_up, snap_state_take_up), + variant=variant, + system=system, + ) + after = _medicaid_eligibility(builder, staged) + assert after.dtype == before.dtype + assert after.tobytes() == before.tobytes(), variant + + +def test_premium_attribution_changes_medicaid_eligibility(builder) -> None: + """The other-health stage sets ``is_self_employed`` from self-employment + income and attributes reported premiums to ``health_insurance_premiums``. + The self-employed health insurance deduction then lowers this adult's + income below California's Medicaid limit, so the eligibility computed + after the stage differs from the one computed before it.""" + + frame = take_up_pass_frame() + before = _medicaid_eligibility(builder, frame) + attributed = with_person_columns( + frame, + SELF_EMPLOYED_PERSON_ID, + health_insurance_premiums=5_000.0, + is_self_employed=True, + ) + after = _medicaid_eligibility(builder, attributed) + + assert _changed_person_ids(frame, before, after) == [SELF_EMPLOYED_PERSON_ID] + assert not by_person_id(frame, before)[SELF_EMPLOYED_PERSON_ID] + assert by_person_id(frame, after)[SELF_EMPLOYED_PERSON_ID] + + +def test_calibrated_weights_and_household_selection_keep_both_arrays( + builder, +) -> None: + """Both export-frame constructions give each remaining person the value + the pre-calibration pass gave them, at any batch composition.""" + + frame = take_up_pass_frame() + ssi_before = by_person_id(frame, _december_uncapped_ssi(builder, frame)) + medicaid_before = by_person_id(frame, _medicaid_eligibility(builder, frame)) + reweighted = builder._with_calibrated_weights( + frame, np.asarray([5.5, 0.25, 9.0, 1.75, 3.0, 12.0, 0.5]) + ) + # L0 selection keeps households 1, 3, 4, 6 and 7. + selected = builder._with_l0_refit_weights( + frame, + SimpleNamespace( + weight_entity="household", + selected_entity_ids=np.asarray([1, 3, 4, 6, 7]), + weights=np.asarray([2.5, 8.0, 0.75, 4.0, 1.5]), + ), + ) + assert selected.n("household") == 5 + + for export_frame, batch_size in ((reweighted, 2), (selected, 1)): + person_ids = export_frame.table("person")["person_id"].to_numpy() + for compute, before in ( + (_december_uncapped_ssi, ssi_before), + (_medicaid_eligibility, medicaid_before), + ): + after = compute(builder, export_frame, batch_size) + expected = before.reindex(person_ids).to_numpy() + assert after.dtype == expected.dtype + assert after.tobytes() == expected.tobytes(), (compute, batch_size) + + +def test_reused_december_ssi_equals_a_fresh_pass_on_the_export_frame( + builder, system +) -> None: + """Every household keeps its inputs, so the post-calibration December SSI + pass takes every value from the first pass and runs one batch as a + check.""" + + frame = take_up_pass_frame() + record = builder._household_pass_record( + frame, _december_uncapped_ssi(builder, frame), variable="uncapped_ssi" + ) + staged = with_stage_outputs( + frame, stages_between_ssi_passes(builder), variant=0, system=system + ) + export_frame = builder._with_l0_refit_weights( + staged, + SimpleNamespace( + weight_entity="household", + selected_entity_ids=np.asarray([1, 3, 4, 6, 7]), + weights=np.asarray([2.5, 8.0, 0.75, 4.0, 1.5]), + ), + ) + + reuse = builder._reuse_household_pass( + record, + export_frame, + recompute=lambda run_frame: _december_uncapped_ssi(builder, run_frame), + maximum_microsim_batch_size=_BATCH_SIZE, + description="December SSI candidate amounts", + ) + + assert reuse.values.tobytes() == ( + _december_uncapped_ssi(builder, export_frame).tobytes() + ) + assert (reuse.reused_households, reuse.recomputed_households) == (5, 0) + assert (reuse.checked_households, reuse.check_failed) == (_BATCH_SIZE, False) + + +def test_reused_medicaid_eligibility_reruns_the_households_whose_inputs_changed( + builder, system +) -> None: + """SNAP take-up flags that differ from the engine default and the + other-health stage's premium attribution change the inputs of three + households, which are rerun; the other four keep their first-pass + values.""" + + frame = take_up_pass_frame() + record = builder._household_pass_record( + frame, _medicaid_eligibility(builder, frame), variable="is_medicaid_eligible" + ) + medicaid_take_up, snap_state_take_up, _ = stages_between_medicaid_passes() + # Variant 0 sets every other SPM unit's flag to False (the engine default + # is True): households 2, 4 and 6. Attribution changes household 4. + staged = with_stage_outputs( + frame, (medicaid_take_up, snap_state_take_up), variant=0, system=system + ) + attributed = with_person_columns( + staged, + SELF_EMPLOYED_PERSON_ID, + health_insurance_premiums=5_000.0, + is_self_employed=True, + ) + export_frame = builder._with_calibrated_weights( + attributed, np.asarray([5.5, 0.25, 9.0, 1.75, 3.0, 12.0, 0.5]) + ) + + reuse = builder._reuse_household_pass( + record, + export_frame, + recompute=lambda run_frame: _medicaid_eligibility(builder, run_frame), + maximum_microsim_batch_size=2, + description="Medicaid eligibility", + ) + + fresh = _medicaid_eligibility(builder, export_frame) + assert reuse.values.tobytes() == fresh.tobytes() + assert (reuse.reused_households, reuse.recomputed_households) == (4, 3) + assert (reuse.checked_households, reuse.check_failed) == (2, False) + # The self-employed adult's eligibility comes from the rerun, not the + # first pass, which had it ineligible. + assert by_person_id(export_frame, reuse.values)[SELF_EMPLOYED_PERSON_ID] + + +@pytest.mark.parametrize( + ("variable", "period"), + [("uncapped_ssi", "2024-12"), ("is_medicaid_eligible", 2024)], +) +def test_the_engine_reads_only_listed_columns_while_it_computes_the_pass( + variable, period, builder, system, monkeypatch +) -> None: + """Every variable policyengine-us calculates or looks up while it computes + the pass variable is in the reuse's input list, except the household + weight, which only weights the returned array.""" + + from policyengine_core.simulations.simulation import Simulation + from policyengine_us import Microsimulation + + from microcosm.build.us_runtime.household_pass_inputs import ( + us_household_pass_inputs, + ) + + reads: set[str] = set() + recording = False + calculate = Simulation.calculate + get_holder = Simulation.get_holder + + def recording_calculate(self, variable_name, *args, **kwargs): + if recording: + reads.add(variable_name) + return calculate(self, variable_name, *args, **kwargs) + + def recording_get_holder(self, variable_name): + if recording: + reads.add(variable_name) + return get_holder(self, variable_name) + + monkeypatch.setattr(Simulation, "calculate", recording_calculate) + monkeypatch.setattr(Simulation, "get_holder", recording_get_holder) + frame = take_up_pass_frame() + simulation = Microsimulation( + dataset=builder._dataset_from_frame( + frame, assert_no_formula_owned_columns=False, period_only=True + ) + ) + recording = True + simulation.calculate(variable, period=period, map_to="person") + recording = False + + listed = { + column.name + for column in us_household_pass_inputs( + variable, + metadata_index=builder._formula_owned_gate_adapter(), + system=system, + ).columns + } + assert len(reads) > 100 + assert reads - listed == {"household_weight"} diff --git a/test_support/microcosm_build/us_post_calibration_take_up_inputs.py b/test_support/microcosm_build/us_post_calibration_take_up_inputs.py new file mode 100644 index 0000000000..1cfb9b1abd --- /dev/null +++ b/test_support/microcosm_build/us_post_calibration_take_up_inputs.py @@ -0,0 +1,413 @@ +"""Columns the US release tool writes between its repeated take-up passes. + +``tools/build_us_fiscal_refresh_release.py`` computes person ``uncapped_ssi`` +for December (``_ssi_person_uncapped_amount``) and person +``is_medicaid_eligible`` (``_medicaid_person_eligibility``) once on the +pre-calibration frame and again on the calibrated export frame. Each pass runs +policyengine-us over every household in batches. The later array equals the +earlier one, selected by person ID, only when no column written between the two +passes is an input of the variable, when the variable reads no weight and no +population aggregate, and when calibration keeps whole households. + +These helpers name the stages ``_main`` runs between the two passes, in build +order, with the table each stage writes to and the columns it writes there +(each module's declared output constant; a read of the stage code found no +column outside those constants). The engine-contract test intersects them with +the engine's static dependency graph, and the engine-workflow test writes them +onto a small frame and compares the arrays the release tool's own passes return. +""" + +from __future__ import annotations + +import ast +import inspect +from dataclasses import dataclass +from types import ModuleType + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime.medicaid_take_up import US_MEDICAID_TAKE_UP_VARIABLE +from microcosm.build.us_runtime.org_wages import US_ORG_WAGES_OUTPUT_COLUMNS +from microcosm.build.us_runtime.other_health_insurance import ( + US_OTHER_HEALTH_INSURANCE_STAGE_OUTPUT_COLUMNS, +) +from microcosm.build.us_runtime.scf_auto_loans import US_SCF_AUTO_LOAN_OUTPUT_COLUMNS +from microcosm.build.us_runtime.scf_education_debt import ( + US_SCF_EDUCATION_DEBT_OUTPUT_COLUMNS, +) +from microcosm.build.us_runtime.sipp_tips import US_SIPP_TIPS_OUTPUT_COLUMNS +from microcosm.build.us_runtime.sipp_vehicles import US_SIPP_VEHICLE_OUTPUT_COLUMNS +from microcosm.build.us_runtime.snap_take_up import US_SNAP_TAKE_UP_OUTPUT_COLUMN +from microcosm.build.us_runtime.ssi_take_up import US_SSI_TAKE_UP_OUTPUT_COLUMNS +from microcosm.build.us_runtime.voluntary_filing import ( + US_VOLUNTARY_FILING_OUTPUT_COLUMNS, +) +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + +#: The two engine variables the release tool computes before and after +#: calibration. December SSI is read at ``f"{PERIOD}-12"``; Medicaid +#: eligibility at ``PERIOD``. +SSI_PASS_VARIABLE = "uncapped_ssi" +MEDICAID_PASS_VARIABLE = "is_medicaid_eligible" + + +@dataclass(frozen=True) +class StageOutputs: + """One ``_main`` stage that reassigns ``base_frame`` between the passes.""" + + name: str + #: The function ``_main`` calls to build the new ``base_frame``. + builder_call: str + #: The frame table the stage writes to. + entity: str + columns: tuple[str, ...] + + +def stages_between_ssi_passes(builder: ModuleType) -> tuple[StageOutputs, ...]: + """Stages from the first December SSI pass to the export frame, in order. + + The first SSI pass feeds the SSI take-up stage, so that stage's output is + written after it. The SCF education-debt stage runs only with + ``--scf-education-debt``. + """ + + return ( + StageOutputs( + "ssi_take_up", + "with_us_ssi_take_up", + "person", + tuple(US_SSI_TAKE_UP_OUTPUT_COLUMNS), + ), + StageOutputs( + "scf_auto_loans", + "with_us_scf_auto_loan_inputs", + "household", + tuple(US_SCF_AUTO_LOAN_OUTPUT_COLUMNS), + ), + StageOutputs( + "scf_education_debt", + "_with_scf_education_debt_stage", + "person", + tuple(US_SCF_EDUCATION_DEBT_OUTPUT_COLUMNS), + ), + StageOutputs( + "sipp_vehicles", + "with_us_sipp_vehicle_inputs", + "household", + tuple(US_SIPP_VEHICLE_OUTPUT_COLUMNS), + ), + StageOutputs( + "voluntary_filing", + "with_us_voluntary_filing_input", + "tax_unit", + tuple(US_VOLUNTARY_FILING_OUTPUT_COLUMNS), + ), + StageOutputs( + "sipp_tips", + "with_us_sipp_tip_inputs", + "person", + tuple(US_SIPP_TIPS_OUTPUT_COLUMNS), + ), + StageOutputs( + "org_wages", + "with_us_org_wages_inputs", + "person", + tuple(US_ORG_WAGES_OUTPUT_COLUMNS), + ), + StageOutputs( + "aca_marketplace", + "_with_aca_marketplace_source_outputs", + "tax_unit", + tuple(builder.US_ACA_SOURCE_OUTPUT_COLUMNS), + ), + *stages_between_medicaid_passes(), + ) + + +def stages_between_medicaid_passes() -> tuple[StageOutputs, ...]: + """Stages from the first Medicaid eligibility pass to the export frame. + + The first Medicaid pass runs inside ``_with_medicaid_take_up_outputs`` and + feeds the Medicaid take-up stage, so that stage's output is written after + it. + """ + + return ( + StageOutputs( + "medicaid_take_up", + "_with_medicaid_take_up_outputs", + "person", + (US_MEDICAID_TAKE_UP_VARIABLE,), + ), + StageOutputs( + "snap_state_take_up", + "_with_snap_state_take_up_outputs", + "spm_unit", + (US_SNAP_TAKE_UP_OUTPUT_COLUMN,), + ), + StageOutputs( + "other_health_insurance", + "with_us_other_health_insurance_inputs", + "person", + tuple(US_OTHER_HEALTH_INSURANCE_STAGE_OUTPUT_COLUMNS), + ), + ) + + +@dataclass(frozen=True) +class MainFrameAssignments: + """Where ``_main`` runs the passes and reassigns its frames, by line.""" + + first_ssi_pass_line: int + second_ssi_pass_line: int + #: ``(line, called function)`` for each ``base_frame = f(...)`` (or + #: ``base_frame, ... = f(...)``) in ``_main``, in source order. + base_frame_calls: tuple[tuple[int, str], ...] + #: ``(line, called function)`` for each ``export_frame = f(...)``. + export_frame_calls: tuple[tuple[int, str], ...] + #: The variable each SSI pass reads its frame from, in source order. + ssi_pass_frames: tuple[str, ...] + + +def _called_name(call: ast.Call) -> str: + function = call.func + if isinstance(function, ast.Name): + return function.id + if isinstance(function, ast.Attribute): + return function.attr + return ast.dump(function) + + +def _assigned_names(target: ast.expr) -> tuple[str, ...]: + if isinstance(target, ast.Name): + return (target.id,) + if isinstance(target, ast.Tuple): + return tuple( + element.id for element in target.elts if isinstance(element, ast.Name) + ) + return () + + +def _statements_outside_nested_scopes(node: ast.AST): + """Every node below ``node`` except bodies of nested functions and lambdas.""" + + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + continue + yield child + yield from _statements_outside_nested_scopes(child) + + +def main_frame_assignments(builder: ModuleType) -> MainFrameAssignments: + """Read ``_main``'s source for the SSI passes and frame reassignments.""" + + # ``_main`` is a module-level function, so its source parses as it stands. + source_lines, first_line = inspect.getsourcelines(builder._main) + tree = ast.parse("".join(source_lines)) + (main,) = ( + node + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name == "_main" + ) + ssi_passes: list[tuple[int, str]] = [] + base_frame_calls: list[tuple[int, str]] = [] + export_frame_calls: list[tuple[int, str]] = [] + for node in _statements_outside_nested_scopes(main): + if isinstance(node, ast.Call): + # A December SSI pass is a direct call, or the reuse of the + # recorded first pass on another frame. + called = _called_name(node) + frame_argument = None + if called == "_ssi_person_uncapped_amount": + frame_argument = node.args[0] + elif ( + called == "_reuse_household_pass" + and isinstance(node.args[0], ast.Name) + and node.args[0].id == "ssi_pass_record" + ): + frame_argument = node.args[1] + if frame_argument is not None: + ssi_passes.append( + ( + first_line + node.lineno - 1, + frame_argument.id + if isinstance(frame_argument, ast.Name) + else ast.dump(frame_argument), + ) + ) + if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Call): + continue + names = {name for target in node.targets for name in _assigned_names(target)} + called = _called_name(node.value) + line = first_line + node.lineno - 1 + if "base_frame" in names: + base_frame_calls.append((line, called)) + if "export_frame" in names: + export_frame_calls.append((line, called)) + ssi_passes.sort() + if len(ssi_passes) != 2: + raise AssertionError( + f"_main should run exactly two December SSI passes: {ssi_passes}." + ) + return MainFrameAssignments( + first_ssi_pass_line=ssi_passes[0][0], + second_ssi_pass_line=ssi_passes[1][0], + base_frame_calls=tuple(sorted(base_frame_calls)), + export_frame_calls=tuple(sorted(export_frame_calls)), + ssi_pass_frames=tuple(frame for _, frame in ssi_passes), + ) + + +# --------------------------------------------------------------------------- +# A small real-engine frame: seven households over five states +# --------------------------------------------------------------------------- + +#: Person ID of the self-employed California adult whose Medicaid eligibility +#: the other-health stage's premium attribution changes. +SELF_EMPLOYED_PERSON_ID = 5 +#: Person ID of the disabled Texas adult with a little employment income. +DISABLED_WORKER_PERSON_ID = 4 + +#: (person_id, household, tax_unit, spm_unit, family, marital_unit, age) +_PERSONS = ( + (1, 1, 10, 100, 1000, 10000, 70.0), + (2, 2, 20, 200, 2000, 20000, 68.0), + (3, 2, 20, 200, 2000, 20000, 72.0), + (4, 3, 30, 300, 3000, 30000, 45.0), + (5, 4, 40, 400, 4000, 40000, 30.0), + (6, 5, 50, 500, 5000, 50000, 35.0), + (7, 5, 50, 500, 5000, 50001, 6.0), + (8, 6, 60, 600, 6000, 60000, 40.0), + (9, 6, 60, 600, 6000, 60001, 10.0), + (10, 7, 70, 700, 7000, 70000, 50.0), +) +#: (household_id, state_fips) +_HOUSEHOLDS = ( + (1, 6), + (2, 36), + (3, 48), + (4, 6), + (5, 6), + (6, 12), + (7, 24), +) + + +def take_up_pass_frame() -> Frame: + """Seven households that reach SSI, Medicaid and SNAP in 2024. + + One aged single person and one aged couple with small Social Security + benefits, a disabled adult and a disabled child with low earnings in the + household, a self-employed adult just above California's Medicaid income + limit, a parent and child with low earnings, and one higher-income adult. + """ + + person_ids = np.asarray([row[0] for row in _PERSONS], dtype="int64") + person = pd.DataFrame( + { + "person_id": person_ids, + "person_household_id": np.asarray([row[1] for row in _PERSONS], "int64"), + "person_tax_unit_id": np.asarray([row[2] for row in _PERSONS], "int64"), + "person_spm_unit_id": np.asarray([row[3] for row in _PERSONS], "int64"), + "person_family_id": np.asarray([row[4] for row in _PERSONS], "int64"), + "person_marital_unit_id": np.asarray([row[5] for row in _PERSONS], "int64"), + "age": np.asarray([row[6] for row in _PERSONS]), + "employment_income_before_lsr": np.asarray( + [0.0, 0.0, 0.0, 3_000.0, 0.0, 20_000.0, 0.0, 30_000.0, 0.0, 90_000.0] + ), + "self_employment_income_before_lsr": np.asarray( + [0.0, 0.0, 0.0, 0.0, 25_000.0, 0.0, 0.0, 0.0, 0.0, 0.0] + ), + "social_security_retirement": np.asarray( + [6_000.0, 9_000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + ), + "meets_ssi_disability_criteria": np.isin(person_ids, (4, 9)), + } + ) + tables = {"person": person} + for entity in ("tax_unit", "spm_unit", "family", "marital_unit"): + ids = np.unique(person[f"person_{entity}_id"].to_numpy()) + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + tables["household"] = pd.DataFrame( + { + "household_id": np.asarray([row[0] for row in _HOUSEHOLDS], "int64"), + "state_fips": np.asarray([row[1] for row in _HOUSEHOLDS], "int64"), + } + ) + return Frame( + tables, + US_SCHEMA, + { + "household": Weights( + np.asarray([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]), WeightKind.DESIGN + ) + }, + ) + + +def _stage_output_values( + column: str, row_count: int, variant: int, system +) -> np.ndarray: + """Values for one stage output; variants 0 and 1 differ on every row.""" + + rows = np.arange(row_count) + variable = system.variables.get(column) + value_type = float if variable is None else variable.value_type + if value_type is bool: + return (rows + variant) % 2 == 0 + if value_type is int: + return (1 + (rows + 3 * variant) % 9).astype(np.int64) + if value_type is float: + scale = 1_000.0 if variant == 0 else 2_750.0 + return (rows + 1) * scale + raise TypeError(f"No test values for {column!r} of type {value_type!r}.") + + +def with_stage_outputs( + frame: Frame, + stages: tuple[StageOutputs, ...], + *, + variant: int, + system, +) -> Frame: + """``frame`` with every column the stages write set to one value variant.""" + + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + for stage in stages: + table = tables[stage.entity] + for column in stage.columns: + table[column] = _stage_output_values(column, len(table), variant, system) + return Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + ) + + +def with_person_columns(frame: Frame, person_id: int, **values) -> Frame: + """``frame`` with person columns set for one person (zero or False elsewhere).""" + + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + person = tables["person"] + selected = person["person_id"].to_numpy() == person_id + for column, value in values.items(): + if column in person: + updated = person[column].to_numpy().copy() + else: + updated = np.zeros(len(person), dtype=type(value)) + updated[selected] = value + person[column] = updated + return Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + ) + + +def by_person_id(frame: Frame, values: np.ndarray) -> pd.Series: + """Person-aligned pass output indexed by ``person_id``.""" + + return pd.Series(values, index=frame.table("person")["person_id"].to_numpy()) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index ee84e30083..a6f4f457dc 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -99,6 +99,12 @@ target_fit_gate, target_profile_coverage_gate, ) +from microcosm.build.household_pass_reuse import ( + HouseholdPassRecord, + HouseholdPassReuse, + record_household_pass, + reuse_household_pass, +) from microcosm.build.ledger_artifact import load_ledger_consumer_artifact from microcosm.build.run_outcome import classify_failure from microcosm.build.source_runtime import SourceRuntimeConfig, run_source_stage @@ -349,10 +355,14 @@ group_to_household_positions, household_batch_plan, household_position_batches, + one_pass_garbage_collection, record_engine_branches, refuse_batch_population_aggregates, select_households_by_position, ) +from microcosm.build.us_runtime.household_pass_inputs import ( + us_household_pass_inputs, +) from microcosm.build.us_runtime.input_mass import ( us_input_mass_parity_gate, us_input_mass_totals, @@ -4680,6 +4690,7 @@ def _with_medicaid_take_up_outputs( substitutions: Sequence[dict[str, object]] = (), simulation=None, maximum_microsim_batch_size: int | None = DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE, + eligibility_recorder: Callable[[Frame, np.ndarray], None] | None = None, ) -> tuple[Frame, dict[str, object]]: """Assign Medicaid take-up (microcosm #331) and return frame + diagnostics. @@ -4688,6 +4699,8 @@ def _with_medicaid_take_up_outputs( they ride the take-up diagnostics so the gate can rot-check a backfilled substitution and the ``us_medicaid_take_up.json`` release artifact records exactly which states shipped a substituted point-in-time count. + ``eligibility_recorder``, when given, receives the frame and the + eligibility array computed on it, before the take-up assignment. """ target_table = _medicaid_source_target_table(target_specs) if target_table.empty: @@ -4701,6 +4714,8 @@ def _with_medicaid_take_up_outputs( simulation=simulation, maximum_microsim_batch_size=maximum_microsim_batch_size, ) + if eligibility_recorder is not None: + eligibility_recorder(frame, eligibility) return with_us_medicaid_take_up( frame, is_medicaid_eligible=eligibility, @@ -4711,6 +4726,150 @@ def _with_medicaid_take_up_outputs( ) +def _medicaid_claim_crossing(frame: Frame) -> str | None: + """Why ``frame``'s households are not independent for Medicaid, if they are not. + + ``is_medicaid_eligible`` reads each person's claiming tax unit through + joins over every person in the simulation. A positive + ``medicaid_claiming_tax_unit_id`` that does not resolve within the + person's own household links two households, so neither can reuse a + value computed without the other. + """ + + try: + assert_medicaid_claiming_tax_units_local(frame, work="Medicaid eligibility") + except ValueError: + return ( + "a positive medicaid_claiming_tax_unit_id does not resolve within " + "the person's own household" + ) + return None + + +def _household_pass_record( + frame: Frame, + values: np.ndarray, + *, + variable: str, + reuse_refused: str | None = None, +) -> HouseholdPassRecord: + """Keep one pre-calibration pass of ``variable`` for reuse after calibration. + + The record holds the values, the person IDs and a digest of each + household's rows over every column the installed policyengine-us can + read for ``variable`` (``us_household_pass_inputs``: its static + dependency graph plus the reads that graph does not follow); it holds no + frame. + """ + + from policyengine_us.system import system + + inputs = us_household_pass_inputs( + variable, + metadata_index=_formula_owned_gate_adapter(), + system=system, + ) + return record_household_pass(frame, values, inputs, reuse_refused=reuse_refused) + + +def _reuse_household_pass( + record: HouseholdPassRecord, + frame: Frame, + *, + recompute: Callable[[Frame], np.ndarray], + maximum_microsim_batch_size: int | None, + description: str, + telemetry: _BuildProgress | None = None, + telemetry_stage: str = "take_up_final_diagnostics", + reuse_refused: str | None = None, +) -> HouseholdPassReuse: + """The pass's values on ``frame``, running policyengine-us only where needed. + + Households whose digest matches the record take their recorded values. + ``recompute`` runs the pass on the others, together with one batch of + unchanged households spread over the frame as a check, in selections of + one batch at most; if that check disagrees with the record, ``recompute`` + runs on the whole frame (see + :func:`microcosm.build.household_pass_reuse.reuse_household_pass`). The + passes inside share one full garbage collection, as a full pass has. + With ``telemetry``, ``telemetry_stage`` is reported running before the + reuse and again with the counts after it; the counts are also printed. + No release file records them. ``reuse_refused`` (a reason) runs the whole + frame, as does a record made with one. Without a positive batch size the + reruns take one selection, as the unbatched pass does. + """ + + def report(message: str, **details: object) -> None: + if telemetry is None: + return + # Reporting only: a telemetry failure must not stop the build here + # or mask an earlier failure (microcosm#547). + try: + telemetry.stage(telemetry_stage, message=message, **details) + except Exception as error: + print( + f"WARNING: the {description} reuse report did not reach " + f"telemetry: {error}", + flush=True, + ) + + batched = ( + maximum_microsim_batch_size is not None and maximum_microsim_batch_size > 0 + ) + checked_households = ( + maximum_microsim_batch_size if batched else DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE + ) + batch_households = maximum_microsim_batch_size if batched else frame.n("household") + report( + f"Reusing pre-calibration {description} for households whose inputs " + "are unchanged." + ) + with one_pass_garbage_collection(): + reuse = reuse_household_pass( + record, + frame, + recompute=recompute, + checked_household_count=checked_households, + batch_household_count=batch_households, + reuse_refused=reuse_refused, + ) + total = reuse.reused_households + reuse.recomputed_households + if reuse.reuse_refused is not None: + message = ( + f"{description} recomputed for all {total:,} households without " + f"reuse: {reuse.reuse_refused}." + ) + elif reuse.check_failed: + message = ( + f"WARNING: {description} recomputed for all {total:,} households. " + f"On {reuse.checked_households:,} households whose inputs did not " + "change, policyengine-us gave at least one person a value that " + "differs from the pre-calibration pass, so the input list misses " + f"something the engine reads ({record.inputs.description})." + ) + else: + message = ( + f"Reused pre-calibration {description} for " + f"{reuse.reused_households:,} of {total:,} households; ran " + f"policyengine-us on {reuse.recomputed_households:,} households " + f"whose inputs changed and on {reuse.checked_households:,} " + "unchanged households as a check." + ) + print(message, flush=True) + report( + message, + household_pass_reuse={ + "variable": record.inputs.variable, + "reused_households": reuse.reused_households, + "recomputed_households": reuse.recomputed_households, + "checked_households": reuse.checked_households, + "check_failed": reuse.check_failed, + "reuse_refused": reuse.reuse_refused, + }, + ) + return reuse + + def _medicaid_diagnostics_for_existing_output( frame: Frame, target_specs: tuple, @@ -4718,18 +4877,30 @@ def _medicaid_diagnostics_for_existing_output( seed: int, substitutions: Sequence[dict[str, object]] = (), maximum_microsim_batch_size: int | None = DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE, + eligibility: np.ndarray | None = None, ) -> dict[str, object]: - """Diagnose persisted Medicaid flags on actual release weights.""" + """Diagnose persisted Medicaid flags on actual release weights. + + ``eligibility`` is the person-aligned ``is_medicaid_eligible`` of + ``frame`` when the caller already has it (the post-calibration reuse of + the first pass); otherwise this runs the pass. + """ target_table = _medicaid_source_target_table(target_specs) if target_table.empty: raise RuntimeError( "Final Medicaid take-up diagnostics require CMS state targets." ) - eligibility = _medicaid_person_eligibility( - frame, - maximum_microsim_batch_size=maximum_microsim_batch_size, - ) + if eligibility is None: + eligibility = _medicaid_person_eligibility( + frame, + maximum_microsim_batch_size=maximum_microsim_batch_size, + ) + elif np.shape(eligibility) != (frame.n("person"),): + raise ValueError( + "Final Medicaid eligibility must hold one value per export person: " + f"{frame.n('person')} people, shape {np.shape(eligibility)}." + ) assigned = us_medicaid_source_person_table( frame, is_medicaid_eligible=eligibility, @@ -17619,6 +17790,14 @@ def _main(argv: Sequence[str] | None = None) -> int | None: base_frame, maximum_microsim_batch_size=args.maximum_microsim_batch_size, ) + # The post-calibration measurement reuses these values for every + # household whose December SSI inputs are unchanged on the export frame. + # A dry run stops before calibration and needs no record. + ssi_pass_record = ( + _household_pass_record(base_frame, ssi_uncapped_amount, variable="uncapped_ssi") + if dry_run is None + else None + ) base_frame, ssi_take_up_stage_diagnostics = with_us_ssi_take_up( base_frame, uncapped_ssi=ssi_uncapped_amount, @@ -17931,13 +18110,32 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "state enrollment snapshots." ), ) + # As for SSI, the post-calibration Medicaid diagnostics reuse this pass for + # households whose eligibility inputs are unchanged on the export frame. + medicaid_pass_records: list[HouseholdPassRecord] = [] base_frame, medicaid_take_up_diagnostics = _with_medicaid_take_up_outputs( base_frame, target_specs, seed=args.seed, substitutions=medicaid_enrollment_substitutions, maximum_microsim_batch_size=args.maximum_microsim_batch_size, + eligibility_recorder=( + None + if dry_run is not None + else lambda frame, eligibility, records=medicaid_pass_records: ( + records.append( + _household_pass_record( + frame, + eligibility, + variable="is_medicaid_eligible", + reuse_refused=_medicaid_claim_crossing(frame), + ) + ) + ) + ), ) + medicaid_pass_record = medicaid_pass_records[0] if medicaid_pass_records else None + del medicaid_pass_records medicaid_take_up_gate = shadow_gate( "us_national_medicaid_take_up", lambda: us_medicaid_take_up_gate(medicaid_take_up_diagnostics), @@ -18700,10 +18898,21 @@ def _main(argv: Sequence[str] | None = None) -> int | None: weights="calibrated_household_weights", ) compilation = dict(compilation) - final_uncapped_ssi = _ssi_person_uncapped_amount( + final_uncapped_ssi = _reuse_household_pass( + ssi_pass_record, export_frame, + # A rerun of only some households holds part of the population, so + # the population-aggregate refusal is on whatever its batch count. + recompute=lambda frame: _ssi_person_uncapped_amount( + frame, + maximum_microsim_batch_size=args.maximum_microsim_batch_size, + refuse_population_aggregates=None if frame is export_frame else True, + ), maximum_microsim_batch_size=args.maximum_microsim_batch_size, - ) + description="December SSI candidate amounts", + telemetry=telemetry, + ).values + del ssi_pass_record ssi_take_up_diagnostics = dict( us_ssi_take_up_diagnostics( export_frame, @@ -18786,17 +18995,38 @@ def _main(argv: Sequence[str] | None = None) -> int | None: _final_medicaid_diagnostics_or_quarantine( ssi_law_degraded=ssi_law_degraded, degraded=bool(early_terminal_gate_failures), - evaluate=lambda: dict( + evaluate=lambda record=medicaid_pass_record: dict( _medicaid_diagnostics_for_existing_output( export_frame, target_specs, seed=args.seed, substitutions=medicaid_enrollment_substitutions, maximum_microsim_batch_size=args.maximum_microsim_batch_size, + eligibility=_reuse_household_pass( + record, + export_frame, + recompute=lambda frame: _medicaid_person_eligibility( + frame, + maximum_microsim_batch_size=( + args.maximum_microsim_batch_size + ), + refuse_population_aggregates=( + None if frame is export_frame else True + ), + ), + maximum_microsim_batch_size=args.maximum_microsim_batch_size, + description="Medicaid eligibility", + telemetry=telemetry, + # A failed SSI delivery check closes the running + # stage; the Medicaid measurement opens its own. + telemetry_stage="medicaid_final_diagnostics", + reuse_refused=_medicaid_claim_crossing(export_frame), + ).values, ) ), ) ) + del medicaid_pass_record early_terminal_gate_failures.extend(medicaid_guard_failures) # Signal gates re-check the exported support: sparse selection can drop # rows, and a column nonconstant on the candidate base can flatten on the