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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/us-jct-reform-system-only.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Target compilation's JCT tax-expenditure reform batches now give each batch engine the reform's tax-benefit system alone, without `reform=` as well, as post-export scoring does. Given both, policyengine-us 2.2.1 cloned the reform's system for every batch engine and gave each a `baseline` branch: 11 reforms × 177 batches = 1,947 clones in a release build. Without a `baseline` branch, each reform is refused before its first batch engine if its system moves a labor-supply or capital-gains response parameter off baseline, and a batch engine is refused if it computed a formula that reads the `baseline` branch (`POST_EXPORT_BASELINE_BRANCH_READERS`), at every batch count. On a five-household policyengine-us fixture in two batches, all 11 reforms give byte-identical household income tax to the previous construction. The reform income-tax cache identity is unchanged.
7 changes: 7 additions & 0 deletions docs/us-release-build-rule.md
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,13 @@ known violations at run time:
those responses score 0. A whole-file engine also scores 0 at the engine's
zero default elasticities.

Target compilation's JCT tax-expenditure reform batches
(`_reform_household_income_tax`) also give each batch engine the reform's
system alone, built once per reform; unlike the scorer's, they pass no `spm=`
selection. They refuse the same two things: a reform system that moves the
behavioral-response parameters, before its first batch engine, and a batch
engine that computed a baseline-branch reader, at every batch count.

Tests pin the watched lists against the installed engine's formula sources,
exercise each guard on a real engine, and compare the shipped baseline plans
(20 smoke keys, 75 validation keys and 1 demographics key), served from the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -386,23 +386,29 @@ def test_batched_base_simulation_refuses_a_stored_aggregate_input(
assert all(simulation.dataset is None for simulation in ledger.simulations)


@pytest.mark.parametrize("aggregate_in_baseline", [False, True])
def test_batched_reform_simulation_refuses_population_aggregates(
monkeypatch, aggregate_in_baseline
monkeypatch,
) -> None:
builder = _load_builder_module()
ledger = _install_fake_engine(
builder,
monkeypatch,
reform_specs=_REFORMS,
aggregate_reads={"income_tax": ("medicaid_slcsp_state_denominator",)},
aggregate_branch="baseline/temporary",
aggregate_branch="temporary_parent/temporary_child",
aggregate_delete_branch=True,
aggregate_reform_only=True,
aggregate_in_baseline=aggregate_in_baseline,
clone_branches=True,
)
with pytest.raises(ValueError, match=r"computed medicaid_slcsp_state_denominator@"):
# The Medicaid denominator is also a baseline-branch reader; this matches
# the population-aggregate refusal's own message, which comes first.
with pytest.raises(
ValueError,
match=(
r"is not batch-invariant: the engine for household batch \d+/\d+ "
r"computed medicaid_slcsp_state_denominator@"
),
):
builder._materialize_target_frame(
_nested_frame(), _TARGETS, maximum_microsim_batch_size=2
)
Expand All @@ -411,6 +417,116 @@ def test_batched_reform_simulation_refuses_population_aggregates(
assert all(simulation.dataset is None for simulation in ledger.simulations)


@pytest.mark.parametrize("batch_size", [None, 2])
def test_jct_reform_engines_get_the_family_system_alone(
monkeypatch, batch_size
) -> None:
"""Each JCT batch engine gets the family's reform system and no ``reform=``.

Given both, policyengine-us 2.2.1 clones the supplied system for every
batch and adds a ``baseline`` branch. The family system's
behavioral-response parameters are compared once, before its first
engine, with the engine's shared baseline system."""

builder = _load_builder_module()
_, _, _, ledger = _materialize(builder, monkeypatch, _nested_frame(), batch_size)

family_system = ledger.reform_systems[1]
assert family_system.reform == "mock_credit"
reform_constructions = [
entry for entry in ledger.constructions if entry["reform"] is not None
]
assert len(reform_constructions) == (1 if batch_size is None else 3)
for entry in reform_constructions:
assert entry["reform_argument"] is None
assert entry["tax_benefit_system"] is family_system
assert not any(entry["baseline_branch"] for entry in ledger.constructions)
assert ledger.behavioral_response_checks == [
(family_system, ledger.shared_baseline_system, builder.PERIOD)
]


@pytest.mark.parametrize("batch_size", [None, 2])
@pytest.mark.parametrize(
("branch", "delete_branch"),
[
pytest.param(None, False, id="root-engine"),
pytest.param("temporary_parent/temporary_child", True, id="deleted-branch"),
],
)
def test_jct_reform_batches_refuse_baseline_branch_readers(
monkeypatch, batch_size, branch, delete_branch
) -> None:
"""A JCT batch engine refuses a formula that reads the ``baseline`` branch.

It carries none, at every batch count, so the refusal does not depend on
the population-aggregate refusal being on, and it reads branches a formula
created and deleted again. The first reform engine refuses, and every
engine is released."""

builder = _load_builder_module()
for reader in builder.POST_EXPORT_BASELINE_BRANCH_READERS:
ledger = _install_fake_engine(
builder,
monkeypatch,
reform_specs=_REFORMS,
aggregate_reads={"income_tax": (reader,)},
aggregate_branch=branch,
aggregate_delete_branch=delete_branch,
aggregate_reform_only=True,
)
with pytest.raises(
ValueError, match=rf"computed {reader}@{builder.PERIOD}"
) as raised:
builder._materialize_target_frame(
_nested_frame(), _TARGETS, maximum_microsim_batch_size=batch_size
)
if (
batch_size is None
or reader not in builder.US_POPULATION_AGGREGATE_VARIABLES
):
# Otherwise the population-aggregate refusal names it first.
assert "jct_mock_credit" in str(raised.value), reader
assert "baseline branch" in str(raised.value), reader
reform_engines = [
simulation for simulation in ledger.simulations if simulation.reform
]
assert len(reform_engines) == 1, reader
assert all(simulation.dataset is None for simulation in ledger.simulations), (
reader
)


def test_jct_reform_refuses_moved_behavioral_responses_before_its_engines(
monkeypatch,
) -> None:
"""A JCT reform system that sets a behavioral-response parameter off
baseline is refused before any of its batch engines is built: those
engines carry no ``baseline`` branch, so policyengine-us would score the
response as zero."""

builder = _load_builder_module()
moved = "gov.simulation.labor_supply_responses.elasticities.income"
ledger = _install_fake_engine(
builder,
monkeypatch,
reform_specs=_REFORMS,
moved_behavioral_response_parameters=(moved,),
)
with pytest.raises(
ValueError,
match=rf"jct_mock_credit.* off baseline at {builder.PERIOD}: {re.escape(moved)}\.",
):
builder._materialize_target_frame(
_nested_frame(), _TARGETS, maximum_microsim_batch_size=2
)
assert [entry for entry in ledger.constructions if entry["reform"]] == []
assert ledger.behavioral_response_checks == [
(ledger.reform_systems[1], ledger.shared_baseline_system, builder.PERIOD)
]
assert all(simulation.dataset is None for simulation in ledger.simulations)


@pytest.mark.parametrize(
("target", "wrap", "message"),
[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11815,6 +11815,8 @@ def test_jct_materialization_collapses_reform_tax_units_and_clears_caches(
simulations = []
reform_systems = []
formula_owned_assertions: list[int] = []
behavioral_response_checks: list[tuple[object, object, int]] = []
shared_baseline_system = SimpleNamespace(name="shared baseline system")

class FakeVariable:
entity = SimpleNamespace(key="tax_unit")
Expand All @@ -11831,6 +11833,7 @@ def __init__(self, reform=None):

class FakeMicrosimulation:
default_tax_benefit_system = FakeSystem
default_tax_benefit_system_instance = shared_baseline_system

def __init__(self, *, dataset, reform=None, tax_benefit_system=None):
self.dataset = dataset
Expand All @@ -11844,7 +11847,9 @@ def calculate(self, variable, *, period, **kwargs):
tax_unit_ids = (
self.dataset["frame"].table("tax_unit")["tax_unit_id"].to_numpy()
)
if self.reform is not None:
# A reform engine computes under the reform its system was built
# with, as policyengine-us does when given that system alone.
if getattr(self.tax_benefit_system, "reform", None) is not None:
assert variable == "income_tax"
assert kwargs == {}
reform_income_tax_by_id = {10: 90.0, 20: 25.0, 30: 40.0}
Expand Down Expand Up @@ -11897,6 +11902,12 @@ def fake_make_zero_variable_reform(system, variable_name):
def fake_assert_no_formula_owned_columns(frame_arg):
formula_owned_assertions.append(frame_arg.n("household"))

def fake_moved_behavioral_response_parameters(
reform_system, baseline_system, period
):
behavioral_response_checks.append((reform_system, baseline_system, period))
return []

monkeypatch.setitem(
sys.modules,
"policyengine_us",
Expand All @@ -11914,6 +11925,11 @@ def fake_assert_no_formula_owned_columns(frame_arg):
monkeypatch.setattr(
builder, "_make_zero_variable_reform", fake_make_zero_variable_reform
)
monkeypatch.setattr(
builder,
"_moved_behavioral_response_parameters",
fake_moved_behavioral_response_parameters,
)
monkeypatch.setattr(builder, "US_JCT_TAX_EXPENDITURE_REFORMS", (reform_spec,))
monkeypatch.setattr(builder, "SOI_VARIABLE_MAP", {})

Expand Down Expand Up @@ -11979,6 +11995,12 @@ def fake_assert_no_formula_owned_columns(frame_arg):
reform_systems[1],
reform_systems[1],
]
# Each reform batch engine gets the family system alone, not ``reform=``
# as well, which would make policyengine-us clone that system per batch.
assert [simulation.reform for simulation in simulations] == [None] * 4
assert behavioral_response_checks == [
(reform_systems[1], shared_baseline_system, builder.PERIOD)
]
# Each simulation was released (dataset reference severed), not merely
# cache-invalidated.
assert [simulation.dataset for simulation in simulations] == [None] * 4
Expand Down Expand Up @@ -12027,6 +12049,7 @@ def fake_assert_no_formula_owned_columns(frame_arg):
True,
False,
]
assert len(behavioral_response_checks) == 1
assert [simulation.dataset for simulation in simulations] == [None] * 6
assert [simulation.cache_invalidations for simulation in simulations] == [0] * 6
assert (
Expand Down Expand Up @@ -16496,6 +16519,9 @@ def __init__(self, reform=None):

class FakeMicrosimulation:
default_tax_benefit_system = FakeSystem
default_tax_benefit_system_instance = SimpleNamespace(
name="shared baseline system"
)

def __init__(self, *, dataset, reform=None, tax_benefit_system=None):
self.dataset = dataset
Expand All @@ -16508,9 +16534,12 @@ def calculate(self, variable, *, period, **kwargs):
tax_unit_ids = (
self.dataset["frame"].table("tax_unit")["tax_unit_id"].to_numpy()
)
if self.reform is not None:
# A reform engine computes under the reform its system was built
# with, as policyengine-us does when given that system alone.
policy_reform = getattr(self.tax_benefit_system, "reform", None)
if policy_reform is not None:
assert variable == "income_tax"
lookup = reform_income_tax_by_id[self.reform]
lookup = reform_income_tax_by_id[policy_reform]
return np.asarray([lookup[id_] for id_ in tax_unit_ids])
arrays_by_id = {
"income_tax": base_income_tax_by_id,
Expand Down Expand Up @@ -16561,6 +16590,12 @@ def fake_make_zero_variable_reform(system, variable_name):
monkeypatch.setattr(
builder, "_make_zero_variable_reform", fake_make_zero_variable_reform
)
# No fake reform moves a behavioral-response parameter.
monkeypatch.setattr(
builder,
"_moved_behavioral_response_parameters",
lambda reform_system, baseline_system, period: [],
)
monkeypatch.setattr(builder, "US_JCT_TAX_EXPENDITURE_REFORMS", reform_specs)
monkeypatch.setattr(builder, "SOI_VARIABLE_MAP", {})

Expand Down
Loading
Loading