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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/update-policyengine-6.20.5.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Updated policyengine.py from 6.20.4 to 6.20.5 in the simulation runtime. 6.20.5 lists every column it stores from a US dataset in the simulation's `input_variables`. policyengine-us's `marginal_tax_rate` recalculates each household's net income in copies of the simulation that keep only those inputs, so until now the copies lost each household's age, location, Social Security and other dataset inputs, and US cliff gaps and cliff shares counted the income they lost as cliffs: a retiree in Wake County, North Carolina, with $15,000 of earnings and $24,000 of Social Security in 2026 got a cliff gap of $22,644.95 instead of $0. US labor-supply and capital-gains responses, whose measurements use the same kind of copies, may change too. Results already stored for 6.20.4 are not recalculated. API v2's new reports, re-runs and household calculations run on the version this deployment makes the v2 default, but need API v1's catalog for that version, which API v1 publishes when it deploys 6.20.5: until then API v2 refuses them with `unknown_catalog_version`. API v1 sends its own .py version with each request, so its reports move to 6.20.5 when API v1 raises its own pin.
4 changes: 2 additions & 2 deletions projects/policyengine-simulation-executor/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ dependencies = [
"policyengine-stage12-persistence",
# PolicyEngine.py's models extra is the only selector for core, country
# models, and the SPM calculator. Do not duplicate those versions here.
"policyengine[models]==6.20.4",
"policyengine[models]==6.20.5",
"tables>=3.10.2",
# 1.6.4 is the first release whose containers reload Secret values when
# they restore from a memory snapshot. Every app deployed or run from this
Expand Down Expand Up @@ -58,7 +58,7 @@ packages = ["src/policyengine_simulation_executor"]
# certified datasets and writes their receipt.
[dependency-groups]
modal-simulation-image = [
"policyengine[models]==6.20.4",
"policyengine[models]==6.20.5",
"fastapi>=0.115.0",
"tables>=3.10.2",
"policyengine-observability[fastapi,google,otlp-grpc]>=3.0.7,<4",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
"""A cliff calculation keeps every dataset input in its extra-earnings copies.

API v2's cliff gap and cliff share come from Stage 12's cliff calculation:
``resolve_cliff_output_plan`` plans the cliff columns, the worker builds .py's
``Simulation(dataset=…)``, ``apply_output_plan`` adds the columns, and
``cliff_totals_from_frames`` sums the rows. ``cliff_gap`` reads policyengine-us's
``marginal_tax_rate``, which recalculates each household's net income in a copy
of the simulation that keeps only the values listed in the simulation's
``input_variables``. From 6.0.0 to 6.20.4, .py stored a US dataset's columns
after constructing the country simulation, so that list named none of them:
the copies lost age, location, Social Security and every other dataset input,
and the income they lost was reported as cliff gaps.

These tests run one household through the service's cliff calculation and
expect the cliff gap and share that policyengine-us calculates for the same
household and policy given as a situation, whose inputs it lists at
construction. Each household lives in Wake County, North Carolina, in 2026.
A retiree under current law covers a run with no policy. A parent of two, whom
policyengine-us places on a cliff, runs under a raised Child Tax Credit: .py
then builds a reform simulation and a baseline simulation beside it from the
dataset, and every compared value comes from the reform simulation, whose tax
unit's Child Tax Credit is compared too, to show the policy took effect. On
.py 6.20.4 (policyengine-us 2.2.2) the retiree gets a gap of $22,644.95
instead of $0, and the parent $6,824.68 instead of $460.95.

The worker calls ``ensure()``, which adds loading and saving stored outputs
around the same ``run()``; these tests call ``run()``, so nothing is read from
or written to disk.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, NamedTuple

import pandas as pd
import pytest
from microdf import MicroDataFrame
from policyengine.core import Simulation
from policyengine.tax_benefit_models.us import PolicyEngineUSDataset, USYearData
from policyengine_core.reforms import Reform
from policyengine_simulation_contract.stage12_execution import SimulationRole
from policyengine_simulation_executor.request_policy import normalise_policy
from policyengine_simulation_executor.simulation_runtime import _country_module
from policyengine_simulation_executor.stage12_runtime.cliff_results import (
CliffTotals,
cliff_totals_from_frames,
)
from policyengine_simulation_executor.stage12_runtime.output_planning import (
apply_output_plan,
resolve_cliff_output_plan,
validate_output_frames,
)
from policyengine_us import Simulation as PolicyEngineUSSimulation
from stage12_runtime_support import simulation_execution_input

if TYPE_CHECKING:
from policyengine_simulation_contract.stage12_execution import Stage12OutputPlan

YEAR = 2026
NORTH_CAROLINA_STATE_FIPS = 37
WAKE_COUNTY_FIPS = "37183"
GROUP_ENTITIES = ("tax_unit", "spm_unit", "family")


class OneHousehold(NamedTuple):
"""One household in Wake County, North Carolina, and the policy it runs under.

``policy`` is a request's policy, as API v2 sends it (None for current
law). ``on_a_cliff`` says policyengine-us gives the household a cliff gap,
so the case checks a nonzero gap.
"""

people: tuple[dict[str, float], ...]
policy: dict[str, dict[str, float]] | None
on_a_cliff: bool


RETIREE_WITH_SOCIAL_SECURITY = OneHousehold(
people=(
{
"age": 67,
"employment_income": 15_000.0,
"social_security_retirement": 24_000.0,
},
),
policy=None,
on_a_cliff=False,
)
PARENT_OF_TWO_ON_A_CLIFF_UNDER_A_REFORM = OneHousehold(
people=(
{"age": 30, "employment_income": 50_000.0},
{"age": 3},
{"age": 6},
),
policy={
"gov.irs.credits.ctc.amount.base[0].amount": {"2026-01-01.2100-12-31": 3_000}
},
on_a_cliff=True,
)


class HouseholdResults(NamedTuple):
"""A household's cliff totals, and its tax unit's Child Tax Credit."""

cliffs: CliffTotals
child_tax_credit: float


@pytest.fixture(scope="module")
def cliff_output_plan() -> Stage12OutputPlan:
"""Return the columns a US cliff calculation stores, as the worker plans them."""
return resolve_cliff_output_plan(
simulation_execution_input(SimulationRole.BASELINE)
)


@pytest.mark.parametrize(
"household",
[
pytest.param(RETIREE_WITH_SOCIAL_SECURITY, id="retiree-with-social-security"),
pytest.param(
PARENT_OF_TWO_ON_A_CLIFF_UNDER_A_REFORM,
id="parent-of-two-on-a-cliff-under-a-reform",
),
],
)
def test_a_cliff_calculation_gives_policyengine_us_cliffs_for_a_dataset_household(
household: OneHousehold, cliff_output_plan: Stage12OutputPlan
) -> None:
calculated = _stage12_results(household, cliff_output_plan)

expected = _policyengine_us_results(household)
if household.on_a_cliff:
assert expected.cliffs.cliff_gap > 0, (
"policyengine-us no longer places this household on a cliff; "
"choose one it does, so the case still checks a nonzero gap"
)
assert calculated.child_tax_credit == pytest.approx(
expected.child_tax_credit, abs=0.01
)
assert calculated.cliffs.cliff_gap == pytest.approx(
expected.cliffs.cliff_gap, abs=0.01
)
assert calculated.cliffs.cliff_share == pytest.approx(expected.cliffs.cliff_share)


def _stage12_results(
household: OneHousehold, output_plan: Stage12OutputPlan
) -> HouseholdResults:
"""Calculate the household's cliffs as a Stage 12 cliff worker does."""
simulation = Simulation(
dataset=_one_household_dataset(household),
tax_benefit_model_version=_country_module("us").model,
policy=normalise_policy(household.policy),
)
apply_output_plan(simulation, output_plan)
simulation.run()
entity_data = simulation.output_dataset.data.entity_data
frames = {entity: pd.DataFrame(frame) for entity, frame in entity_data.items()}
validate_output_frames(frames, output_plan)
return HouseholdResults(
cliffs=cliff_totals_from_frames(frames, output_plan),
child_tax_credit=float(frames["tax_unit"]["ctc"].sum()),
)


def _policyengine_us_results(household: OneHousehold) -> HouseholdResults:
"""Calculate the household's cliffs in policyengine-us, from a situation."""
names = [f"person_{index}" for index in range(len(household.people))]
reform = (
None
if household.policy is None
else Reform.from_dict(household.policy, country_id="us")
)
simulation = PolicyEngineUSSimulation(
reform=reform,
situation={
"people": {
name: {variable: {YEAR: value} for variable, value in inputs.items()}
for name, inputs in zip(names, household.people, strict=True)
},
**{
f"{entity}s": {entity: {"members": names}}
for entity in ("tax_unit", "spm_unit")
},
"families": {"family": {"members": names}},
"marital_units": {
f"marital_unit_{index}": {"members": [name]}
for index, name in enumerate(names)
},
"households": {
"household": {
"members": names,
"state_fips": {YEAR: NORTH_CAROLINA_STATE_FIPS},
"county_fips": {YEAR: WAKE_COUNTY_FIPS},
}
},
},
)
adults = float(simulation.calculate("is_adult", YEAR).sum())
return HouseholdResults(
cliffs=CliffTotals(
cliff_gap=float(simulation.calculate("cliff_gap", YEAR).sum()),
cliff_share=float(simulation.calculate("is_on_cliff", YEAR).sum()) / adults,
),
child_tax_credit=float(simulation.calculate("ctc", YEAR).sum()),
)


def _one_household_dataset(household: OneHousehold) -> PolicyEngineUSDataset:
"""Return the household as a .py US dataset: one tax unit, SPM unit and family.

Each person is their own marital unit, and every weight is 1.
"""
person_count = len(household.people)
person_ids = list(range(1, person_count + 1))
input_names = sorted({name for inputs in household.people for name in inputs})
person = pd.DataFrame(
{
"person_id": person_ids,
"person_household_id": [1] * person_count,
**{f"person_{entity}_id": [1] * person_count for entity in GROUP_ENTITIES},
"person_marital_unit_id": person_ids,
"person_weight": [1.0] * person_count,
**{
name: [inputs.get(name, 0.0) for inputs in household.people]
for name in input_names
},
}
)
groups = {
entity: _weighted(pd.DataFrame({f"{entity}_id": [1]}), entity)
for entity in GROUP_ENTITIES
}
marital_units = pd.DataFrame({"marital_unit_id": person_ids})
households = pd.DataFrame(
{
"household_id": [1],
"state_fips": [NORTH_CAROLINA_STATE_FIPS],
"county_fips": [WAKE_COUNTY_FIPS],
}
)
return PolicyEngineUSDataset(
id="stage12-cliff-one-household",
name="stage12-cliff-one-household",
description="One household in Wake County, North Carolina",
filepath=None,
year=YEAR,
data=USYearData(
person=MicroDataFrame(person, weights="person_weight"),
marital_unit=_weighted(marital_units, "marital_unit"),
household=_weighted(households, "household"),
**groups,
),
)


def _weighted(frame: pd.DataFrame, entity: str) -> MicroDataFrame:
"""Return ``frame`` with a weight of 1 for each row, as ``<entity>_weight``."""
weight = f"{entity}_weight"
return MicroDataFrame(frame.assign(**{weight: 1.0}), weights=weight)
10 changes: 5 additions & 5 deletions projects/policyengine-simulation-executor/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading