diff --git a/changelog.d/mapped-threshold-and-nested-nan-guards.fixed.md b/changelog.d/mapped-threshold-and-nested-nan-guards.fixed.md new file mode 100644 index 00000000000..579be1a0641 --- /dev/null +++ b/changelog.d/mapped-threshold-and-nested-nan-guards.fixed.md @@ -0,0 +1 @@ +The additional tax bracket contrib reform now applies half the joint 33% threshold to separate filers from 2026 and a $539,900 single-filer 35% threshold for 2022. Tests reject repeated or inverted mapped thresholds and NaN parameter values, including values inside lists, dictionaries and sets. diff --git a/policyengine_us/parameters/gov/contrib/additional_tax_bracket/bracket.yaml b/policyengine_us/parameters/gov/contrib/additional_tax_bracket/bracket.yaml index d3ad5c54d8a..fcd2a351fd1 100644 --- a/policyengine_us/parameters/gov/contrib/additional_tax_bracket/bracket.yaml +++ b/policyengine_us/parameters/gov/contrib/additional_tax_bracket/bracket.yaml @@ -680,16 +680,16 @@ thresholds: 2024-01-01: 243_725 2025-01-01: 250_525 # CBO forecast. - 2026-01-01: 541_550 - 2027-01-01: 553_050 - 2028-01-01: 564_200 - 2029-01-01: 575_400 - 2030-01-01: 586_750 - 2031-01-01: 598_350 - 2032-01-01: 610_200 - 2033-01-01: 622_300 - 2034-01-01: 634_650 - 2035-01-01: 647_250 + 2026-01-01: 270_775 + 2027-01-01: 276_525 + 2028-01-01: 282_100 + 2029-01-01: 287_700 + 2030-01-01: 293_375 + 2031-01-01: 299_175 + 2032-01-01: 305_100 + 2033-01-01: 311_150 + 2034-01-01: 317_325 + 2035-01-01: 323_625 metadata: uprating: parameter: gov.irs.uprating @@ -757,7 +757,7 @@ thresholds: 2019-01-01: 510_300 2020-01-01: 518_400 2021-01-01: 523_600 - 2022-01-01: 539_000 + 2022-01-01: 539_900 2023-01-01: 578_125 2024-01-01: 609_350 2025-01-01: 626_350 diff --git a/policyengine_us/tests/policy/contrib/additional_tax_bracket/additional_tax_bracket_reform.yaml b/policyengine_us/tests/policy/contrib/additional_tax_bracket/additional_tax_bracket_reform.yaml index a24a2270924..b2429577498 100644 --- a/policyengine_us/tests/policy/contrib/additional_tax_bracket/additional_tax_bracket_reform.yaml +++ b/policyengine_us/tests/policy/contrib/additional_tax_bracket/additional_tax_bracket_reform.yaml @@ -197,3 +197,67 @@ income_tax_main_rates: 6_962.50 tax_on_taxable_income_at_main_rates: 19_462.50 capital_gains_tax: 12_500 + +- name: A separate filer's 33% bracket ends at half the joint threshold under the reform. + period: 2026 + absolute_error_margin: 0.01 + reforms: policyengine_us.reforms.additional_tax_bracket.additional_tax_bracket_reform.additional_tax_bracket + input: + gov.contrib.additional_tax_bracket.in_effect: true + taxable_income: 300_000 + filing_status: SEPARATE + output: + # 2026 separate thresholds 12,150 / 49,300 / 99,500 / 151,625 / 270,775 / + # 305,875 at 10 / 15 / 25 / 28 / 33 / 35%: + # 1,215 + 5,572.50 + 12,550 + 14,595 + 39,319.50 + 0.35 * 29,225. + income_tax_main_rates: 83_480.75 + +- name: A separate filer above the 35% bracket pays 39.6% under the reform. + period: 2026 + absolute_error_margin: 0.01 + reforms: policyengine_us.reforms.additional_tax_bracket.additional_tax_bracket_reform.additional_tax_bracket + input: + gov.contrib.additional_tax_bracket.in_effect: true + taxable_income: 400_000 + filing_status: SEPARATE + output: + # 83,480.75 on the first 300,000 (case above), plus 35% of 5,875 up to + # 305,875, plus 39.6% of the remaining 94,125. + income_tax_main_rates: 122_810.50 + +- name: A single filer stays in the 35% bracket through 539900 in 2022. + period: 2022 + absolute_error_margin: 0.01 + reforms: policyengine_us.reforms.additional_tax_bracket.additional_tax_bracket_reform.additional_tax_bracket + input: + gov.contrib.additional_tax_bracket.in_effect: true + taxable_income: 539_450 + filing_status: SINGLE + output: + # IRS Rev. Proc. 2021-45, Table 3: 49,335.50 + 35% of 323,500. + income_tax_main_rates: 162_560.50 + +- name: A single filer pays 37% above 539900 in 2022. + period: 2022 + absolute_error_margin: 0.01 + reforms: policyengine_us.reforms.additional_tax_bracket.additional_tax_bracket_reform.additional_tax_bracket + input: + gov.contrib.additional_tax_bracket.in_effect: true + taxable_income: 540_000 + filing_status: SINGLE + output: + # IRS Rev. Proc. 2021-45, Table 3: 162,718 + 37% of 100. + income_tax_main_rates: 162_755 + +- name: A separate filer pays 39.6% above the projected 2035 threshold. + period: 2035 + absolute_error_margin: 0.01 + reforms: policyengine_us.reforms.additional_tax_bracket.additional_tax_bracket_reform.additional_tax_bracket + input: + gov.contrib.additional_tax_bracket.in_effect: true + taxable_income: 400_000 + filing_status: SEPARATE + output: + # CBO January 2025: 87,547.25 through 323,625, then 35% of 41,950 + # through 365,575, plus 39.6% of the remaining 34,425. + income_tax_main_rates: 115_862.05 diff --git a/policyengine_us/tests/policy/contrib/additional_tax_bracket/test_additional_tax_bracket_unset_bracket.py b/policyengine_us/tests/policy/contrib/additional_tax_bracket/test_additional_tax_bracket_unset_bracket.py index 92e9dc540c7..2cb18e8f051 100644 --- a/policyengine_us/tests/policy/contrib/additional_tax_bracket/test_additional_tax_bracket_unset_bracket.py +++ b/policyengine_us/tests/policy/contrib/additional_tax_bracket/test_additional_tax_bracket_unset_bracket.py @@ -392,6 +392,40 @@ def test_baseline_schedule_is_unchanged_in_every_year(): assert np.array_equal(below, old_below), (status, year) +def test_shipped_separate_thresholds_equal_half_joint_thresholds(): + thresholds = baseline_system.parameters.get_child(f"{BRACKET}.thresholds") + expected_brackets = {str(i) for i in range(1, N_BRACKETS + 1)} + assert set(thresholds.children) == expected_brackets + checked = set() + + for bracket in sorted(thresholds.children, key=int): + columns = thresholds.children[bracket].children + joint, separate = columns["JOINT"], columns["SEPARATE"] + instants = sorted( + { + value_at_instant.instant_str + for leaf in (joint, separate) + for value_at_instant in leaf.values_list + } + ) + for instant_str in instants: + joint_value = joint._get_at_instant(instant_str) + separate_value = separate._get_at_instant(instant_str) + if joint_value is None and separate_value is None: + continue + assert joint_value is not None and separate_value is not None, ( + bracket, + instant_str, + ) + assert separate_value == joint_value / 2, ( + f"{BRACKET}.thresholds.{bracket}: SEPARATE {separate_value} " + f"does not equal half JOINT {joint_value} at {instant_str}" + ) + checked.add(bracket) + + assert checked == expected_brackets + + # --------------------------------------------------------------------------- # The reform in simulations # --------------------------------------------------------------------------- diff --git a/policyengine_us/tests/test_negative_main_rates_inverted_brackets.py b/policyengine_us/tests/test_negative_main_rates_inverted_brackets.py index 6af6c56020d..4c61a687038 100644 --- a/policyengine_us/tests/test_negative_main_rates_inverted_brackets.py +++ b/policyengine_us/tests/test_negative_main_rates_inverted_brackets.py @@ -29,6 +29,8 @@ the SEPARATE-specific reform under test. """ +import gc + import numpy as np import pytest @@ -194,15 +196,14 @@ def four_status_situation(): def test_shipped_additional_tax_bracket_reform_is_clamped(): - # The contrib reform replaces both bracket loops and its parameter - # tree still carries the expiration projection's inverted SEPARATE - # thresholds (bracket 5 top 541,550 above bracket 6 top 305,875), - # so it must clamp too: before the fix a zero-income 2026 MFS filer - # owed a flat −$82,486 under this shipped reform. The reform's - # user-supplied extra bracket is filled as in its own yaml tests; - # brackets 1–6 stay at the shipped (inverted) values. + # Inject a SEPARATE bracket-5 top of 541,550 above bracket 6's 305,875 + # to exercise the contrib reform's shared bracket clamp. Fill the + # user-supplied extra bracket as in the reform's YAML tests. fill_extra_bracket = Reform.from_dict( { + "gov.contrib.additional_tax_bracket.bracket.thresholds.5.SEPARATE": { + "2026-01-01.2026-12-31": 541_550 + }, "gov.contrib.additional_tax_bracket.bracket.thresholds.7.SEPARATE": { "2026-01-01.2026-12-31": 800_000 }, @@ -220,3 +221,19 @@ def test_shipped_additional_tax_bracket_reform_is_clamped(): before_credits = sim.calculate("income_tax_before_credits", 2026)[0] assert main == 0 assert before_credits == 0 + del sim + gc.collect() + + # A zero-income filer owes nothing under any non-negative loop, so also + # check a filer inside the inverted band. Clamped, bracket 6 is empty and + # 151,625-400,000 is all taxed at bracket 5's 33%: 115,896.25. Without + # the inversion the tax is 122,810.50, and an unclamped loop gives yet + # another figure. + situation = separate_filer(0) + situation["tax_units"]["tu"]["taxable_income"] = {"2026": 400_000} + sim = Simulation( + reform=(fill_extra_bracket, additional_tax_bracket), situation=situation + ) + assert sim.calculate("income_tax_main_rates", 2026)[0] == pytest.approx( + 115_896.25, abs=0.01 + ) diff --git a/policyengine_us/tests/test_parameter_scale_thresholds.py b/policyengine_us/tests/test_parameter_scale_thresholds.py index 5a4899c5de8..0fb5014a9b8 100644 --- a/policyengine_us/tests/test_parameter_scale_thresholds.py +++ b/policyengine_us/tests/test_parameter_scale_thresholds.py @@ -1,4 +1,4 @@ -"""Parameter scales must not repeat a threshold at any instant. +"""Check parameter dates, bracket thresholds and NaN values. To build a scale at an instant, policyengine-core's `ParameterScale._get_at_instant` passes brackets to `add_bracket`, which adds @@ -13,6 +13,18 @@ Duplicate `+inf` thresholds are exempt: tables whose length changes over time park unused brackets there, and no finite value reaches them. `-inf` is a reachable bottom row, so duplicates there are flagged. + +Federal-style rate schedules such as `gov.irs.income.bracket` are not scales: +their `thresholds` node maps bracket numbers 1..N to a value per filing status, +and `tax_at_main_rates` reads bracket i's threshold as its top. A repeated +threshold empties a bracket and an inverted one is clamped (#9084), so either +silently taxes a band at the wrong rate. Each filing status's thresholds must +therefore strictly increase at every instant, again exempting `+inf`. +`tax_at_main_rates` leaves income above a finite final threshold untaxed, +so the shipped ordinary income schedules must end at `+inf`. + +YAML's `.nan` loads as a float in a scalar or nested value, and every +comparison with it is false, so no parameter value may hold NaN at any depth. """ import calendar @@ -31,7 +43,12 @@ from policyengine_core.taxscales.amount_tax_scale_like import AmountTaxScaleLike from policyengine_core.taxscales.rate_tax_scale_like import RateTaxScaleLike -from policyengine_us.system import system + +@pytest.fixture(scope="module") +def system(): + from policyengine_us.system import system as us_system + + return us_system def _add_bracket_thresholds(scale, instant_str): @@ -111,7 +128,7 @@ def _scale(brackets): ) -def _all_scales(): +def _all_scales(system): return [ node for node in system.parameters.get_descendants() @@ -328,7 +345,7 @@ def test_calendar_date_guard_exempts_only_beginning_of_time(month, day): assert _non_calendar_instants(parameter) == expected -def test_parameter_instants_are_calendar_dates(): +def test_parameter_instants_are_calendar_dates(system): errors = [ f"{parameter.name}: {instant_str}" for parameter in system.parameters.get_descendants() @@ -339,7 +356,9 @@ def test_parameter_instants_are_calendar_dates(): assert not errors, "\n".join(errors) -def test_add_bracket_thresholds_match_core_for_every_scale_and_instant(monkeypatch): +def test_add_bracket_thresholds_match_core_for_every_scale_and_instant( + monkeypatch, system +): # Record every threshold core passes to add_bracket, repeats included, and # compare that multiset with the guard's; comparing the built scale's # thresholds would hide exactly the repeats the guard exists to find. @@ -354,7 +373,7 @@ def recording_add_bracket(self, threshold, value, original=original): monkeypatch.setattr(scale_class, "add_bracket", recording_add_bracket) mismatches = [] - for scale in _all_scales(): + for scale in _all_scales(system): for instant_str in _change_instants(scale): if instant_str == YEAR_ZERO_SENTINEL: # Core's public lookup cannot parse year zero. @@ -371,9 +390,249 @@ def recording_add_bracket(self, threshold, value, original=original): assert not mismatches, "\n".join(mismatches) -def test_parameter_scales_have_no_duplicate_thresholds(): - scales = _all_scales() +def test_parameter_scales_have_no_duplicate_thresholds(system): + scales = _all_scales(system) errors = [error for scale in scales for error in _duplicate_threshold_errors(scale)] assert scales assert not errors, "\n".join(errors) + + +def _mapped_threshold_tables(system): + # A rate schedule's `thresholds` node sits beside the `rates` node that + # `tax_at_main_rates` reads with it, and maps bracket numbers 1..N. + return [ + node.children["thresholds"] + for node in system.parameters.get_descendants() + if isinstance(node, ParameterNode) + and "rates" in node.children + and isinstance(node.children.get("thresholds"), ParameterNode) + and node.children["thresholds"].children + and sorted(node.children["thresholds"].children) + == sorted( + str(i) for i in range(1, len(node.children["thresholds"].children) + 1) + ) + ] + + +def _mapped_threshold_errors(node): + brackets = sorted(node.children, key=int) + columns = defaultdict(dict) + for bracket in brackets: + child = node.children[bracket] + if isinstance(child, ParameterNode): + for column, leaf in child.children.items(): + columns[column][bracket] = leaf + else: + columns[None][bracket] = child + instants_by_error = defaultdict(list) + for column, leaves in columns.items(): + instants = sorted( + { + value_at_instant.instant_str + for leaf in leaves.values() + for value_at_instant in leaf.values_list + } + ) + for instant_str in instants: + present = [ + (bracket, value) + for bracket in brackets + if bracket in leaves + and (value := leaves[bracket]._get_at_instant(instant_str)) is not None + ] + for (lower, low), (upper, high) in zip(present, present[1:]): + if not low < high and not low == high == math.inf: + instants_by_error[(column, lower, upper)].append( + (instant_str, low, high) + ) + errors = [] + for (column, lower, upper), cases in instants_by_error.items(): + instant_str, low, high = cases[0] + when = instant_str + if len(cases) > 1: + when = ( + f"{instant_str} and {len(cases) - 1} later instants to {cases[-1][0]}" + ) + name = node.name if column is None else f"{node.name}.*.{column}" + errors.append( + f"{name}: bracket {upper} threshold {high:,.15g} does not exceed " + f"bracket {lower} threshold {low:,.15g} at {when}" + ) + return errors + + +def _mapped_table(thresholds): + return ParameterNode("root", data={"thresholds": thresholds}).thresholds + + +def test_mapped_threshold_guard_flags_repeats_and_inversions(): + table = _mapped_table( + { + 1: {"SINGLE": {"2024-01-01": 100}, "JOINT": {"2024-01-01": 200}}, + 2: { + "SINGLE": {"2024-01-01": 100}, + "JOINT": {"2024-01-01": 400, "2025-01-01": 150}, + }, + 3: {"SINGLE": {"2024-01-01": 300}, "JOINT": {"2024-01-01": 600}}, + } + ) + + assert _mapped_threshold_errors(table) == [ + "root.thresholds.*.SINGLE: bracket 2 threshold 100 does not exceed " + "bracket 1 threshold 100 at 2024-01-01", + "root.thresholds.*.JOINT: bracket 2 threshold 150 does not exceed " + "bracket 1 threshold 200 at 2025-01-01", + ] + + +def test_mapped_threshold_guard_flags_negative_infinity_repeats_and_nan(): + table = _mapped_table( + { + 1: {"SINGLE": {"2024-01-01": -math.inf}, "JOINT": {"2024-01-01": 100}}, + 2: { + "SINGLE": {"2024-01-01": -math.inf}, + "JOINT": {"2024-01-01": math.nan}, + }, + 3: {"SINGLE": {"2024-01-01": 300}, "JOINT": {"2024-01-01": 600}}, + } + ) + + assert _mapped_threshold_errors(table) == [ + "root.thresholds.*.SINGLE: bracket 2 threshold -inf does not exceed " + "bracket 1 threshold -inf at 2024-01-01", + "root.thresholds.*.JOINT: bracket 2 threshold nan does not exceed " + "bracket 1 threshold 100 at 2024-01-01", + "root.thresholds.*.JOINT: bracket 3 threshold 600 does not exceed " + "bracket 2 threshold nan at 2024-01-01", + ] + + +def test_mapped_threshold_guard_ignores_only_parked_positive_infinity(): + def table_with_top(top): + return _mapped_table( + { + 1: {"SINGLE": {"2024-01-01": 100}}, + 2: {"SINGLE": {"2024-01-01": math.inf}}, + 3: {"SINGLE": {"2024-01-01": top}}, + } + ) + + assert _mapped_threshold_errors(table_with_top(math.inf)) == [] + assert _mapped_threshold_errors(table_with_top(500)) == [ + "root.thresholds.*.SINGLE: bracket 3 threshold 500 does not exceed " + "bracket 2 threshold inf at 2024-01-01" + ] + + +def test_mapped_bracket_thresholds_strictly_increase(system): + tables = _mapped_threshold_tables(system) + errors = [error for table in tables for error in _mapped_threshold_errors(table)] + + assert { + "gov.irs.income.bracket.thresholds", + "gov.irs.capital_gains.thresholds", + } <= {table.name for table in tables} + assert not errors, "\n".join(errors) + + +@pytest.mark.parametrize( + "name", + [ + "gov.irs.income.bracket", + "gov.contrib.additional_tax_bracket.bracket", + ], +) +def test_shipped_income_bracket_top_thresholds_are_infinite(name, system): + table = system.parameters.get_child(f"{name}.thresholds") + brackets = sorted(table.children, key=int) + assert brackets + statuses = { + status for bracket in brackets for status in table.children[bracket].children + } + assert statuses + + for status in sorted(statuses): + leaves = [table.children[bracket].children[status] for bracket in brackets] + instants = sorted( + { + value_at_instant.instant_str + for leaf in leaves + for value_at_instant in leaf.values_list + } + ) + checked = 0 + for instant_str in instants: + values = [leaf._get_at_instant(instant_str) for leaf in leaves] + if all(value is None for value in values): + continue + checked += 1 + assert values[-1] == math.inf, ( + f"{name}.thresholds.{brackets[-1]}.{status}: " + f"top threshold {values[-1]} at {instant_str}" + ) + assert checked, f"{name}: no active thresholds for {status}" + + +def _nan_paths(value, path=""): + if isinstance(value, float) and math.isnan(value): + yield path or "value" + elif isinstance(value, (list, tuple)): + for index, item in enumerate(value): + yield from _nan_paths(item, f"{path}[{index}]") + elif isinstance(value, dict): + for key, item in value.items(): + yield from _nan_paths(key, f"{path}.key[{key!r}]") + yield from _nan_paths(item, f"{path}[{key!r}]") + elif isinstance(value, (set, frozenset)): + for item in sorted(value, key=repr): + yield from _nan_paths(item, f"{path}{{{item!r}}}") + + +def _nan_values(parameter): + return [ + f"{value_at_instant.instant_str} {path}" + for value_at_instant in parameter.values_list + for path in _nan_paths(value_at_instant.value) + ] + + +def test_nan_guard_flags_nan_in_scalars_and_nested_containers(): + parameter = Parameter( + "test_parameter", + { + "values": { + "2023-01-01": [1.0, [2.0, 3.0], {4.0, 5.0}], + "2024-01-01": [1.0, [2.0, math.nan]], + "2025-01-01": math.nan, + "2026-01-01": [math.nan], + "2027-01-01": [{"nested": [math.nan], math.nan: 1.0}], + "2028-01-01": [{math.nan}], + } + }, + ) + + assert sorted(_nan_values(parameter)) == [ + "2024-01-01 [1][1]", + "2025-01-01 value", + "2026-01-01 [0]", + "2027-01-01 [0].key[nan]", + "2027-01-01 [0]['nested'][0]", + "2028-01-01 [0]{nan}", + ] + + +def test_parameter_values_are_not_nan(system): + parameters = [ + parameter + for parameter in system.parameters.get_descendants() + if isinstance(parameter, Parameter) + ] + errors = [ + f"{parameter.name}: {error}" + for parameter in parameters + for error in _nan_values(parameter) + ] + + assert parameters + assert not errors, "\n".join(errors)