From 370f5ae4ba22db165877b388dd96ec4dcea8da09 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 01:53:25 -0400 Subject: [PATCH 01/16] Document supplied-record Social Security calculator interface --- .../ss-household-calculator-4a1.added.md | 1 + docs/usage/social-security-calculator.md | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 changelog.d/ss-household-calculator-4a1.added.md create mode 100644 docs/usage/social-security-calculator.md diff --git a/changelog.d/ss-household-calculator-4a1.added.md b/changelog.d/ss-household-calculator-4a1.added.md new file mode 100644 index 00000000000..a27f457f59b --- /dev/null +++ b/changelog.d/ss-household-calculator-4a1.added.md @@ -0,0 +1 @@ +Add an opt-in supplied-AIME/PIA Social Security household calculator and shared eligibility-year PIA service. diff --git a/docs/usage/social-security-calculator.md b/docs/usage/social-security-calculator.md new file mode 100644 index 00000000000..900933759e6 --- /dev/null +++ b/docs/usage/social-security-calculator.md @@ -0,0 +1,23 @@ +# Supplied-record Social Security calculator + +This opt-in route will calculate gross monthly retirement benefits from a supplied +unreformed eligibility-year AIME or PIA, and the restricted single-survivor case +from a supplied monthly benefit and composite ratio. Existing public benefit +inputs retain their current behavior. + +Implementation plan: + +1. Share one monthly PIA service across household and future history callers, + with eligibility-year bend points, explicit applicability, baseline inversion, + contributed formula paths and the S.770 section 2 preset. +2. Build an entitlement ledger with cohort claiming adjustments, statutory COLA + and payment rounding, insured-status assertions and the annual earnings test. +3. Require an identified worker record and ordinary, non-WINDEX survivor basis; + derive the death benchmark and propagate supplied-payment rounding intervals. +4. Expose separate calculated results until the benefit source-selector change + merges. Wire those results into its AIME/PIA/survivor modes in one later step. +5. Validate published SSA examples, boundary cases, property invariants and + equality of existing outputs with the calculator disabled. + +The supported computation benchmark begins in 1983. History-derived AIME, +family benefits, disability computations and minimum PIAs are separate work. From 94a1440fc200db465af9c6769697dd6fa96b9dcd Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 02:03:18 -0400 Subject: [PATCH 02/16] Add shared eligibility-year PIA service and contributed formula paths --- .../congress/s770/section_2/in_effect.yaml | 9 + ...pute_pre2026_death_before_eligibility.yaml | 9 + .../ssa/pia/bend_point_multipliers/first.yaml | 9 + .../pia/bend_point_multipliers/second.yaml | 9 + .../gov/contrib/ssa/pia/effective_year.yaml | 9 + .../gov/contrib/ssa/pia/factors/first.yaml | 9 + .../gov/contrib/ssa/pia/factors/second.yaml | 9 + .../contrib/ssa/pia/factors/start_year.yaml | 9 + .../gov/contrib/ssa/pia/factors/third.yaml | 9 + .../pia/full_price_indexing/in_effect.yaml | 9 + .../full_price_indexing/real_wage_scale.yaml | 9 + .../pia/full_price_indexing/start_year.yaml | 9 + .../gov/contrib/ssa/pia/in_effect.yaml | 9 + .../bend_point_fraction.yaml | 9 + .../progressive_price_indexing/in_effect.yaml | 9 + .../maximum_aime.yaml | 9 + .../maximum_pia_target.yaml | 9 + .../start_year.yaml | 9 + .../progressive_price_indexing/threshold.yaml | 9 + .../contrib/ssa/pia/recompute_existing.yaml | 9 + .../tests/unit/test_ss_pia_service.py | 316 +++++++++++++++++ .../tools/social_security/__init__.py | 1 + policyengine_us/tools/social_security/pia.py | 333 ++++++++++++++++++ 23 files changed, 830 insertions(+) create mode 100644 policyengine_us/parameters/gov/contrib/congress/s770/section_2/in_effect.yaml create mode 100644 policyengine_us/parameters/gov/contrib/congress/s770/section_2/recompute_pre2026_death_before_eligibility.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/bend_point_multipliers/first.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/bend_point_multipliers/second.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/effective_year.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/factors/first.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/factors/second.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/factors/start_year.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/factors/third.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/in_effect.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/real_wage_scale.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/start_year.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/in_effect.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/bend_point_fraction.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/in_effect.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/maximum_aime.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/maximum_pia_target.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/start_year.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/threshold.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/pia/recompute_existing.yaml create mode 100644 policyengine_us/tests/unit/test_ss_pia_service.py create mode 100644 policyengine_us/tools/social_security/__init__.py create mode 100644 policyengine_us/tools/social_security/pia.py diff --git a/policyengine_us/parameters/gov/contrib/congress/s770/section_2/in_effect.yaml b/policyengine_us/parameters/gov/contrib/congress/s770/section_2/in_effect.yaml new file mode 100644 index 00000000000..4bf5e07fe8e --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/congress/s770/section_2/in_effect.yaml @@ -0,0 +1,9 @@ +description: Whether the supplied-input household calculator applies introduced S.770 section 2, including the 95 percent first PIA factor and 18 percent first-bend-point increase from 2026. +values: + 1983-01-01: false +metadata: + unit: bool + label: S.770 section 2 PIA reform + reference: + - title: S.770 (119th Congress), section 2 + href: https://www.congress.gov/bill/119th-congress/senate-bill/770/text diff --git a/policyengine_us/parameters/gov/contrib/congress/s770/section_2/recompute_pre2026_death_before_eligibility.yaml b/policyengine_us/parameters/gov/contrib/congress/s770/section_2/recompute_pre2026_death_before_eligibility.yaml new file mode 100644 index 00000000000..9757a0f3e9f --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/congress/s770/section_2/recompute_pre2026_death_before_eligibility.yaml @@ -0,0 +1,9 @@ +description: Whether S.770 section 2 increases the first bend point for a pre-2026 death before age-62 eligibility; the 95 percent first factor applies either way in this modeled interpretation. +values: + 1983-01-01: false +metadata: + unit: bool + label: S.770 first-bend-point increase for earlier pre-eligibility deaths + reference: + - title: S.770 (119th Congress), section 2 + href: https://www.congress.gov/bill/119th-congress/senate-bill/770/text diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/bend_point_multipliers/first.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/bend_point_multipliers/first.yaml new file mode 100644 index 00000000000..71cd6c6ec48 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/bend_point_multipliers/first.yaml @@ -0,0 +1,9 @@ +description: The multiplier applied to the first initial-eligibility PIA bend point. +values: + 1983-01-01: 1 +metadata: + unit: /1 + label: First PIA bend-point multiplier + reference: + - title: SSA Primary Insurance Amount formula + href: https://www.ssa.gov/OACT/COLA/piaformula.html diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/bend_point_multipliers/second.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/bend_point_multipliers/second.yaml new file mode 100644 index 00000000000..6672d036758 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/bend_point_multipliers/second.yaml @@ -0,0 +1,9 @@ +description: The multiplier applied to the second initial-eligibility PIA bend point. +values: + 1983-01-01: 1 +metadata: + unit: /1 + label: Second PIA bend-point multiplier + reference: + - title: SSA Primary Insurance Amount formula + href: https://www.ssa.gov/OACT/COLA/piaformula.html diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/effective_year.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/effective_year.yaml new file mode 100644 index 00000000000..1d17d31377c --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/effective_year.yaml @@ -0,0 +1,9 @@ +description: The first eligibility cohort reached by custom PIA bend-point multipliers. +values: + 1983-01-01: 1983 +metadata: + unit: year + label: PIA bend-point change start cohort + reference: + - title: SSA Primary Insurance Amount formula + href: https://www.ssa.gov/OACT/COLA/piaformula.html diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/factors/first.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/factors/first.yaml new file mode 100644 index 00000000000..8c5c9cbcb68 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/factors/first.yaml @@ -0,0 +1,9 @@ +description: The contributed first PIA marginal factor, with an unchanged current-law default. +values: + 1983-01-01: 0.9 +metadata: + unit: /1 + label: Contributed first PIA factor + reference: + - title: SSA Primary Insurance Amount formula + href: https://www.ssa.gov/OACT/COLA/piaformula.html diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/factors/second.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/factors/second.yaml new file mode 100644 index 00000000000..03c26a6a861 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/factors/second.yaml @@ -0,0 +1,9 @@ +description: The contributed second PIA marginal factor, with an unchanged current-law default. +values: + 1983-01-01: 0.32 +metadata: + unit: /1 + label: Contributed second PIA factor + reference: + - title: SSA Primary Insurance Amount formula + href: https://www.ssa.gov/OACT/COLA/piaformula.html diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/factors/start_year.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/factors/start_year.yaml new file mode 100644 index 00000000000..f9d0e826079 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/factors/start_year.yaml @@ -0,0 +1,9 @@ +description: The first eligibility cohort reached by the contributed PIA marginal factors. +values: + 1983-01-01: 1983 +metadata: + unit: year + label: PIA factor change start cohort + reference: + - title: SSA Primary Insurance Amount formula + href: https://www.ssa.gov/OACT/COLA/piaformula.html diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/factors/third.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/factors/third.yaml new file mode 100644 index 00000000000..c67e6cacd58 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/factors/third.yaml @@ -0,0 +1,9 @@ +description: The contributed top PIA marginal factor, with an unchanged current-law default. +values: + 1983-01-01: 0.15 +metadata: + unit: /1 + label: Contributed top PIA factor + reference: + - title: SSA Primary Insurance Amount formula + href: https://www.ssa.gov/OACT/COLA/piaformula.html diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/in_effect.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/in_effect.yaml new file mode 100644 index 00000000000..27ce1357c96 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/in_effect.yaml @@ -0,0 +1,9 @@ +description: Whether the household PIA formula applies a supplied frozen full price-indexing path. +values: + 1983-01-01: false +metadata: + unit: bool + label: Full PIA price indexing + reference: + - title: SSA OACT price-indexing provision memorandum + href: https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/real_wage_scale.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/real_wage_scale.yaml new file mode 100644 index 00000000000..1b111581dc4 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/real_wage_scale.yaml @@ -0,0 +1,9 @@ +description: The supplied frozen ratio of price-index growth to wage-index growth for each eligibility cohort; unset until a documented path is supplied. +values: + 1983-01-01: null +metadata: + unit: /1 + label: PIA full price-indexing real-wage scale + reference: + - title: SSA OACT price-indexing provision memorandum + href: https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/start_year.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/start_year.yaml new file mode 100644 index 00000000000..21c7a66a80b --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/full_price_indexing/start_year.yaml @@ -0,0 +1,9 @@ +description: The first eligibility cohort reached by full PIA price indexing when enabled. +values: + 1983-01-01: 2032 +metadata: + unit: year + label: Full PIA price-indexing start cohort + reference: + - title: SSA OACT price-indexing provision memorandum + href: https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/in_effect.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/in_effect.yaml new file mode 100644 index 00000000000..cb2fd665d45 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/in_effect.yaml @@ -0,0 +1,9 @@ +description: Whether the supplied-input household calculator applies the contributed PIA path. +values: + 1983-01-01: false +metadata: + unit: bool + label: Contributed Social Security PIA path + reference: + - title: SSA Primary Insurance Amount formula + href: https://www.ssa.gov/OACT/COLA/piaformula.html diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/bend_point_fraction.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/bend_point_fraction.yaml new file mode 100644 index 00000000000..59f4a45e93c --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/bend_point_fraction.yaml @@ -0,0 +1,9 @@ +description: The supplied fraction of the eligibility-year gap between the first and second PIA bend points defining the protected threshold; there is no default fraction. +values: + 1983-01-01: null +metadata: + unit: /1 + label: Progressive PIA protected bend-point fraction + reference: + - title: SSA OACT price-indexing provision memorandum + href: https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/in_effect.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/in_effect.yaml new file mode 100644 index 00000000000..a44a9f743f6 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/in_effect.yaml @@ -0,0 +1,9 @@ +description: Whether the household PIA formula applies a supplied progressive price-indexing path; enabling it without a threshold fails. +values: + 1983-01-01: false +metadata: + unit: bool + label: Progressive PIA price indexing + reference: + - title: SSA OACT price-indexing provision memorandum + href: https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/maximum_aime.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/maximum_aime.yaml new file mode 100644 index 00000000000..ae4e15b799a --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/maximum_aime.yaml @@ -0,0 +1,9 @@ +description: The supplied frozen monthly AIME of a maximum-taxable-earnings career for each eligibility cohort. +values: + 1983-01-01: null +metadata: + unit: currency-USD + label: Progressive PIA maximum-career AIME + reference: + - title: SSA OACT price-indexing provision memorandum + href: https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/maximum_pia_target.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/maximum_pia_target.yaml new file mode 100644 index 00000000000..9c56f942877 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/maximum_pia_target.yaml @@ -0,0 +1,9 @@ +description: The supplied frozen monthly target initial PIA for the maximum-taxable-earnings career, using documented price-index bases and lags. +values: + 1983-01-01: null +metadata: + unit: currency-USD + label: Progressive PIA maximum-career target + reference: + - title: SSA OACT price-indexing provision memorandum + href: https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/start_year.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/start_year.yaml new file mode 100644 index 00000000000..7a08b087bbf --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/start_year.yaml @@ -0,0 +1,9 @@ +description: The first eligibility cohort reached by progressive PIA price indexing when enabled. +values: + 1983-01-01: 2032 +metadata: + unit: year + label: Progressive PIA price-indexing start cohort + reference: + - title: SSA OACT price-indexing provision memorandum + href: https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/threshold.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/threshold.yaml new file mode 100644 index 00000000000..e11e6aa320a --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/progressive_price_indexing/threshold.yaml @@ -0,0 +1,9 @@ +description: An optional supplied monthly dollar threshold by eligibility year, overriding the bend-point fraction when present. +values: + 1983-01-01: null +metadata: + unit: currency-USD + label: Progressive PIA protected dollar threshold + reference: + - title: SSA OACT price-indexing provision memorandum + href: https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf diff --git a/policyengine_us/parameters/gov/contrib/ssa/pia/recompute_existing.yaml b/policyengine_us/parameters/gov/contrib/ssa/pia/recompute_existing.yaml new file mode 100644 index 00000000000..1e6e57bcc8d --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/pia/recompute_existing.yaml @@ -0,0 +1,9 @@ +description: Whether the contributed PIA formula applies by payment year to earlier eligibility cohorts. +values: + 1983-01-01: false +metadata: + unit: bool + label: Recompute PIA for existing beneficiaries + reference: + - title: SSA Primary Insurance Amount formula + href: https://www.ssa.gov/OACT/COLA/piaformula.html diff --git a/policyengine_us/tests/unit/test_ss_pia_service.py b/policyengine_us/tests/unit/test_ss_pia_service.py new file mode 100644 index 00000000000..1a8804d5956 --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_pia_service.py @@ -0,0 +1,316 @@ +"""Monthly shared PIA formula, reform composition and exact inverse checks.""" + +from decimal import Decimal +from fractions import Fraction + +from hypothesis import given, strategies as st +import pytest + +from policyengine_us.tools.social_security.pia import ( + FormulaPath, + compute_pia, + inverse_pia, + inverse_unrounded, + progressive_threshold, +) + + +D = Decimal +BENDS = (960, 5785) + + +@pytest.mark.parametrize( + "aime,expected", + [(700, "630.00"), (3000, "1606.70"), (8000, "2989.20")], +) +def test_ssa_published_2023_appendix_examples(aime, expected): + # SSA Annual Statistical Supplement 2023, Appendix D, "Computing a PIA": + # https://www.ssa.gov/policy/docs/statcomps/supplement/2023/apnd.html + # The last example has an unrounded PIA of $2,989.27. + assert compute_pia(aime, 2023, bend_points=(1115, 6721)) == D(expected) + + +def test_review_fixture_is_distinct_from_s770(): + path = FormulaPath( + factor_values=(".95", ".32", ".15"), + bend_point_multipliers=("1.15", 1), + ) + assert compute_pia(5000, 2020, bend_points=BENDS) == D("2156.8") + assert compute_pia(5000, 2020, path, bend_points=BENDS) == D("2295.5") + assert compute_pia(5000, 2020, path, bend_points=BENDS, round_result=False) == D( + "2295.52" + ) + + +def test_supplied_pia_interval_and_lower_point_convention(): + interval = inverse_pia("2156.8", 2020, bend_points=BENDS) + assert interval.lower == D("5000") + assert interval.upper == D("5000.3125") + assert interval.exact_lower == 5000 + assert interval.exact_upper == Fraction(80005, 16) + assert compute_pia(interval.lower, 2020, bend_points=BENDS) == D("2156.8") + assert compute_pia(interval.exact_upper, 2020, bend_points=BENDS) == D("2156.9") + + +@pytest.mark.parametrize("pia", ["0", ".1", "864", "1000", "2408", "3000"]) +def test_inverse_at_zero_each_segment_and_bend_boundary(pia): + interval = inverse_pia(pia, 2020, bend_points=BENDS) + assert compute_pia(interval.exact_lower, 2020, bend_points=BENDS) == D(pia) + assert compute_pia(interval.lower, 2020, bend_points=BENDS) == D(pia) + assert compute_pia(interval.exact_upper, 2020, bend_points=BENDS) == D(pia) + D( + ".1" + ) + assert interval.exact_lower < interval.exact_upper + + +def test_inverse_exposes_exact_rational_nonterminating_endpoints(): + interval = inverse_pia("0.1", 2020, bend_points=BENDS) + assert interval.exact_lower == Fraction(1, 9) + assert interval.exact_upper == Fraction(2, 9) + assert Fraction(interval.lower) >= interval.exact_lower + assert inverse_unrounded(".1", 2020, bend_points=BENDS) == Fraction(1, 9) + + +@pytest.mark.parametrize("year", [1979, 1982]) +def test_pre1983_benchmark_rejected_for_computation_and_inverse(year): + # POMS RS 00605.021 B.2.b requires upward rounding before 1983. + # https://secure.ssa.gov/poms.nsf/lnx/0300605021 + with pytest.raises(ValueError, match="before 1983"): + compute_pia(1000, year, bend_points=BENDS) + with pytest.raises(ValueError, match="before 1983"): + inverse_pia(100, year, bend_points=BENDS) + + +def test_first_supported_benchmark_uses_lower_dime(): + assert compute_pia(1001, 1983, bend_points=(254, 1528)) == D("467.6") + + +def test_custom_factor_changes_only_from_selected_cohort(): + path = FormulaPath(factor_values=(".90", ".32", ".05"), factor_start_year=2027) + assert compute_pia(7000, 2026, path, bend_points=BENDS) == compute_pia( + 7000, 2026, bend_points=BENDS + ) + assert compute_pia(7000, 2027, path, bend_points=BENDS) == D("2468.7") + + +def test_custom_bend_change_has_explicit_cohort_gate(): + path = FormulaPath(effective_year=2027, bend_point_multipliers=("1.15", 1)) + assert compute_pia(5000, 2026, path, bend_points=BENDS) == D("2156.8") + assert compute_pia(5000, 2027, path, bend_points=BENDS) == D("2240.3") + + +def test_fixed_cohort_and_aime_ignore_scoring_year_without_recompute(): + path = FormulaPath(s770=True) + assert compute_pia(5000, 2020, path, 2025, bend_points=BENDS) == D("2156.8") + assert compute_pia(5000, 2020, path, 2035, bend_points=BENDS) == D("2156.8") + + +def test_s770_recomputes_old_cohort_at_original_bends_from_2026(): + # Introduced S.770 section 2: 95% first factor, 18% first-bend increase, + # effective January 2026, with recomputation at initial-eligibility bends. + # https://www.congress.gov/bill/119th-congress/senate-bill/770/text + path = FormulaPath(s770=True) + assert compute_pia(5000, 2020, path, 2025, "retroactive", bend_points=BENDS) == D( + "2156.8" + ) + assert compute_pia(5000, 2020, path, 2026, "retroactive", bend_points=BENDS) == D( + "2313.6" + ) + assert compute_pia( + 5000, 2020, path, 2026, "retroactive", bend_points=BENDS, round_result=False + ) == D("2313.664") + + +@pytest.mark.parametrize("increase,expected_gain", [(False, ".05"), (True, ".1634")]) +def test_s770_survivor_flag_controls_only_bend_increase(increase, expected_gain): + path = FormulaPath(s770=True, s770_increase_first_bend_point=increase) + baseline = compute_pia(5000, 2020, bend_points=BENDS, round_result=False) + reform = compute_pia( + 5000, 2020, path, 2026, "retroactive", bend_points=BENDS, round_result=False + ) + assert reform - baseline == D(expected_gain) * BENDS[0] + + +def test_full_price_indexing_anchor_and_all_factor_reduction(): + path = FormulaPath( + full_price_indexing_start_year=2032, + real_wage_scale_by_year={2032: 1, 2033: ".98"}, + ) + assert compute_pia(5000, 2031, path, bend_points=BENDS) == D("2156.8") + assert compute_pia(5000, 2032, path, bend_points=BENDS) == D("2156.8") + assert compute_pia(5000, 2033, path, bend_points=BENDS) == D("2113.6") + assert compute_pia(5000, 2033, path, bend_points=BENDS, round_result=False) == D( + "2113.664" + ) + + +@pytest.mark.parametrize("fraction,expected", [(0, 1000), (1, 6000), (".4", 3000)]) +def test_progressive_threshold_fraction_endpoints_and_hand_example(fraction, expected): + path = FormulaPath(bend_point_fraction=fraction) + assert progressive_threshold(2032, path, bend_points=(1000, 6000)) == expected + + +def test_progressive_threshold_grows_with_eligibility_bends(): + path = FormulaPath(bend_point_fraction=".4") + early = progressive_threshold(2032, path, bend_points=(1000, 6000)) + later = progressive_threshold(2033, path, bend_points=(1100, 6600)) + assert early == 3000 + assert later == 3300 + + +def test_progressive_dollar_path_overrides_fraction(): + path = FormulaPath(bend_point_fraction=".4", threshold_by_year={2032: 3500}) + assert progressive_threshold(2032, path, bend_points=(1000, 6000)) == 3500 + + +def _progressive_path(**overrides): + values = dict( + progressive_price_indexing_start_year=2032, + bend_point_fraction=".4", + maximum_aime_by_year={2032: 10000}, + maximum_pia_target_by_year={2032: 2800}, + ) + values.update(overrides) + return FormulaPath(**values) + + +@pytest.mark.parametrize("aime", [0, 500, 1000, 2999, 3000]) +def test_progressive_indexing_protects_every_amount_below_threshold(aime): + assert compute_pia(aime, 2032, _progressive_path(), bend_points=(1000, 6000)) == ( + compute_pia(aime, 2032, bend_points=(1000, 6000)) + ) + + +def test_progressive_indexing_continuity_and_maximum_target(): + path = _progressive_path() + # F(3000)=1540; F(10000)=3100; k=(2800-1540)/(3100-1540)=21/26. + assert ( + compute_pia(3000, 2032, path, bend_points=(1000, 6000), round_result=False) + == 1540 + ) + assert compute_pia(10000, 2032, path, bend_points=(1000, 6000)) == 2800 + assert compute_pia(6000, 2032, path, bend_points=(1000, 6000)) == D("2315.3") + + +def test_progressive_no_change_anchor_has_unit_above_threshold_multiplier(): + path = _progressive_path(maximum_pia_target_by_year={2032: 3100}) + for aime in (0, 1000, 3000, 6000, 10000, 12000): + assert compute_pia(aime, 2032, path, bend_points=(1000, 6000)) == compute_pia( + aime, 2032, bend_points=(1000, 6000) + ) + + +def test_progressive_path_before_start_needs_no_frozen_data(): + path = FormulaPath(progressive_price_indexing_start_year=2032) + assert compute_pia(5000, 2031, path, bend_points=BENDS) == D("2156.8") + + +@pytest.mark.parametrize( + "path,match", + [ + (FormulaPath(full_price_indexing_start_year=2032), "real-wage scale"), + ( + FormulaPath( + full_price_indexing_start_year=2032, + real_wage_scale_by_year={2033: 1}, + ), + "frozen value", + ), + (FormulaPath(progressive_price_indexing_start_year=2032), "fraction"), + (_progressive_path(maximum_aime_by_year=None), "maximum-career AIME"), + (_progressive_path(maximum_pia_target_by_year=None), "PIA target"), + (_progressive_path(maximum_aime_by_year={2032: 3000}), "must exceed"), + (_progressive_path(maximum_pia_target_by_year={2032: 1500}), "bounds"), + (_progressive_path(maximum_pia_target_by_year={2032: 3200}), "bounds"), + (_progressive_path(threshold_by_year={2032: 900}), "first segment"), + (_progressive_path(bend_point_fraction="1.1"), "between zero and one"), + (_progressive_path(threshold_by_year={2033: 3000}), "frozen value"), + ], +) +def test_missing_or_inconsistent_indexing_inputs_fail_explicitly(path, match): + with pytest.raises(ValueError, match=match): + compute_pia(5000, 2032, path, bend_points=(1000, 6000)) + + +@pytest.mark.parametrize("bends", [(1000, 1000), (6000, 1000), (0, 6000)]) +def test_bend_point_order_is_explicit(bends): + with pytest.raises(ValueError, match="0 < first < second"): + compute_pia(5000, 2020, bend_points=bends) + + +def test_custom_bend_multiplier_cannot_reverse_thresholds(): + with pytest.raises(ValueError, match="0 < first < second"): + compute_pia( + 5000, + 2020, + FormulaPath(bend_point_multipliers=(10, 1)), + bend_points=BENDS, + ) + + +@pytest.mark.parametrize("amount", [-1, "NaN", "Infinity", True]) +def test_invalid_aime_rejected(amount): + with pytest.raises(ValueError): + compute_pia(amount, 2020, bend_points=BENDS) + + +def test_ambiguous_rounded_pia_and_nonpositive_inverse_factors_rejected(): + with pytest.raises(ValueError, match="multiple of one dime"): + inverse_pia("100.01", 2020, bend_points=BENDS) + with pytest.raises(ValueError, match="positive historical factors"): + inverse_pia(100, 2020, bend_points=BENDS, factors=(".9", ".32", 0)) + with pytest.raises(ValueError, match="nonnegative"): + inverse_pia(-100, 2020, bend_points=BENDS) + + +def test_recompute_requires_explicit_payment_year_and_supported_mode(): + with pytest.raises(ValueError, match="requires a payment year"): + compute_pia(1000, 2020, recompute_mode="retroactive", bend_points=BENDS) + with pytest.raises(ValueError, match="recompute_mode"): + compute_pia(1000, 2020, recompute_mode="automatic", bend_points=BENDS) + with pytest.raises(ValueError, match="precede eligibility"): + compute_pia(1000, 2020, payment_year=2019, bend_points=BENDS) + + +@given(st.integers(0, 50000), st.integers(0, 50000)) +@pytest.mark.parametrize( + "path", + [ + FormulaPath(), + FormulaPath(bend_point_multipliers=("1.15", "1.02")), + FormulaPath(factor_values=(".95", ".32", ".05")), + FormulaPath(s770=True), + FormulaPath( + full_price_indexing_start_year=2032, + real_wage_scale_by_year={2032: ".98"}, + ), + _progressive_path(), + ], +) +def test_every_formula_path_is_nondecreasing_in_aime(path, first, second): + lower, upper = sorted((first, second)) + assert compute_pia(lower, 2032, path, bend_points=(1000, 6000)) <= compute_pia( + upper, 2032, path, bend_points=(1000, 6000) + ) + + +@given(st.integers(0, 50000), st.integers(1983, 2035)) +def test_no_reform_equals_current_law_at_eligibility(aime, year): + # Independent piecewise formula, evaluated as exact rational arithmetic. + expected = ( + Fraction(9, 10) * min(aime, 960) + + Fraction(32, 100) * max(min(aime, 5785) - 960, 0) + + Fraction(15, 100) * max(aime - 5785, 0) + ) + assert ( + compute_pia(aime, year, bend_points=BENDS) + == D((expected * 10).numerator // (expected * 10).denominator) / 10 + ) + + +@given(st.integers(0, 50000)) +def test_inverse_interval_contains_original_and_reproduces_rounded_pia(aime): + pia = compute_pia(aime, 2020, bend_points=BENDS) + interval = inverse_pia(pia, 2020, bend_points=BENDS) + assert interval.exact_lower <= aime < interval.exact_upper + assert compute_pia(interval.lower, 2020, bend_points=BENDS) == pia diff --git a/policyengine_us/tools/social_security/__init__.py b/policyengine_us/tools/social_security/__init__.py new file mode 100644 index 00000000000..cbd93af640f --- /dev/null +++ b/policyengine_us/tools/social_security/__init__.py @@ -0,0 +1 @@ +"""Pure monthly Social Security benefit calculation services.""" diff --git a/policyengine_us/tools/social_security/pia.py b/policyengine_us/tools/social_security/pia.py new file mode 100644 index 00000000000..10cf064de16 --- /dev/null +++ b/policyengine_us/tools/social_security/pia.py @@ -0,0 +1,333 @@ +"""Eligibility-cohort Primary Insurance Amount formulas, in monthly dollars. + +The ordinary model's reported-benefit route does not call this opt-in service. +Callers supply the unreformed bend points at initial eligibility, even when a +payment-year reform recomputes an older cohort. Benchmark years before 1983 +are unsupported because their initial-PIA rounding rule differs. + +Sources: +* https://www.ssa.gov/OACT/COLA/piaformula.html +* https://secure.ssa.gov/poms.nsf/lnx/0300605021 +* https://www.congress.gov/bill/119th-congress/senate-bill/770/text +* https://www.ssa.gov/OACT/solvency/advisoryboard_20050810.pdf + +Composition order is custom bend points/factors, S.770, full price indexing, +progressive price indexing, then one final dime truncation. Price-index scales, +maximum-career AIME and maximum-PIA targets must be frozen externally with +their index bases, lags and source provenance. No sample percentile is inferred. +""" + +from dataclasses import dataclass +from decimal import Decimal, ROUND_CEILING, localcontext +from fractions import Fraction +from typing import Mapping + + +Number = Decimal | Fraction | int | float | str +DEFAULT_FACTORS = (Decimal("0.90"), Decimal("0.32"), Decimal("0.15")) + + +@dataclass(frozen=True) +class FormulaPath: + """A supplied reform path; defaults reproduce the unreformed formula. + + Every year-keyed mapping contains values for eligibility cohorts, not + payment years. Entries are exact cohort values: a missing year fails rather + than silently carrying forward an incompletely frozen scoring path. + + ``effective_year`` gates custom bend-point changes. ``factor_start_year`` + gates custom factors independently. With ``recompute_mode='cohort'`` these + gates use eligibility; ``'retroactive'`` uses the supplied payment year and + retains the original eligibility-year bend points. The S.770 preset always + has the introduced bill's 2026 effective year. Its separately controllable + bend-point increase implements the documented restricted-survivor reading; + disabling that increase leaves the 95% first factor in place. + """ + + effective_year: int | None = None + bend_point_multipliers: tuple[Number, Number] = (1, 1) + factor_values: tuple[Number, Number, Number] | None = None + factor_start_year: int | None = None + full_price_indexing_start_year: int | None = None + real_wage_scale_by_year: Mapping[int, Number] | None = None + progressive_price_indexing_start_year: int | None = None + bend_point_fraction: Number | None = None + threshold_by_year: Mapping[int, Number] | None = None + maximum_aime_by_year: Mapping[int, Number] | None = None + maximum_pia_target_by_year: Mapping[int, Number] | None = None + s770: bool = False + s770_increase_first_bend_point: bool = True + + +@dataclass(frozen=True) +class PIAInverse: + """AIME interval giving a supplied dime-rounded unreformed PIA. + + The interval is ``[exact_lower, exact_upper)``. ``lower`` and ``upper`` are + convenient 50-digit Decimal representations, rounded toward +infinity. + This preserves the lower-endpoint point convention under forward PIA + truncation even when the rational endpoint has no finite decimal expansion. + Use the exact Fraction fields for interval membership or exact endpoints. + """ + + lower: Decimal + upper: Decimal + exact_lower: Fraction + exact_upper: Fraction + + +def _number(value: Number, name: str) -> Fraction: + try: + if isinstance(value, bool): + raise ValueError + if isinstance(value, Fraction): + return value + result = Decimal(str(value)) + if not result.is_finite(): + raise ValueError + return Fraction(result) + except (ValueError, TypeError, ArithmeticError) as error: + raise ValueError(f"{name} must be a finite number") from error + + +def _decimal(value: Fraction, *, ceiling: bool = False) -> Decimal: + with localcontext() as context: + context.prec = 50 + if ceiling: + context.rounding = ROUND_CEILING + return Decimal(value.numerator) / Decimal(value.denominator) + + +def _year(value: int, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"{name} must be an integer calendar year") + if value < 1983: + raise ValueError("PIA benchmark years before 1983 are unsupported") + return value + + +def _scale(bend_points, factors): + if len(bend_points) != 2 or len(factors) != 3: + raise ValueError("PIA requires two bend points and three factors") + bp1, bp2 = (_number(value, "bend point") for value in bend_points) + rates = tuple(_number(value, "PIA factor") for value in factors) + if not 0 < bp1 < bp2: + raise ValueError("PIA bend points must satisfy 0 < first < second") + if any(rate < 0 for rate in rates): + raise ValueError("PIA factors must be nonnegative") + return (bp1, bp2), rates + + +def _raw_pia(aime, bend_points, factors): + bp1, bp2 = bend_points + first, second, third = factors + return ( + first * min(aime, bp1) + + second * max(min(aime, bp2) - bp1, 0) + + third * max(aime - bp2, 0) + ) + + +def _active(start_year, eligibility_year, payment_year, recompute_mode): + if start_year is None: + return True + _year(start_year, "reform start year") + year = eligibility_year if recompute_mode == "cohort" else payment_year + return year >= start_year + + +def _cohort_value(path, year, name): + if path is None or year not in path: + raise ValueError(f"{name} requires a frozen value for eligibility year {year}") + return _number(path[year], name) + + +def progressive_threshold( + eligibility_year: int, + formula_path: FormulaPath, + *, + bend_points: tuple[Number, Number], +) -> Decimal: + """Return the M8 protected threshold; a supplied dollar path takes priority. + + The fractional threshold uses the unreformed eligibility-year bend points, + including when another provision changes the formula's bend points. + """ + year = _year(eligibility_year, "eligibility year") + bends, _ = _scale(bend_points, DEFAULT_FACTORS) + if formula_path.threshold_by_year is not None: + threshold = _cohort_value( + formula_path.threshold_by_year, year, "progressive dollar threshold" + ) + elif formula_path.bend_point_fraction is not None: + fraction = _number(formula_path.bend_point_fraction, "bend-point fraction") + if not 0 <= fraction <= 1: + raise ValueError("bend-point fraction must be between zero and one") + threshold = bends[0] + fraction * (bends[1] - bends[0]) + else: + raise ValueError( + "Progressive price indexing requires a bend-point fraction or " + "a supplied dollar threshold path" + ) + if threshold < bends[0]: + raise ValueError("progressive threshold cannot cut the protected first segment") + return _decimal(threshold) + + +def compute_pia( + aime: Number, + eligibility_year: int, + formula_path: FormulaPath | None = None, + payment_year: int | None = None, + recompute_mode: str = "cohort", + *, + bend_points: tuple[Number, Number], + factors: tuple[Number, Number, Number] = DEFAULT_FACTORS, + round_result: bool = True, +) -> Decimal: + """Compute a monthly PIA from supplied AIME and eligibility-year inputs. + + Direct household AIME inputs must be whole dollars (the household adapter + validates this). Fractional AIME remains supported here for the documented + inverse lower-endpoint convention and continuous reform sensitivities. + ``round_result=False`` exposes the formula before statutory dime truncation. + """ + year = _year(eligibility_year, "eligibility year") + if recompute_mode not in ("cohort", "retroactive"): + raise ValueError("recompute_mode must be 'cohort' or 'retroactive'") + if payment_year is not None: + _year(payment_year, "payment year") + if payment_year < year: + raise ValueError("payment year cannot precede eligibility year") + if recompute_mode == "retroactive" and payment_year is None: + raise ValueError("retroactive recomputation requires a payment year") + amount = _number(aime, "AIME") + if amount < 0: + raise ValueError("AIME must be nonnegative") + baseline_bends, rates = _scale(bend_points, factors) + bends = baseline_bends + path = formula_path or FormulaPath() + if _active(path.effective_year, year, payment_year, recompute_mode): + if len(path.bend_point_multipliers) != 2: + raise ValueError("two bend-point multipliers are required") + multipliers = tuple( + _number(value, "bend-point multiplier") + for value in path.bend_point_multipliers + ) + bends = tuple(bp * multiplier for bp, multiplier in zip(bends, multipliers)) + if path.factor_values is not None and _active( + path.factor_start_year, year, payment_year, recompute_mode + ): + _, rates = _scale(baseline_bends, path.factor_values) + if path.s770 and _active(2026, year, payment_year, recompute_mode): + rates = (Fraction(95, 100), rates[1], rates[2]) + if path.s770_increase_first_bend_point: + bends = (bends[0] * Fraction(118, 100), bends[1]) + bends, rates = _scale(bends, rates) + + # Full price indexing scales every marginal factor by a pinned ratio of + # price growth to wage growth, using the same documented cohort index basis. + if path.full_price_indexing_start_year is not None and _active( + path.full_price_indexing_start_year, year, payment_year, recompute_mode + ): + scale = _cohort_value(path.real_wage_scale_by_year, year, "real-wage scale") + if scale <= 0: + raise ValueError("real-wage scale must be positive") + rates = tuple(rate * scale for rate in rates) + + result = _raw_pia(amount, bends, rates) + if path.progressive_price_indexing_start_year is not None and _active( + path.progressive_price_indexing_start_year, + year, + payment_year, + recompute_mode, + ): + threshold = _number( + progressive_threshold(year, path, bend_points=baseline_bends), + "progressive threshold", + ) + if threshold < bends[0]: + raise ValueError( + "progressive threshold cuts the final formula's first segment" + ) + maximum = _cohort_value(path.maximum_aime_by_year, year, "maximum-career AIME") + target = _cohort_value( + path.maximum_pia_target_by_year, year, "maximum-career PIA target" + ) + protected_pia = _raw_pia(threshold, bends, rates) + maximum_pia = _raw_pia(maximum, bends, rates) + if maximum <= threshold or maximum_pia <= protected_pia: + raise ValueError( + "maximum-career AIME must exceed the progressive threshold" + ) + if not protected_pia <= target <= maximum_pia: + raise ValueError( + "progressive PIA target is outside the protected/maximum bounds" + ) + multiplier = (target - protected_pia) / (maximum_pia - protected_pia) + result = _raw_pia(min(amount, threshold), bends, rates) + multiplier * max( + result - protected_pia, 0 + ) + if round_result: + # Rational arithmetic keeps exact dime boundaries exact; binary floats + # and finite Decimal approximations cannot accidentally lose one dime. + return Decimal((result * 10).numerator // (result * 10).denominator) / 10 + return _decimal(result) + + +def inverse_unrounded( + pia: Number, + eligibility_year: int, + *, + bend_points: tuple[Number, Number], + factors: tuple[Number, Number, Number] = DEFAULT_FACTORS, +) -> Fraction: + """Invert the fixed unreformed, unrounded historical PIA scale exactly.""" + _year(eligibility_year, "eligibility year") + amount = _number(pia, "PIA") + if amount < 0: + raise ValueError("PIA must be nonnegative") + bends, rates = _scale(bend_points, factors) + if any(rate <= 0 for rate in rates): + raise ValueError("baseline inverse requires three positive historical factors") + bp1, bp2 = bends + first, second, third = rates + first_pia = first * bp1 + second_pia = first_pia + second * (bp2 - bp1) + if amount <= first_pia: + return amount / first + if amount <= second_pia: + return bp1 + (amount - first_pia) / second + return bp2 + (amount - second_pia) / third + + +def inverse_pia( + pia: Number, + eligibility_year: int, + *, + bend_points: tuple[Number, Number], + factors: tuple[Number, Number, Number] = DEFAULT_FACTORS, +) -> PIAInverse: + """Invert an exact dime-rounded baseline PIA, never reform factors. + + An observed rounded paid benefit is a wider measurement interval and must + first be propagated backward through its payment/claim/COLA operations. + """ + amount = _number(pia, "PIA") + if (amount * 10).denominator != 1: + raise ValueError("an exact eligibility PIA must be a multiple of one dime") + lower = inverse_unrounded( + amount, eligibility_year, bend_points=bend_points, factors=factors + ) + upper = inverse_unrounded( + amount + Fraction(1, 10), + eligibility_year, + bend_points=bend_points, + factors=factors, + ) + return PIAInverse( + lower=_decimal(lower, ceiling=True), + upper=_decimal(upper, ceiling=True), + exact_lower=lower, + exact_upper=upper, + ) From 93a54a0fc88a1e9f8fb1148258a8615084a50d5a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 02:12:44 -0400 Subject: [PATCH 03/16] Add statutory COLA ledger and separate historical bend points --- .../cola/december_1999_as_paid_rate.yaml | 9 + ...ecember_1999_correction_payment_month.yaml | 9 + .../cola/effective_month_number.yaml | 10 + .../cola/first_payment_month_number.yaml | 10 + .../cola/first_payment_year_offset.yaml | 10 + .../cola/historical_last_effective_year.yaml | 9 + .../cola/pia_rounding_direction.yaml | 10 + .../cola/pia_rounding_increment.yaml | 9 + .../gov/ssa/social_security/cola/rate.yaml | 62 ++++ .../pia/bend_points/first.yaml | 57 ++++ .../pia/bend_points/second.yaml | 57 ++++ .../tests/unit/test_ss_cola_schedule.py | 208 +++++++++++++ policyengine_us/tools/social_security/cola.py | 292 ++++++++++++++++++ 13 files changed, 752 insertions(+) create mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/december_1999_as_paid_rate.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/december_1999_correction_payment_month.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/effective_month_number.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_month_number.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_year_offset.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/historical_last_effective_year.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_direction.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_increment.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/rate.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/pia/bend_points/first.yaml create mode 100644 policyengine_us/parameters/gov/ssa/social_security/pia/bend_points/second.yaml create mode 100644 policyengine_us/tests/unit/test_ss_cola_schedule.py create mode 100644 policyengine_us/tools/social_security/cola.py diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/december_1999_as_paid_rate.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/december_1999_as_paid_rate.yaml new file mode 100644 index 00000000000..ba28645610c --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/cola/december_1999_as_paid_rate.yaml @@ -0,0 +1,9 @@ +description: Original December 1999 COLA used in checks before the July 2001 effective correction (first ordinary corrected check August 2001). +values: + 1975-06-01: 0.024 +metadata: + unit: /1 + label: Original December 1999 Social Security COLA + reference: + - title: SSA COLA history, timing, and computation + href: https://secure.ssa.gov/poms.nsf/lnx/0300601122 diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/december_1999_correction_payment_month.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/december_1999_correction_payment_month.yaml new file mode 100644 index 00000000000..0f4e51de20d --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/cola/december_1999_correction_payment_month.yaml @@ -0,0 +1,9 @@ +description: First ordinary check month reflecting the July 2001 correction of the December 1999 COLA, encoded YYYYMM; excludes the special one-time arrears payment. +values: + 1975-06-01: 200108 +metadata: + unit: year + label: First corrected December 1999 COLA check month + reference: + - title: SSA COLA history, timing, and computation + href: https://secure.ssa.gov/poms.nsf/lnx/0300601122 diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/effective_month_number.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/effective_month_number.yaml new file mode 100644 index 00000000000..20052d37858 --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/cola/effective_month_number.yaml @@ -0,0 +1,10 @@ +description: Month in which a statutory Social Security COLA changes entitlement. +values: + 1975-06-01: 6 + 1983-12-01: 12 +metadata: + unit: year + label: Effective month of Social Security COLA + reference: + - title: SSA COLA history, timing, and computation + href: https://www.ssa.gov/OACT/COLA/colaseries.html diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_month_number.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_month_number.yaml new file mode 100644 index 00000000000..7b2b8c2be34 --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_month_number.yaml @@ -0,0 +1,10 @@ +description: Month of the first ordinary Social Security check reflecting the effective COLA. +values: + 1975-06-01: 7 + 1983-12-01: 1 +metadata: + unit: year + label: First check month for Social Security COLA + reference: + - title: SSA COLA history, timing, and computation + href: https://www.ssa.gov/OACT/COLA/latestCOLA.html diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_year_offset.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_year_offset.yaml new file mode 100644 index 00000000000..556c1f7f401 --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_year_offset.yaml @@ -0,0 +1,10 @@ +description: Calendar-year offset between a Social Security COLA's effective and first ordinary check months. +values: + 1975-06-01: 0 + 1983-12-01: 1 +metadata: + unit: year + label: First check year offset for Social Security COLA + reference: + - title: SSA COLA history, timing, and computation + href: https://www.ssa.gov/OACT/COLA/latestCOLA.html diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/historical_last_effective_year.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/historical_last_effective_year.yaml new file mode 100644 index 00000000000..5e47aeda4eb --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/cola/historical_last_effective_year.yaml @@ -0,0 +1,9 @@ +description: Last effective COLA year with an audited historical rate; later rates use the runtime January-keyed Q3 SSA schedule. +values: + 1975-06-01: 2026 +metadata: + unit: year + label: Last historical Social Security COLA year + reference: + - title: SSA COLA history, timing, and computation + href: https://www.ssa.gov/OACT/COLA/colaseries.html diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_direction.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_direction.yaml new file mode 100644 index 00000000000..1e40f1a00c5 --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_direction.yaml @@ -0,0 +1,10 @@ +description: "Direction of PIA rounding after each COLA: 1 rounds up and -1 rounds down. The household service rejects unsupported historical rounding." +values: + 1975-06-01: 1 + 1982-06-01: -1 +metadata: + unit: year + label: Social Security COLA PIA rounding direction + reference: + - title: SSA COLA history, timing, and computation + href: https://secure.ssa.gov/poms.nsf/lnx/0300601020 diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_increment.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_increment.yaml new file mode 100644 index 00000000000..034d0035834 --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_increment.yaml @@ -0,0 +1,9 @@ +description: Dollar increment used to round PIA after each Social Security COLA. +values: + 1975-06-01: 0.1 +metadata: + unit: currency-USD + label: Social Security COLA PIA rounding increment + reference: + - title: SSA COLA history, timing, and computation + href: https://secure.ssa.gov/poms.nsf/lnx/0300601020 diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/rate.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/rate.yaml new file mode 100644 index 00000000000..753bdf4522b --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/cola/rate.yaml @@ -0,0 +1,62 @@ +description: Statutory Social Security COLA rates by effective month; December 1999 uses the corrected rate, with its original rate and correction timing recorded separately. +values: + 1975-06-01: 0.080 # First check 1975-07 + 1976-06-01: 0.064 # First check 1976-07 + 1977-06-01: 0.059 # First check 1977-07 + 1978-06-01: 0.065 # First check 1978-07 + 1979-06-01: 0.099 # First check 1979-07 + 1980-06-01: 0.143 # First check 1980-07 + 1981-06-01: 0.112 # First check 1981-07 + 1982-06-01: 0.074 # First check 1982-07 + 1983-12-01: 0.035 # First check 1984-01 + 1984-12-01: 0.035 # First check 1985-01 + 1985-12-01: 0.031 # First check 1986-01 + 1986-12-01: 0.013 # First check 1987-01 + 1987-12-01: 0.042 # First check 1988-01 + 1988-12-01: 0.040 # First check 1989-01 + 1989-12-01: 0.047 # First check 1990-01 + 1990-12-01: 0.054 # First check 1991-01 + 1991-12-01: 0.037 # First check 1992-01 + 1992-12-01: 0.030 # First check 1993-01 + 1993-12-01: 0.026 # First check 1994-01 + 1994-12-01: 0.028 # First check 1995-01 + 1995-12-01: 0.026 # First check 1996-01 + 1996-12-01: 0.029 # First check 1997-01 + 1997-12-01: 0.021 # First check 1998-01 + 1998-12-01: 0.013 # First check 1999-01 + 1999-12-01: 0.025 # First check 2000-01 + 2000-12-01: 0.035 # First check 2001-01 + 2001-12-01: 0.026 # First check 2002-01 + 2002-12-01: 0.014 # First check 2003-01 + 2003-12-01: 0.021 # First check 2004-01 + 2004-12-01: 0.027 # First check 2005-01 + 2005-12-01: 0.041 # First check 2006-01 + 2006-12-01: 0.033 # First check 2007-01 + 2007-12-01: 0.023 # First check 2008-01 + 2008-12-01: 0.058 # First check 2009-01 + 2009-12-01: 0.000 # First check 2010-01 + 2010-12-01: 0.000 # First check 2011-01 + 2011-12-01: 0.036 # First check 2012-01 + 2012-12-01: 0.017 # First check 2013-01 + 2013-12-01: 0.015 # First check 2014-01 + 2014-12-01: 0.017 # First check 2015-01 + 2015-12-01: 0.000 # First check 2016-01 + 2016-12-01: 0.003 # First check 2017-01 + 2017-12-01: 0.020 # First check 2018-01 + 2018-12-01: 0.028 # First check 2019-01 + 2019-12-01: 0.016 # First check 2020-01 + 2020-12-01: 0.013 # First check 2021-01 + 2021-12-01: 0.059 # First check 2022-01 + 2022-12-01: 0.087 # First check 2023-01 + 2023-12-01: 0.032 # First check 2024-01 + 2024-12-01: 0.025 # First check 2025-01 + 2025-12-01: 0.028 # First check 2026-01 + 2026-12-01: 0.036 # First check 2027-01 +metadata: + unit: /1 + label: Statutory Social Security COLA rate + reference: + - title: SSA Cost-Of-Living Adjustments, including corrected December 1999 rate + href: https://www.ssa.gov/OACT/COLA/colaseries.html + - title: POMS RS 00601.120, Cost-Of-Living Adjustment + href: https://secure.ssa.gov/poms.nsf/lnx/0300601120 diff --git a/policyengine_us/parameters/gov/ssa/social_security/pia/bend_points/first.yaml b/policyengine_us/parameters/gov/ssa/social_security/pia/bend_points/first.yaml new file mode 100644 index 00000000000..0ad952e4e6e --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/pia/bend_points/first.yaml @@ -0,0 +1,57 @@ +description: Social Security historical first PIA bend point, selected by the worker's eligibility year for the opt-in household service. +values: + 1979-01-01: 180 + 1980-01-01: 194 + 1981-01-01: 211 + 1982-01-01: 230 + 1983-01-01: 254 + 1984-01-01: 267 + 1985-01-01: 280 + 1986-01-01: 297 + 1987-01-01: 310 + 1988-01-01: 319 + 1989-01-01: 339 + 1990-01-01: 356 + 1991-01-01: 370 + 1992-01-01: 387 + 1993-01-01: 401 + 1994-01-01: 422 + 1995-01-01: 426 + 1996-01-01: 437 + 1997-01-01: 455 + 1998-01-01: 477 + 1999-01-01: 505 + 2000-01-01: 531 + 2001-01-01: 561 + 2002-01-01: 592 + 2003-01-01: 606 + 2004-01-01: 612 + 2005-01-01: 627 + 2006-01-01: 656 + 2007-01-01: 680 + 2008-01-01: 711 + 2009-01-01: 744 + 2010-01-01: 761 + 2011-01-01: 749 + 2012-01-01: 767 + 2013-01-01: 791 + 2014-01-01: 816 + 2015-01-01: 826 + 2016-01-01: 856 + 2017-01-01: 885 + 2018-01-01: 895 + 2019-01-01: 926 + 2020-01-01: 960 + 2021-01-01: 996 + 2022-01-01: 1024 + 2023-01-01: 1115 + 2024-01-01: 1174 + 2025-01-01: 1226 + 2026-01-01: 1286 +metadata: + unit: currency-USD + period: year + label: Social Security historical first PIA bend point + reference: + - title: SSA Benefit Formula Bend Points (year of eligibility) + href: https://www.ssa.gov/OACT/COLA/bendpoints.html diff --git a/policyengine_us/parameters/gov/ssa/social_security/pia/bend_points/second.yaml b/policyengine_us/parameters/gov/ssa/social_security/pia/bend_points/second.yaml new file mode 100644 index 00000000000..45e04e98f27 --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/social_security/pia/bend_points/second.yaml @@ -0,0 +1,57 @@ +description: Social Security historical second PIA bend point, selected by the worker's eligibility year for the opt-in household service. +values: + 1979-01-01: 1085 + 1980-01-01: 1171 + 1981-01-01: 1274 + 1982-01-01: 1388 + 1983-01-01: 1528 + 1984-01-01: 1612 + 1985-01-01: 1691 + 1986-01-01: 1790 + 1987-01-01: 1866 + 1988-01-01: 1922 + 1989-01-01: 2044 + 1990-01-01: 2145 + 1991-01-01: 2230 + 1992-01-01: 2333 + 1993-01-01: 2420 + 1994-01-01: 2545 + 1995-01-01: 2567 + 1996-01-01: 2635 + 1997-01-01: 2741 + 1998-01-01: 2875 + 1999-01-01: 3043 + 2000-01-01: 3202 + 2001-01-01: 3381 + 2002-01-01: 3567 + 2003-01-01: 3653 + 2004-01-01: 3689 + 2005-01-01: 3779 + 2006-01-01: 3955 + 2007-01-01: 4100 + 2008-01-01: 4288 + 2009-01-01: 4483 + 2010-01-01: 4586 + 2011-01-01: 4517 + 2012-01-01: 4624 + 2013-01-01: 4768 + 2014-01-01: 4917 + 2015-01-01: 4980 + 2016-01-01: 5157 + 2017-01-01: 5336 + 2018-01-01: 5397 + 2019-01-01: 5583 + 2020-01-01: 5785 + 2021-01-01: 6002 + 2022-01-01: 6172 + 2023-01-01: 6721 + 2024-01-01: 7078 + 2025-01-01: 7391 + 2026-01-01: 7749 +metadata: + unit: currency-USD + period: year + label: Social Security historical second PIA bend point + reference: + - title: SSA Benefit Formula Bend Points (year of eligibility) + href: https://www.ssa.gov/OACT/COLA/bendpoints.html diff --git a/policyengine_us/tests/unit/test_ss_cola_schedule.py b/policyengine_us/tests/unit/test_ss_cola_schedule.py new file mode 100644 index 00000000000..ac02d44ca27 --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_cola_schedule.py @@ -0,0 +1,208 @@ +"""COLA timing, statutory rounding, projections and inverse intervals. + +Published examples are cited at their assertions. These tests exercise gross +monthly recurring benefits and exclude Medicare deductions and 2001 arrears. +""" + +from decimal import Decimal, ROUND_FLOOR +from fractions import Fraction + +import pytest +from hypothesis import given, settings, strategies as st + +from policyengine_us import Simulation +from policyengine_us.tools.social_security.cola import ( + ColaEvent, + adjusted_events, + apply_colas, + cola_factor, + projected_events, + read_parameter_events, + reverse_colas_interval, +) + + +D = Decimal + + +@pytest.fixture(scope="module") +def parameters(): + return Simulation.default_tax_benefit_system_instance.parameters + + +def test_ssa_published_cola_application(): + # https://www.ssa.gov/oact/COLA/colaapplic.html + event = ColaEvent("2011-12", "2012-01", D(".036")) + assert apply_colas("2197.50", 2011, "2012-01", [event]) == D("2276.60") + + +def test_ssa_supplement_sequential_cola_example(): + # https://www.ssa.gov/policy/docs/statcomps/supplement/2023/apnd.html + # This published arithmetic illustration deliberately uses a hypothetical + # 2020 benchmark with a separately illustrated PIA; it is not an E2023 PIA. + events = [ + ColaEvent("2020-12", "2021-01", D(".013")), + ColaEvent("2021-12", "2022-01", D(".059")), + ColaEvent("2022-12", "2023-01", D(".087")), + ] + assert apply_colas("1606.70", 2020, "2021-01", events) == D("1627.50") + assert apply_colas("1606.70", 2020, "2022-01", events) == D("1723.50") + assert apply_colas("1606.70", 2020, "2023-01", events) == D("1873.40") + + +def test_eligibility_colas_accrue_before_claiming_and_start_next_january(): + events = [ColaEvent("1983-12", "1984-01", D(".035"))] + assert apply_colas("1000", 1983, "1983-12", events) == D("1000") + assert apply_colas("1000", 1983, "1984-01", events) == D("1035") + assert apply_colas("1000", 1984, "1984-01", events) == D("1000") + + +def test_truncates_after_every_cola_and_retains_raw_diagnostic(): + events = [ + ColaEvent("2020-12", "2021-01", D(".1")), + ColaEvent("2021-12", "2022-01", D(".1")), + ] + assert apply_colas(".9", 2020, "2022-01", events) == D(".9") + assert cola_factor(2020, "2022-01", events) == D("1.21") + assert apply_colas(0, 2020, "2022-01", events) == 0 + + +@pytest.mark.parametrize("year", [1979, 1982]) +def test_rejects_unsupported_benchmarks_even_without_exposed_colas(year): + with pytest.raises(ValueError, match="1983"): + apply_colas(1000, year, "2026-01", []) + with pytest.raises(ValueError, match="1983"): + reverse_colas_interval(1000, 1001, year, "2026-01", []) + + +def test_rejects_unsupported_exposed_rounding_rule(): + event = ColaEvent("1983-12", "1984-01", D(".035"), "dime_ceiling") + with pytest.raises(ValueError, match="rounding"): + apply_colas(1000, 1983, "1984-01", [event]) + + +def test_cola_changes_and_withholding_are_joint_and_preserve_precision(): + baseline = [ + ColaEvent("2026-12", "2027-01", D(".02")), + ColaEvent("2027-12", "2028-01", D(0)), + ColaEvent("2028-12", "2029-01", D(".01")), + ] + adjusted = adjusted_events( + baseline, + {2027: D(".0015"), 2028: D("-.003"), 2029: D(".0015")}, + withheld_years=[2029], + ) + assert [event.rate for event in adjusted] == [D(".0215"), D(0), D(0)] + assert apply_colas(1000, 2026, "2029-01", adjusted) == D("1021.5") + + +def test_projection_uses_statutory_rounding_and_retains_high_water(): + events = projected_events({2025: D("308.729"), 2026: D("317.265")}) + assert events[0].rate == D(".028") + # Half-up at .05 percentage point; ties-to-even would incorrectly be zero. + assert projected_events({2025: 100, 2026: D("100.05")})[0].rate == D(".001") + events = projected_events({2025: 100, 2026: 99, 2027: D("100.04"), 2028: 101}) + assert [event.rate for event in events] == [D(0), D(0), D(".010")] + + +def test_projection_rejects_missing_or_invalid_q3_path(): + with pytest.raises(ValueError, match="consecutive"): + projected_events({2025: 100, 2027: 101}) + with pytest.raises(ValueError, match="positive"): + projected_events({2025: 0, 2026: 101}) + + +def test_audited_history_timing_corrected_1999_and_future_horizon(parameters): + # https://www.ssa.gov/OACT/COLA/colaseries.html + events = read_parameter_events(parameters, 2059) + by_effective = {event.effective_month: event for event in events} + assert by_effective["1975-06"].payment_month == "1975-07" + assert by_effective["1982-06"].payment_month == "1982-07" + assert by_effective["1983-12"].payment_month == "1984-01" + assert by_effective["1999-12"].rate == D(".025") + assert by_effective["1999-12"].as_paid_rate == D(".024") + assert by_effective["2026-12"].rate == D(".036") + assert by_effective["2058-12"].payment_month == "2059-01" + assert apply_colas("1000", 2057, "2059-01", events) >= D("1000") + + +def test_projection_explicitly_rejects_after_runtime_frozen_horizon(parameters): + with pytest.raises(ValueError, match="frozen Q3 horizon 2100"): + read_parameter_events(parameters, 2101) + + +def test_december_1999_original_checks_and_july_2001_correction(parameters): + # https://secure.ssa.gov/poms.nsf/lnx/0300601122 + # The corrected July2001 PIA reconstructs the two prior COLAs, with dime + # truncation after each. Original 2000 checks remain the amounts paid. + events = read_parameter_events(parameters, 2002) + assert apply_colas(1000, 1999, "2000-01", events) == D("1024") + assert apply_colas(1000, 1999, "2001-07", events) == D("1059.8") + assert apply_colas(1000, 1999, "2001-08", events) == D("1060.8") + # An E2000 worker receives no December1999 correction. + assert apply_colas(1000, 2000, "2001-08", events) == D("1035") + + +def test_historical_bend_points_are_separate_from_legacy_scale(parameters): + # https://www.ssa.gov/OACT/COLA/bendpoints.html + for year, expected in [ + (1979, (180, 1085)), + (1983, (254, 1528)), + (2000, (531, 3202)), + (2026, (1286, 7749)), + ]: + bp = parameters(f"{year}-01-01").gov.ssa.social_security.pia.bend_points + assert (bp.first, bp.second) == expected + for year in range(2015, 2027): + pia = parameters(f"{year}-01-01").gov.ssa.social_security.pia + assert list(pia.formula_factors.thresholds)[1:] == [ + pia.bend_points.first, + pia.bend_points.second, + ] + + +@settings(max_examples=60, deadline=None) +@given( + pia_dimes=st.integers(min_value=0, max_value=500_000), + rates=st.lists(st.integers(min_value=0, max_value=100), min_size=0, max_size=5), +) +def test_reverse_cola_interval_exactly_contains_possible_dime_pias(pia_dimes, rates): + pia = D(pia_dimes) / 10 + events = [ + ColaEvent(f"{2020 + i}-12", f"{2021 + i}-01", D(rate) / 1000) + for i, rate in enumerate(rates) + ] + current = apply_colas(pia, 2020, "2026-01", events) + check = current.quantize(D(1), rounding=ROUND_FLOOR) + lower, upper = reverse_colas_interval(check, check + 1, 2020, "2026-01", events) + assert lower <= pia < upper + assert check <= apply_colas(lower, 2020, "2026-01", events) < check + 1 + assert apply_colas(upper, 2020, "2026-01", events) >= check + 1 + if lower >= D(".1"): + assert apply_colas(lower - D(".1"), 2020, "2026-01", events) < check + + +def test_reverse_cola_interval_rejects_unattainable_payment(): + event = ColaEvent("2020-12", "2021-01", D(1)) + with pytest.raises(ValueError, match="no eligible PIA"): + reverse_colas_interval(".1", ".2", 2020, "2021-01", [event]) + + +def test_reverse_cola_interval_accepts_exact_nonterminating_ratio_endpoints(): + event = ColaEvent("2020-12", "2021-01", D(".1")) + assert reverse_colas_interval( + Fraction(1, 3), Fraction(2, 3), 2020, "2021-01", [event] + ) == (D(".4"), D(".7")) + # A rational endpoint immediately above a dime must not round down to that + # dime when a Decimal context cannot retain all of its significant digits. + precise_lower = Fraction(10**50 + 1, 10**51) + assert reverse_colas_interval( + precise_lower, Fraction(3, 10), 2020, "2021-01", [] + ) == (D(".2"), D(".3")) + + +def test_cola_truncation_preserves_exact_boundary_at_high_rate_precision(): + just_below_ten_percent = D("0." + "0" + "9" * 49) + event = ColaEvent("2020-12", "2021-01", just_below_ten_percent) + # 1*(1+.0999...) is strictly below1.1 even beyond Decimal's context. + assert apply_colas(1, 2020, "2021-01", [event]) == D("1.0") diff --git a/policyengine_us/tools/social_security/cola.py b/policyengine_us/tools/social_security/cola.py new file mode 100644 index 00000000000..1e95763e825 --- /dev/null +++ b/policyengine_us/tools/social_security/cola.py @@ -0,0 +1,292 @@ +"""Statutory COLA events for the opt-in household calculator. + +Amounts are monthly dollars. The December COLA changes the following January +check; ``payment_month`` always denotes the check month, not entitlement month. +Historical observations and rounding rules come from SSA, never SOI uprating. +""" + +from dataclasses import dataclass, replace +from datetime import date +from decimal import Decimal, ROUND_HALF_UP +from fractions import Fraction +from typing import Iterable, Mapping + + +DIME = Decimal("0.1") + + +def _decimal(value) -> Decimal: + result = Decimal(str(value)) + if not result.is_finite(): + raise ValueError("A COLA amount or rate must be finite") + return result + + +def _month(value) -> str: + if isinstance(value, date): + return value.strftime("%Y-%m") + result = str(value) + try: + parsed = date.fromisoformat(result + "-01" if len(result) == 7 else result) + except ValueError as error: + raise ValueError("A COLA month must be YYYY-MM or an ISO date") from error + return parsed.strftime("%Y-%m") + + +def floor_dime(value) -> Decimal: + value = value if isinstance(value, Fraction) else Fraction(_decimal(value)) + dimes = value * 10 + return Decimal(dimes.numerator // dimes.denominator) / 10 + + +def _ceil_dime(value) -> Decimal: + value = value if isinstance(value, Fraction) else Fraction(_decimal(value)) + dimes = value * 10 + return Decimal(-(-dimes.numerator // dimes.denominator)) / 10 + + +@dataclass(frozen=True) +class ColaEvent: + effective_month: str + payment_month: str + rate: Decimal + rounding: str = "dime_floor" + # December 1999 was paid at 2.4% until the July 2001 adjustment, when SSA + # recomputed the 1999/2000 increases at 2.5%/3.5%. Keeping both values + # reproduces ordinary checks before and after the correction. The special + # one-time arrears payment is outside this gross recurring-benefit service. + as_paid_rate: Decimal | None = None + correction_payment_month: str | None = None + + def __post_init__(self): + object.__setattr__(self, "effective_month", _month(self.effective_month)) + object.__setattr__(self, "payment_month", _month(self.payment_month)) + object.__setattr__(self, "rate", _decimal(self.rate)) + if self.rate < 0 or self.payment_month <= self.effective_month: + raise ValueError("COLAs require a nonnegative rate and later check month") + if self.as_paid_rate is not None: + object.__setattr__(self, "as_paid_rate", _decimal(self.as_paid_rate)) + if self.as_paid_rate < 0 or self.correction_payment_month is None: + raise ValueError("An as-paid COLA requires its correction month") + if self.correction_payment_month is not None: + object.__setattr__( + self, "correction_payment_month", _month(self.correction_payment_month) + ) + + def rate_at_valuation(self, payment_month) -> Decimal: + if ( + self.as_paid_rate is not None + and _month(payment_month) < self.correction_payment_month + ): + return self.as_paid_rate + return self.rate + + +def exposed_events(eligibility_year, payment_month, events) -> tuple[ColaEvent, ...]: + """Select events from the benchmark year, including pre-claim COLAs.""" + if int(eligibility_year) < 1983: + raise ValueError("COLA calculations require a benchmark year of 1983 or later") + target = _month(payment_month) + selected = tuple( + sorted( + ( + event + for event in events + if int(event.effective_month[:4]) >= int(eligibility_year) + and event.payment_month <= target + ), + key=lambda event: event.payment_month, + ) + ) + if len({event.payment_month for event in selected}) != len(selected): + raise ValueError("Duplicate COLA payment months are ambiguous") + for event in selected: + if event.rounding != "dime_floor" or event.effective_month < "1982-06": + raise ValueError("The applicable historical COLA rounding is unsupported") + return selected + + +def apply_colas(pia, eligibility_year, payment_month, events) -> Decimal: + """Truncate the eligibility PIA and truncate again after every COLA.""" + result = _decimal(pia) + if result < 0: + raise ValueError("PIA must be nonnegative") + result = floor_dime(result) + for event in exposed_events(eligibility_year, payment_month, events): + result = floor_dime( + Fraction(result) * (1 + Fraction(event.rate_at_valuation(payment_month))) + ) + return result + + +def cola_factor(eligibility_year, payment_month, events) -> Decimal: + """Unrounded accumulation for diagnostics; not a replacement for apply_colas.""" + result = Decimal(1) + for event in exposed_events(eligibility_year, payment_month, events): + result *= 1 + event.rate_at_valuation(payment_month) + return result + + +def reverse_colas_interval(lower, upper, eligibility_year, payment_month, events): + """Exact half-open preimage on the eligibility-PIA dime lattice. + + Fraction endpoints are accepted to preserve an exact amount/ratio division. + Each returned endpoint is a dime. An eligibility PIA on that lattice is + admissible iff lower <= PIA < upper; an empty preimage raises ValueError. + This carries payment-rounding uncertainty backward instead of dividing a + rounded check by an unrounded cumulative COLA factor. + """ + lower, upper = _ceil_dime(lower), _ceil_dime(upper) + if lower < 0 or lower >= upper: + raise ValueError("A PIA interval must be nonnegative and nonempty") + for event in reversed(exposed_events(eligibility_year, payment_month, events)): + factor = 1 + Fraction(event.rate_at_valuation(payment_month)) + lower, upper = ( + _ceil_dime(Fraction(lower) / factor), + _ceil_dime(Fraction(upper) / factor), + ) + if lower >= upper: + raise ValueError("The supplied payment interval has no eligible PIA") + return lower, upper + + +def adjusted_events( + events: Iterable[ColaEvent], + rate_changes: Mapping[int, Decimal] | None = None, + withheld_years: Iterable[int] = (), +) -> tuple[ColaEvent, ...]: + """Apply percentage-point changes and withholding jointly, exactly once. + + Keys denote check calendar years. A withheld event has rate zero even if a + rate increase is also selected. Preserve the supplied precision after a + policy addition, and floor the proposed COLA at zero. + """ + changes = rate_changes or {} + withheld = set(withheld_years) + result = [] + for event in events: + year = int(event.payment_month[:4]) + delta = _decimal(changes.get(year, 0)) + rate = Decimal(0) if year in withheld else max(Decimal(0), event.rate + delta) + paid = event.as_paid_rate + if paid is not None: + paid = Decimal(0) if year in withheld else max(Decimal(0), paid + delta) + result.append(replace(event, rate=rate, as_paid_rate=paid)) + return tuple(result) + + +def projected_events( + q3_by_payment_year: Mapping[int, Decimal], +) -> tuple[ColaEvent, ...]: + """Freeze statutory rounded rates from January-keyed Q3 index levels. + + The first observation is the last effective-COLA anchor. Zero-COLA years + retain that anchor; a new positive rate advances it. SSA rounds a positive + fractional rate to .001 (one tenth of one percentage point), half up. + """ + observations = sorted( + (int(year), _decimal(value)) for year, value in q3_by_payment_year.items() + ) + if not observations or any(value <= 0 for _, value in observations): + raise ValueError("Projection requires a positive Q3-index anchor and path") + anchor_year, high_water = observations[0] + result = [] + for year, level in observations[1:]: + if year != anchor_year + 1: + raise ValueError("The projected Q3 path must contain consecutive years") + rate = max( + Decimal(0), + (level / high_water - 1).quantize(Decimal("0.001"), rounding=ROUND_HALF_UP), + ) + result.append(ColaEvent(f"{year - 1}-12", f"{year}-01", rate)) + if rate > 0: + high_water = level + anchor_year = year + return tuple(result) + + +def read_parameter_events(parameters, through_year: int) -> tuple[ColaEvent, ...]: + """Read authored statutory history and freeze projected runtime SSA Q3 data. + + ``parameters`` is the callable parameter tree, not an instant snapshot. + Missing forecast years fail explicitly. Runtime SSA uprating extensions + supply the household horizon beyond the population scoring window. + """ + through_year = int(through_year) + if through_year < 1983: + raise ValueError("COLA calculations require a benchmark year of 1983 or later") + try: + history = parameters("2026-01-01").gov.ssa.social_security.cola + last_year = int(history.historical_last_effective_year) + result = [] + for year in range(1975, min(last_year, through_year) + 1): + # The effective month changed once, in 1983. Read both dates from + # parameters so an event never silently receives a January date. + node = parameters(f"{year}-12-01").gov.ssa.social_security.cola + effective = f"{year}-{int(node.effective_month_number):02d}" + payment = f"{year + int(node.first_payment_year_offset)}-{int(node.first_payment_month_number):02d}" + rule = ( + "dime_floor" + if int(node.pia_rounding_direction) == -1 + and _decimal(node.pia_rounding_increment) == DIME + else "unsupported_historical_rounding" + ) + kwargs = {} + if year == 1999: + kwargs = { + "as_paid_rate": _decimal(node.december_1999_as_paid_rate), + "correction_payment_month": str( + int(node.december_1999_correction_payment_month) + ), + } + kwargs["correction_payment_month"] = ( + kwargs["correction_payment_month"][:4] + + "-" + + kwargs["correction_payment_month"][4:] + ) + result.append( + ColaEvent(effective, payment, _decimal(node.rate), rule, **kwargs) + ) + if through_year > last_year + 1: + # Core parameters carry their final scalar indefinitely. That is + # not evidence of a frozen Q3 projection after its last dated + # observation. Inspect the raw tree, including runtime extensions, + # before reading instant values that could silently carry forward. + q3_years = { + int(observation.instant_str[:4]) + for observation in parameters.gov.ssa.uprating.values_list + if observation.value is not None + and observation.instant_str[5:] == "01-01" + } + if not q3_years or through_year > max(q3_years): + horizon = max(q3_years) if q3_years else "unavailable" + raise ValueError( + f"Requested COLA year {through_year} exceeds the frozen Q3 horizon {horizon}" + ) + # Find the most recent nonzero historical COLA for the high-water + # anchor. A zero-COLA year must not reset that comparison basis. + anchor_year = last_year + while ( + parameters(f"{anchor_year}-12-01").gov.ssa.social_security.cola.rate + == 0 + ): + anchor_year -= 1 + missing_years = set(range(anchor_year + 1, through_year + 1)) - q3_years + if missing_years: + raise ValueError( + f"The frozen SSA Q3 path is missing payment year {min(missing_years)}" + ) + q3 = { + year: _decimal(parameters(f"{year}-01-01").gov.ssa.uprating) + for year in range(anchor_year + 1, through_year + 1) + } + result.extend( + event + for event in projected_events(q3) + if int(event.payment_month[:4]) > last_year + 1 + ) + return tuple(result) + except (AttributeError, KeyError, TypeError) as error: + raise ValueError( + f"No supported SSA COLA/index path through {through_year}" + ) from error From 73460e3bc6d3d4ae6cb369e96d3abc2c63f6d9fd Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 02:28:31 -0400 Subject: [PATCH 04/16] Adapt calculator parameters and reuse shared statutory history --- .../benefit_levers/across_the_board/rate.yaml | 7 + .../across_the_board/start_year.yaml | 7 + .../benefit_levers/cola/alternative_rate.yaml | 7 + .../benefit_levers/cola/effective_month.yaml | 7 + .../benefit_levers/cola/effective_year.yaml | 7 + .../ssa/benefit_levers/cola/end_year.yaml | 7 + .../ssa/benefit_levers/cola/pp_change.yaml | 7 + .../ssa/benefit_levers/cola/start_year.yaml | 7 + .../cola/withholding_enabled.yaml | 7 + .../ssa/benefit_levers/payable/oasi_only.yaml | 7 + .../ssa/benefit_levers/payable/share.yaml | 7 + .../gov/ssa/cola_history/effective_month.yaml | 15 ++ .../ssa/cola_history/first_payment_month.yaml | 15 ++ .../gov/ssa/cola_history/pia_rounding.yaml | 21 +++ .../parameters/gov/ssa/cola_history/rate.yaml | 70 +++++++++ .../cola/effective_month_number.yaml | 10 -- .../cola/first_payment_month_number.yaml | 10 -- .../cola/first_payment_year_offset.yaml | 10 -- .../cola/historical_last_effective_year.yaml | 9 -- .../cola/pia_rounding_direction.yaml | 10 -- .../cola/pia_rounding_increment.yaml | 9 -- .../gov/ssa/social_security/cola/rate.yaml | 62 -------- .../unit/test_ss_calculator_parameters.py | 146 ++++++++++++++++++ .../tests/unit/test_ss_cola_schedule.py | 20 +++ policyengine_us/tools/social_security/cola.py | 61 +++++--- .../tools/social_security/parameters.py | 106 +++++++++++++ 26 files changed, 513 insertions(+), 138 deletions(-) create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/across_the_board/rate.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/across_the_board/start_year.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/alternative_rate.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/effective_month.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/effective_year.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/end_year.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/pp_change.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/start_year.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/withholding_enabled.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/payable/oasi_only.yaml create mode 100644 policyengine_us/parameters/gov/contrib/ssa/benefit_levers/payable/share.yaml create mode 100644 policyengine_us/parameters/gov/ssa/cola_history/effective_month.yaml create mode 100644 policyengine_us/parameters/gov/ssa/cola_history/first_payment_month.yaml create mode 100644 policyengine_us/parameters/gov/ssa/cola_history/pia_rounding.yaml create mode 100644 policyengine_us/parameters/gov/ssa/cola_history/rate.yaml delete mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/effective_month_number.yaml delete mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_month_number.yaml delete mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_year_offset.yaml delete mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/historical_last_effective_year.yaml delete mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_direction.yaml delete mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_increment.yaml delete mode 100644 policyengine_us/parameters/gov/ssa/social_security/cola/rate.yaml create mode 100644 policyengine_us/tests/unit/test_ss_calculator_parameters.py create mode 100644 policyengine_us/tools/social_security/parameters.py diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/across_the_board/rate.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/across_the_board/rate.yaml new file mode 100644 index 00000000000..b70a3bd4b04 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/across_the_board/rate.yaml @@ -0,0 +1,7 @@ +description: "Proportional across-the-board benefit change, at least -1." +values: + 0000-01-01: 0 +metadata: + unit: /1 + label: Social Security across the board rate + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/across_the_board/start_year.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/across_the_board/start_year.yaml new file mode 100644 index 00000000000..7a098179d2d --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/across_the_board/start_year.yaml @@ -0,0 +1,7 @@ +description: "First payment year of the across-the-board change." +values: + 0000-01-01: 9999 +metadata: + unit: year + label: Social Security across the board start year + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/alternative_rate.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/alternative_rate.yaml new file mode 100644 index 00000000000..29a263f39c8 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/alternative_rate.yaml @@ -0,0 +1,7 @@ +description: "Optional externally pinned annual alternative COLA rate before pp_change, or -1 to use the baseline statutory rate." +values: + 0000-01-01: -1 +metadata: + unit: /1 + label: Social Security cola alternative rate + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/effective_month.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/effective_month.yaml new file mode 100644 index 00000000000..dafde46fbb8 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/effective_month.yaml @@ -0,0 +1,7 @@ +description: "First affected COLA effective month when effective_year is supplied." +values: + 0000-01-01: 12 +metadata: + unit: month + label: Social Security cola effective month + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/effective_year.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/effective_year.yaml new file mode 100644 index 00000000000..b61974d9d2a --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/effective_year.yaml @@ -0,0 +1,7 @@ +description: "First affected COLA effective calendar year, or zero to use start_year." +values: + 0000-01-01: 0 +metadata: + unit: year + label: Social Security cola effective year + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/end_year.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/end_year.yaml new file mode 100644 index 00000000000..f1f86f725db --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/end_year.yaml @@ -0,0 +1,7 @@ +description: "Last affected payment calendar year, or zero for no end." +values: + 0000-01-01: 0 +metadata: + unit: year + label: Social Security cola end year + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/pp_change.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/pp_change.yaml new file mode 100644 index 00000000000..f3b94f89f2e --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/pp_change.yaml @@ -0,0 +1,7 @@ +description: "Annual COLA proportional-rate addition; examples: CPI-E +0.15 percentage points = 0.0015, chained CPI -0.30 percentage points = -0.0030. Preserve this precision after statutory rounding." +values: + 0000-01-01: 0 +metadata: + unit: /1 + label: Social Security cola pp change + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/start_year.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/start_year.yaml new file mode 100644 index 00000000000..ae728d81e44 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/start_year.yaml @@ -0,0 +1,7 @@ +description: "First affected January payment year. Used unless effective_year is supplied." +values: + 0000-01-01: 9999 +metadata: + unit: year + label: Social Security cola start year + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/withholding_enabled.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/withholding_enabled.yaml new file mode 100644 index 00000000000..dd9e94d981e --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/cola/withholding_enabled.yaml @@ -0,0 +1,7 @@ +description: "Enable the component payment-year withholding terms; subsequent means-test rules supply the decisions." +values: + 0000-01-01: false +metadata: + unit: bool + label: Social Security cola withholding enabled + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/payable/oasi_only.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/payable/oasi_only.yaml new file mode 100644 index 00000000000..95fb0d2386c --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/payable/oasi_only.yaml @@ -0,0 +1,7 @@ +description: "Apply the supplied payable share only to OASI components rather than combined OASDI." +values: + 0000-01-01: false +metadata: + unit: bool + label: Social Security payable oasi only + economy: false diff --git a/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/payable/share.yaml b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/payable/share.yaml new file mode 100644 index 00000000000..921b00d37e9 --- /dev/null +++ b/policyengine_us/parameters/gov/contrib/ssa/benefit_levers/payable/share.yaml @@ -0,0 +1,7 @@ +description: "Supplied annual payable share in [0, 1]. The supplier blends any partial depletion year." +values: + 0000-01-01: 1 +metadata: + unit: /1 + label: Social Security payable share + economy: false diff --git a/policyengine_us/parameters/gov/ssa/cola_history/effective_month.yaml b/policyengine_us/parameters/gov/ssa/cola_history/effective_month.yaml new file mode 100644 index 00000000000..b41cf18dc3b --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/cola_history/effective_month.yaml @@ -0,0 +1,15 @@ +description: Social Security applies a historical annual COLA in this calendar month of its effective year. +values: + 1975-06-01: 6 + 1983-12-01: 12 +metadata: + unit: int + label: Social Security historical COLA effective month + economy: false + reference: + - title: Social Security Cost-Of-Living Adjustments + href: https://www.ssa.gov/OACT/COLA/colaseries.html +documentation: | + Read this month at an event date in cola_history.rate. June-effective + events apply in 1975-1982, and December-effective events apply from 1983. + No COLA occurred in December 1982 or June 1983. diff --git a/policyengine_us/parameters/gov/ssa/cola_history/first_payment_month.yaml b/policyengine_us/parameters/gov/ssa/cola_history/first_payment_month.yaml new file mode 100644 index 00000000000..605255718b5 --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/cola_history/first_payment_month.yaml @@ -0,0 +1,15 @@ +description: Social Security first pays a historical annual COLA in this calendar month. +values: + 1975-06-01: 7 + 1983-12-01: 1 +metadata: + unit: int + label: Social Security historical COLA first payment month + economy: false + reference: + - title: Social Security COLA information, history of automatic adjustments + href: https://www.ssa.gov/news/en/cola/ +documentation: | + Read this month at an event date in cola_history.rate. For a June-effective + event, the first payment is in July of the same year. For a December-effective + event, the first payment is in January of the next year. diff --git a/policyengine_us/parameters/gov/ssa/cola_history/pia_rounding.yaml b/policyengine_us/parameters/gov/ssa/cola_history/pia_rounding.yaml new file mode 100644 index 00000000000..447daa26acf --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/cola_history/pia_rounding.yaml @@ -0,0 +1,21 @@ +description: Social Security applies this historical rounding rule to the PIA after a COLA. +values: + 1975-06-01: 1 + 1982-06-01: 2 +metadata: + unit: int + label: Social Security historical COLA PIA rounding rule + economy: false + reference: + - title: POMS RS 00601.020 A, rounding of benefits + href: https://secure.ssa.gov/poms.nsf/lnx/0300601020 + - title: POMS RS 00605.021 C, computation example with historical COLAs + href: https://secure.ssa.gov/poms.nsf/lnx/0300605021 +documentation: | + Code 1 means round up to the next dime if not already a multiple of a dime. + Code 2 means truncate to the next lower dime. The June 1982 COLA uses code 2, + even where the initial PIA for a pre-1983 benchmark year rounded upward. + These codes describe COLA PIA rounding, not initial-PIA benchmark rounding. + A computation must reject any history containing a code it does not implement. + Reported-source proportional factors approximate changes in annual survey + amounts and do not reconstruct unidentified monthly benefit rounding. diff --git a/policyengine_us/parameters/gov/ssa/cola_history/rate.yaml b/policyengine_us/parameters/gov/ssa/cola_history/rate.yaml new file mode 100644 index 00000000000..9e26b7c528b --- /dev/null +++ b/policyengine_us/parameters/gov/ssa/cola_history/rate.yaml @@ -0,0 +1,70 @@ +description: Social Security applies these historical statutory cost-of-living adjustment rates, dated by their effective benefit month. +values: + 1975-06-01: 0.080 + 1976-06-01: 0.064 + 1977-06-01: 0.059 + 1978-06-01: 0.065 + 1979-06-01: 0.099 + 1980-06-01: 0.143 + 1981-06-01: 0.112 + 1982-06-01: 0.074 + 1983-12-01: 0.035 + 1984-12-01: 0.035 + 1985-12-01: 0.031 + 1986-12-01: 0.013 + 1987-12-01: 0.042 + 1988-12-01: 0.040 + 1989-12-01: 0.047 + 1990-12-01: 0.054 + 1991-12-01: 0.037 + 1992-12-01: 0.030 + 1993-12-01: 0.026 + 1994-12-01: 0.028 + 1995-12-01: 0.026 + 1996-12-01: 0.029 + 1997-12-01: 0.021 + 1998-12-01: 0.013 + 1999-12-01: 0.025 # Corrected from 0.024 by Public Law 106-554. + 2000-12-01: 0.035 + 2001-12-01: 0.026 + 2002-12-01: 0.014 + 2003-12-01: 0.021 + 2004-12-01: 0.027 + 2005-12-01: 0.041 + 2006-12-01: 0.033 + 2007-12-01: 0.023 + 2008-12-01: 0.058 + 2009-12-01: 0.000 + 2010-12-01: 0.000 + 2011-12-01: 0.036 + 2012-12-01: 0.017 + 2013-12-01: 0.015 + 2014-12-01: 0.017 + 2015-12-01: 0.000 + 2016-12-01: 0.003 + 2017-12-01: 0.020 + 2018-12-01: 0.028 + 2019-12-01: 0.016 + 2020-12-01: 0.013 + 2021-12-01: 0.059 + 2022-12-01: 0.087 + 2023-12-01: 0.032 + 2024-12-01: 0.025 + 2025-12-01: 0.028 +metadata: + unit: /1 + label: Social Security historical statutory COLA rate + economy: false + historical_start: 1975-06-01 + historical_end: 2025-12-01 + reference: + - title: Social Security Cost-Of-Living Adjustments + href: https://www.ssa.gov/OACT/COLA/colaseries.html +documentation: | + Dates are effective benefit months, not payment months. The June 1975-1982 + adjustments were first paid in July of the same year; adjustments from + December 1983 were first paid the following January. There was no December + 1982 or June 1983 adjustment. Explicit zero entries retain the 2009, 2010, + and 2015 determinations. December 1999 includes the statutory correction to + 2.5 percent. This audited series ends with December 2025, first paid January + 2026; later payment-year rates use the existing gov.ssa.uprating schedule. diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/effective_month_number.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/effective_month_number.yaml deleted file mode 100644 index 20052d37858..00000000000 --- a/policyengine_us/parameters/gov/ssa/social_security/cola/effective_month_number.yaml +++ /dev/null @@ -1,10 +0,0 @@ -description: Month in which a statutory Social Security COLA changes entitlement. -values: - 1975-06-01: 6 - 1983-12-01: 12 -metadata: - unit: year - label: Effective month of Social Security COLA - reference: - - title: SSA COLA history, timing, and computation - href: https://www.ssa.gov/OACT/COLA/colaseries.html diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_month_number.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_month_number.yaml deleted file mode 100644 index 7b2b8c2be34..00000000000 --- a/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_month_number.yaml +++ /dev/null @@ -1,10 +0,0 @@ -description: Month of the first ordinary Social Security check reflecting the effective COLA. -values: - 1975-06-01: 7 - 1983-12-01: 1 -metadata: - unit: year - label: First check month for Social Security COLA - reference: - - title: SSA COLA history, timing, and computation - href: https://www.ssa.gov/OACT/COLA/latestCOLA.html diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_year_offset.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_year_offset.yaml deleted file mode 100644 index 556c1f7f401..00000000000 --- a/policyengine_us/parameters/gov/ssa/social_security/cola/first_payment_year_offset.yaml +++ /dev/null @@ -1,10 +0,0 @@ -description: Calendar-year offset between a Social Security COLA's effective and first ordinary check months. -values: - 1975-06-01: 0 - 1983-12-01: 1 -metadata: - unit: year - label: First check year offset for Social Security COLA - reference: - - title: SSA COLA history, timing, and computation - href: https://www.ssa.gov/OACT/COLA/latestCOLA.html diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/historical_last_effective_year.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/historical_last_effective_year.yaml deleted file mode 100644 index 5e47aeda4eb..00000000000 --- a/policyengine_us/parameters/gov/ssa/social_security/cola/historical_last_effective_year.yaml +++ /dev/null @@ -1,9 +0,0 @@ -description: Last effective COLA year with an audited historical rate; later rates use the runtime January-keyed Q3 SSA schedule. -values: - 1975-06-01: 2026 -metadata: - unit: year - label: Last historical Social Security COLA year - reference: - - title: SSA COLA history, timing, and computation - href: https://www.ssa.gov/OACT/COLA/colaseries.html diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_direction.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_direction.yaml deleted file mode 100644 index 1e40f1a00c5..00000000000 --- a/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_direction.yaml +++ /dev/null @@ -1,10 +0,0 @@ -description: "Direction of PIA rounding after each COLA: 1 rounds up and -1 rounds down. The household service rejects unsupported historical rounding." -values: - 1975-06-01: 1 - 1982-06-01: -1 -metadata: - unit: year - label: Social Security COLA PIA rounding direction - reference: - - title: SSA COLA history, timing, and computation - href: https://secure.ssa.gov/poms.nsf/lnx/0300601020 diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_increment.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_increment.yaml deleted file mode 100644 index 034d0035834..00000000000 --- a/policyengine_us/parameters/gov/ssa/social_security/cola/pia_rounding_increment.yaml +++ /dev/null @@ -1,9 +0,0 @@ -description: Dollar increment used to round PIA after each Social Security COLA. -values: - 1975-06-01: 0.1 -metadata: - unit: currency-USD - label: Social Security COLA PIA rounding increment - reference: - - title: SSA COLA history, timing, and computation - href: https://secure.ssa.gov/poms.nsf/lnx/0300601020 diff --git a/policyengine_us/parameters/gov/ssa/social_security/cola/rate.yaml b/policyengine_us/parameters/gov/ssa/social_security/cola/rate.yaml deleted file mode 100644 index 753bdf4522b..00000000000 --- a/policyengine_us/parameters/gov/ssa/social_security/cola/rate.yaml +++ /dev/null @@ -1,62 +0,0 @@ -description: Statutory Social Security COLA rates by effective month; December 1999 uses the corrected rate, with its original rate and correction timing recorded separately. -values: - 1975-06-01: 0.080 # First check 1975-07 - 1976-06-01: 0.064 # First check 1976-07 - 1977-06-01: 0.059 # First check 1977-07 - 1978-06-01: 0.065 # First check 1978-07 - 1979-06-01: 0.099 # First check 1979-07 - 1980-06-01: 0.143 # First check 1980-07 - 1981-06-01: 0.112 # First check 1981-07 - 1982-06-01: 0.074 # First check 1982-07 - 1983-12-01: 0.035 # First check 1984-01 - 1984-12-01: 0.035 # First check 1985-01 - 1985-12-01: 0.031 # First check 1986-01 - 1986-12-01: 0.013 # First check 1987-01 - 1987-12-01: 0.042 # First check 1988-01 - 1988-12-01: 0.040 # First check 1989-01 - 1989-12-01: 0.047 # First check 1990-01 - 1990-12-01: 0.054 # First check 1991-01 - 1991-12-01: 0.037 # First check 1992-01 - 1992-12-01: 0.030 # First check 1993-01 - 1993-12-01: 0.026 # First check 1994-01 - 1994-12-01: 0.028 # First check 1995-01 - 1995-12-01: 0.026 # First check 1996-01 - 1996-12-01: 0.029 # First check 1997-01 - 1997-12-01: 0.021 # First check 1998-01 - 1998-12-01: 0.013 # First check 1999-01 - 1999-12-01: 0.025 # First check 2000-01 - 2000-12-01: 0.035 # First check 2001-01 - 2001-12-01: 0.026 # First check 2002-01 - 2002-12-01: 0.014 # First check 2003-01 - 2003-12-01: 0.021 # First check 2004-01 - 2004-12-01: 0.027 # First check 2005-01 - 2005-12-01: 0.041 # First check 2006-01 - 2006-12-01: 0.033 # First check 2007-01 - 2007-12-01: 0.023 # First check 2008-01 - 2008-12-01: 0.058 # First check 2009-01 - 2009-12-01: 0.000 # First check 2010-01 - 2010-12-01: 0.000 # First check 2011-01 - 2011-12-01: 0.036 # First check 2012-01 - 2012-12-01: 0.017 # First check 2013-01 - 2013-12-01: 0.015 # First check 2014-01 - 2014-12-01: 0.017 # First check 2015-01 - 2015-12-01: 0.000 # First check 2016-01 - 2016-12-01: 0.003 # First check 2017-01 - 2017-12-01: 0.020 # First check 2018-01 - 2018-12-01: 0.028 # First check 2019-01 - 2019-12-01: 0.016 # First check 2020-01 - 2020-12-01: 0.013 # First check 2021-01 - 2021-12-01: 0.059 # First check 2022-01 - 2022-12-01: 0.087 # First check 2023-01 - 2023-12-01: 0.032 # First check 2024-01 - 2024-12-01: 0.025 # First check 2025-01 - 2025-12-01: 0.028 # First check 2026-01 - 2026-12-01: 0.036 # First check 2027-01 -metadata: - unit: /1 - label: Statutory Social Security COLA rate - reference: - - title: SSA Cost-Of-Living Adjustments, including corrected December 1999 rate - href: https://www.ssa.gov/OACT/COLA/colaseries.html - - title: POMS RS 00601.120, Cost-Of-Living Adjustment - href: https://secure.ssa.gov/poms.nsf/lnx/0300601120 diff --git a/policyengine_us/tests/unit/test_ss_calculator_parameters.py b/policyengine_us/tests/unit/test_ss_calculator_parameters.py new file mode 100644 index 00000000000..f6e36b564bd --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_calculator_parameters.py @@ -0,0 +1,146 @@ +"""Runtime parameter selection for the opt-in eligibility-year PIA service.""" + +from decimal import Decimal + +import pytest + +from policyengine_us import Simulation +from policyengine_us.tools.social_security.parameters import ( + bend_points_at, + formula_path_at, +) +from policyengine_us.tools.social_security.pia import compute_pia, progressive_threshold + + +@pytest.fixture(scope="module") +def reference_parameters(): + return Simulation.default_tax_benefit_system_instance.parameters + + +@pytest.fixture +def parameters(reference_parameters): + # Reuse the one read-only runtime system; only reform cases copy its tree. + return reference_parameters.clone() + + +def _set(parameter, value, start="2026-01-01"): + parameter.update(start=start, value=value) + + +def _calculate(parameters, aime, eligibility_year, payment_year): + path, mode = formula_path_at(parameters, eligibility_year, payment_year) + return compute_pia( + aime, + eligibility_year, + path, + payment_year, + mode, + bend_points=bend_points_at(parameters, eligibility_year), + ) + + +def test_runtime_parameters_are_neutral_by_default(reference_parameters): + parameters = reference_parameters + path, mode = formula_path_at(parameters, 2020, 2026) + assert mode == "cohort" + assert path.s770 is False + assert path.factor_values is None + assert path.bend_point_multipliers == (1, 1) + assert _calculate(parameters, 5000, 2020, 2026) == Decimal("2156.8") + + +def test_historical_1983_bends_are_distinct_from_modern_scale(reference_parameters): + parameters = reference_parameters + assert bend_points_at(parameters, 1983) == (254, 1528) + assert _calculate(parameters, 1001, 1983, 2026) == Decimal("467.6") + with pytest.raises(ValueError, match="before 1983"): + bend_points_at(parameters, 1982) + + +def test_future_2059_bends_use_existing_uprated_scale(reference_parameters): + parameters = reference_parameters + bends = bend_points_at(parameters, 2059) + scale = parameters("2059-01-01").gov.ssa.social_security.pia.formula_factors + assert bends == tuple(scale.thresholds[1:3]) + assert bends[0] > bend_points_at(parameters, 2026)[0] + assert 0 < bends[0] < bends[1] + + +def test_custom_factor_schedule_is_selected_by_eligibility(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True) + _set(p.factors.third, 0.05, "2027-01-01") + _set(p.factors.start_year, 2027) + path_2026, mode = formula_path_at(parameters, 2026, 2030) + path_2027, _ = formula_path_at(parameters, 2027, 2030) + assert mode == "cohort" + assert path_2026.factor_values is None + assert path_2027.factor_values == (0.9, 0.32, 0.05) + assert _calculate(parameters, 10000, 2026, 2030) == compute_pia( + 10000, 2026, bend_points=bend_points_at(parameters, 2026) + ) + + +def test_explicit_custom_recompute_uses_payment_formula_and_initial_bends(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True) + _set(p.recompute_existing, True) + _set(p.factors.third, 0.05, "2027-01-01") + _set(p.factors.start_year, 2027) + path, mode = formula_path_at(parameters, 2020, 2027) + assert mode == "retroactive" + assert path.factor_values == (0.9, 0.32, 0.05) + assert _calculate(parameters, 7000, 2020, 2027) == Decimal("2468.7") + + +def test_s770_recomputes_without_extending_custom_cohort_reform(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True) + _set(p.effective_year, 2026) + _set(p.bend_point_multipliers.second, 1.1) + _set(parameters.gov.contrib.congress.s770.section_2.in_effect, True) + path, mode = formula_path_at(parameters, 2020, 2026) + assert mode == "retroactive" + assert path.s770 is True + assert path.bend_point_multipliers == (1, 1) + assert _calculate(parameters, 5000, 2020, 2026) == Decimal("2313.6") + + +def test_progressive_enable_with_unset_fraction_fails_on_runtime_adapter(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True) + _set(p.progressive_price_indexing.in_effect, True) + with pytest.raises(ValueError, match="bend-point fraction"): + _calculate(parameters, 5000, 2032, 2032) + + +def test_runtime_progressive_dollar_path_overrides_fraction(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True) + progressive = p.progressive_price_indexing + _set(progressive.in_effect, True) + _set(progressive.bend_point_fraction, 0.4) + _set(progressive.threshold, 3500) + path, _ = formula_path_at(parameters, 2032, 2032) + assert ( + progressive_threshold(2032, path, bend_points=bend_points_at(parameters, 2032)) + == 3500 + ) + + +def test_full_indexing_rejects_missing_frozen_runtime_scale(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True) + _set(p.full_price_indexing.in_effect, True) + with pytest.raises(ValueError, match="real-wage scale"): + _calculate(parameters, 5000, 2032, 2032) + + +def test_frozen_full_indexing_scale_is_read_at_eligibility_not_payment(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True) + _set(p.full_price_indexing.in_effect, True) + _set(p.full_price_indexing.real_wage_scale, 1, "2032-01-01") + _set(p.full_price_indexing.real_wage_scale, 0.9, "2033-01-01") + path, _ = formula_path_at(parameters, 2032, 2035) + assert path.real_wage_scale_by_year == {2032: 1} diff --git a/policyengine_us/tests/unit/test_ss_cola_schedule.py b/policyengine_us/tests/unit/test_ss_cola_schedule.py index ac02d44ca27..7086c8b35b4 100644 --- a/policyengine_us/tests/unit/test_ss_cola_schedule.py +++ b/policyengine_us/tests/unit/test_ss_cola_schedule.py @@ -114,6 +114,13 @@ def test_projection_rejects_missing_or_invalid_q3_path(): def test_audited_history_timing_corrected_1999_and_future_horizon(parameters): # https://www.ssa.gov/OACT/COLA/colaseries.html + canonical = parameters("2025-12-01").gov.ssa.cola_history + assert D(str(canonical.rate)) == D(".028") + assert canonical.effective_month == 12 + assert canonical.first_payment_month == 1 + assert canonical.pia_rounding == 2 + assert parameters("1981-06-01").gov.ssa.cola_history.pia_rounding == 1 + assert parameters("1982-06-01").gov.ssa.cola_history.pia_rounding == 2 events = read_parameter_events(parameters, 2059) by_effective = {event.effective_month: event for event in events} assert by_effective["1975-06"].payment_month == "1975-07" @@ -126,6 +133,19 @@ def test_audited_history_timing_corrected_1999_and_future_horizon(parameters): assert apply_colas("1000", 2057, "2059-01", events) >= D("1000") +def test_canonical_history_stops_before_projected_2027_check(parameters): + # Canonical authored history ends December2025. January2027 uses runtime + # Q3 levels317.265 and328.746, giving a statutory rounded rate3.6%. + assert ( + str(parameters.gov.ssa.cola_history.rate.metadata["historical_end"]) + == "2025-12-01" + ) + events = read_parameter_events(parameters, 2027) + projected = next(event for event in events if event.payment_month == "2027-01") + assert projected.effective_month == "2026-12" + assert projected.rate == D(".036") + + def test_projection_explicitly_rejects_after_runtime_frozen_horizon(parameters): with pytest.raises(ValueError, match="frozen Q3 horizon 2100"): read_parameter_events(parameters, 2101) diff --git a/policyengine_us/tools/social_security/cola.py b/policyengine_us/tools/social_security/cola.py index 1e95763e825..ee14e7b3b79 100644 --- a/policyengine_us/tools/social_security/cola.py +++ b/policyengine_us/tools/social_security/cola.py @@ -216,27 +216,50 @@ def read_parameter_events(parameters, through_year: int) -> tuple[ColaEvent, ... if through_year < 1983: raise ValueError("COLA calculations require a benchmark year of 1983 or later") try: - history = parameters("2026-01-01").gov.ssa.social_security.cola - last_year = int(history.historical_last_effective_year) + # Reuse the canonical statutory history supplied by the benefit-lever + # route. Its authored event dates preserve irregular historical timing. + raw_history = parameters.gov.ssa.cola_history.rate + history_start = str(raw_history.metadata["historical_start"]) + history_end = str(raw_history.metadata["historical_end"]) + observations = sorted( + ( + observation + for observation in raw_history.values_list + if observation.value is not None + and history_start <= observation.instant_str <= history_end + ), + key=lambda observation: observation.instant_str, + ) + if not observations: + raise ValueError("The statutory SSA COLA history has no dated events") + last_year = int(history_end[:4]) result = [] - for year in range(1975, min(last_year, through_year) + 1): - # The effective month changed once, in 1983. Read both dates from - # parameters so an event never silently receives a January date. - node = parameters(f"{year}-12-01").gov.ssa.social_security.cola - effective = f"{year}-{int(node.effective_month_number):02d}" - payment = f"{year + int(node.first_payment_year_offset)}-{int(node.first_payment_month_number):02d}" + for observation in observations: + year = int(observation.instant_str[:4]) + if year > through_year: + continue + node = parameters(observation.instant_str).gov.ssa.cola_history + effective_number = int(node.effective_month) + payment_number = int(node.first_payment_month) + effective = f"{year}-{effective_number:02d}" + if observation.instant_str[:7] != effective: + raise ValueError("Statutory COLA date and effective month disagree") + payment_year = year + int(payment_number <= effective_number) + payment = f"{payment_year}-{payment_number:02d}" rule = ( "dime_floor" - if int(node.pia_rounding_direction) == -1 - and _decimal(node.pia_rounding_increment) == DIME + if int(node.pia_rounding) == 2 else "unsupported_historical_rounding" ) kwargs = {} if year == 1999: + correction = parameters( + observation.instant_str + ).gov.ssa.social_security.cola kwargs = { - "as_paid_rate": _decimal(node.december_1999_as_paid_rate), + "as_paid_rate": _decimal(correction.december_1999_as_paid_rate), "correction_payment_month": str( - int(node.december_1999_correction_payment_month) + int(correction.december_1999_correction_payment_month) ), } kwargs["correction_payment_month"] = ( @@ -265,12 +288,14 @@ def read_parameter_events(parameters, through_year: int) -> tuple[ColaEvent, ... ) # Find the most recent nonzero historical COLA for the high-water # anchor. A zero-COLA year must not reset that comparison basis. - anchor_year = last_year - while ( - parameters(f"{anchor_year}-12-01").gov.ssa.social_security.cola.rate - == 0 - ): - anchor_year -= 1 + positive_history = [ + observation + for observation in observations + if _decimal(observation.value) > 0 + ] + if not positive_history: + raise ValueError("The statutory COLA history has no positive anchor") + anchor_year = int(positive_history[-1].instant_str[:4]) missing_years = set(range(anchor_year + 1, through_year + 1)) - q3_years if missing_years: raise ValueError( diff --git a/policyengine_us/tools/social_security/parameters.py b/policyengine_us/tools/social_security/parameters.py new file mode 100644 index 00000000000..425aa9c4c62 --- /dev/null +++ b/policyengine_us/tools/social_security/parameters.py @@ -0,0 +1,106 @@ +"""Read eligibility-cohort parameters for the opt-in monthly PIA service.""" + +from policyengine_core.errors import ParameterNotFoundError + +from .pia import FormulaPath + + +def _year(value): + if isinstance(value, bool) or int(value) != value or value < 1983: + raise ValueError( + "PIA benchmark years before 1983 or noninteger years are unsupported" + ) + return int(value) + + +def _optional(node, name): + # Core omits a null parameter from ParameterNodeAtInstant._children and + # raises ParameterNotFoundError on access. An unset fraction/threshold must + # stay unset rather than becoming an implicit zero or population estimate. + try: + return getattr(node, name) + except ParameterNotFoundError: + return None + + +def _snapshot(parameters, year): + return parameters(f"{year}-01-01") + + +def bend_points_at(parameters, eligibility_year): + """Select initial-eligibility bends, with historical values before 2015. + + The separate historical table avoids changing the ordinary model's legacy + scale. Future years use that scale's existing wage-indexed projections. + """ + year = _year(eligibility_year) + pia = _snapshot(parameters, year).gov.ssa.social_security.pia + if year <= 2026: + return (pia.bend_points.first, pia.bend_points.second) + return tuple(pia.formula_factors.thresholds[1:3]) + + +def formula_path_at(parameters, eligibility_year, payment_year): + """Return ``(FormulaPath, recompute_mode)`` for one worker and payment year. + + Cohort-only custom factors and bend multipliers read their dated values at + eligibility. An explicit custom recompute reads the payment-year formula + while keeping that worker's initial-eligibility bends. Frozen indexing + scales, thresholds, maximum-career AIMEs and targets always read at the + eligibility year. Any missing frozen data fail in the shared PIA service. + + S.770 has its own switch and mandatory older-beneficiary recomputation. + Custom gates are resolved here so enabling S.770 cannot accidentally extend + a separately configured cohort-only custom reform to older beneficiaries. + """ + year = _year(eligibility_year) + payment = _year(payment_year) + if payment < year: + raise ValueError("payment year cannot precede eligibility year") + current = _snapshot(parameters, payment) + enabled = current.gov.contrib.ssa.pia.in_effect + custom_recompute = bool(enabled and current.gov.contrib.ssa.pia.recompute_existing) + selection_year = payment if custom_recompute else year + settings = _snapshot(parameters, selection_year).gov.contrib.ssa.pia + cohort = _snapshot(parameters, year).gov.contrib.ssa.pia + s770 = bool( + current.gov.contrib.congress.s770.section_2.in_effect and payment >= 2026 + ) + + values = {"s770": s770} + if enabled: + if selection_year >= settings.effective_year: + values["bend_point_multipliers"] = ( + settings.bend_point_multipliers.first, + settings.bend_point_multipliers.second, + ) + if selection_year >= settings.factors.start_year: + values["factor_values"] = ( + settings.factors.first, + settings.factors.second, + settings.factors.third, + ) + + full = settings.full_price_indexing + if full.in_effect and selection_year >= full.start_year: + scale = _optional(cohort.full_price_indexing, "real_wage_scale") + values["full_price_indexing_start_year"] = int(full.start_year) + values["real_wage_scale_by_year"] = None if scale is None else {year: scale} + + progressive = settings.progressive_price_indexing + if progressive.in_effect and selection_year >= progressive.start_year: + frozen = cohort.progressive_price_indexing + values["progressive_price_indexing_start_year"] = int( + progressive.start_year + ) + values["bend_point_fraction"] = _optional(frozen, "bend_point_fraction") + for parameter_name, field in ( + ("threshold", "threshold_by_year"), + ("maximum_aime", "maximum_aime_by_year"), + ("maximum_pia_target", "maximum_pia_target_by_year"), + ): + value = _optional(frozen, parameter_name) + values[field] = None if value is None else {year: value} + + mode = "retroactive" if custom_recompute or s770 else "cohort" + return FormulaPath(**values), mode From 76a7c5b76eed0361c1286f8b41094e8602aac315 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 03:43:40 -0400 Subject: [PATCH 05/16] Preserve exact PIA thresholds and require complete frozen cohort paths --- .../unit/test_ss_calculator_parameters.py | 142 +++++++++++++++++- .../tests/unit/test_ss_pia_service.py | 33 ++++ policyengine_us/tools/social_security/cola.py | 16 +- .../tools/social_security/parameters.py | 64 +++++--- policyengine_us/tools/social_security/pia.py | 127 +++++++++++----- 5 files changed, 318 insertions(+), 64 deletions(-) diff --git a/policyengine_us/tests/unit/test_ss_calculator_parameters.py b/policyengine_us/tests/unit/test_ss_calculator_parameters.py index f6e36b564bd..7a01fecf8b1 100644 --- a/policyengine_us/tests/unit/test_ss_calculator_parameters.py +++ b/policyengine_us/tests/unit/test_ss_calculator_parameters.py @@ -3,6 +3,7 @@ from decimal import Decimal import pytest +from policyengine_core.parameters import ParameterNode from policyengine_us import Simulation from policyengine_us.tools.social_security.parameters import ( @@ -17,10 +18,41 @@ def reference_parameters(): return Simulation.default_tax_benefit_system_instance.parameters +@pytest.fixture(scope="module") +def calculator_parameters(reference_parameters): + """Keep actual processed Core parameters without cloning unrelated policy. + + These subtrees include historical bend points, projected future scales, + null optional values and dated reform settings. New ancestor nodes keep + the adapter's production paths intact while avoiding a whole-US tree copy + and whole-US instant snapshots for each isolated parameter reform. + """ + root = ParameterNode() + for path in ( + "gov.ssa.social_security.pia", + "gov.contrib.ssa.pia", + "gov.contrib.congress.s770", + ): + parts = path.split(".") + source = reference_parameters + destination = root + for index, part in enumerate(parts): + source = getattr(source, part) + if index == len(parts) - 1: + destination.add_child(part, source.clone()) + else: + if part not in destination.children: + destination.add_child( + part, ParameterNode(name=".".join(parts[: index + 1])) + ) + destination = destination.children[part] + return root + + @pytest.fixture -def parameters(reference_parameters): - # Reuse the one read-only runtime system; only reform cases copy its tree. - return reference_parameters.clone() +def parameters(calculator_parameters): + # Each mutable case receives its own small Core tree and empty caches. + return calculator_parameters.clone() def _set(parameter, value, start="2026-01-01"): @@ -60,7 +92,7 @@ def test_historical_1983_bends_are_distinct_from_modern_scale(reference_paramete def test_future_2059_bends_use_existing_uprated_scale(reference_parameters): parameters = reference_parameters bends = bend_points_at(parameters, 2059) - scale = parameters("2059-01-01").gov.ssa.social_security.pia.formula_factors + scale = parameters.gov.ssa.social_security.pia("2059-01-01").formula_factors assert bends == tuple(scale.thresholds[1:3]) assert bends[0] > bend_points_at(parameters, 2026)[0] assert 0 < bends[0] < bends[1] @@ -81,6 +113,31 @@ def test_custom_factor_schedule_is_selected_by_eligibility(parameters): ) +def test_cohort_master_start_does_not_reach_older_cohort_without_recompute(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.factors.first, 0.95, "1983-01-01") + _set(p.in_effect, True, "2026-01-01") + path, mode = formula_path_at(parameters, 2020, 2035) + assert mode == "cohort" + assert path.factor_values is None + assert _calculate(parameters, 5000, 2020, 2035) == Decimal("2156.8") + + +def test_cohort_master_later_off_preserves_previously_eligible_cohort_path(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True, "2026-01-01") + _set(p.in_effect, False, "2030-01-01") + _set(p.factors.first, 0.95, "2026-01-01") + initial, initial_mode = formula_path_at(parameters, 2027, 2027) + later, later_mode = formula_path_at(parameters, 2027, 2035) + assert later_mode == initial_mode == "cohort" + assert later == initial + assert later.factor_values == (0.95, 0.32, 0.15) + assert _calculate(parameters, 5000, 2027, 2035) == _calculate( + parameters, 5000, 2027, 2027 + ) + + def test_explicit_custom_recompute_uses_payment_formula_and_initial_bends(parameters): p = parameters.gov.contrib.ssa.pia _set(p.in_effect, True) @@ -120,7 +177,7 @@ def test_runtime_progressive_dollar_path_overrides_fraction(parameters): progressive = p.progressive_price_indexing _set(progressive.in_effect, True) _set(progressive.bend_point_fraction, 0.4) - _set(progressive.threshold, 3500) + _set(progressive.threshold, 3500, "2032-01-01") path, _ = formula_path_at(parameters, 2032, 2032) assert ( progressive_threshold(2032, path, bend_points=bend_points_at(parameters, 2032)) @@ -128,6 +185,24 @@ def test_runtime_progressive_dollar_path_overrides_fraction(parameters): ) +def test_progressive_recompute_uses_selected_fraction_and_original_bends(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True, "2032-01-01") + _set(p.recompute_existing, True, "2032-01-01") + progressive = p.progressive_price_indexing + _set(progressive.in_effect, True, "2032-01-01") + _set(progressive.bend_point_fraction, 0.4, "2032-01-01") + # Frozen benchmark inputs explicitly describe the older eligibility cohort. + _set(progressive.maximum_aime, 10000, "2020-01-01") + _set(progressive.maximum_pia_target, 2800, "2020-01-01") + path, mode = formula_path_at(parameters, 2020, 2032) + assert mode == "retroactive" + assert path.bend_point_fraction == 0.4 + assert path.maximum_aime_by_year == {2020: 10000} + assert progressive_threshold(2020, path, bend_points=(960, 5785)) == 2890 + assert _calculate(parameters, 10000, 2020, 2032) == 2800 + + def test_full_indexing_rejects_missing_frozen_runtime_scale(parameters): p = parameters.gov.contrib.ssa.pia _set(p.in_effect, True) @@ -144,3 +219,60 @@ def test_frozen_full_indexing_scale_is_read_at_eligibility_not_payment(parameter _set(p.full_price_indexing.real_wage_scale, 0.9, "2033-01-01") path, _ = formula_path_at(parameters, 2032, 2035) assert path.real_wage_scale_by_year == {2032: 1} + + +@pytest.mark.parametrize( + "missing_field,match", + [ + ("real_wage_scale", "real-wage scale"), + ("maximum_aime", "maximum-career AIME"), + ("maximum_pia_target", "maximum-career PIA target"), + ], +) +def test_frozen_2032_value_cannot_implicitly_serve_future_cohort( + parameters, missing_field, match +): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True) + if missing_field == "real_wage_scale": + _set(p.full_price_indexing.in_effect, True) + _set(p.full_price_indexing.real_wage_scale, 1, "2032-01-01") + else: + progressive = p.progressive_price_indexing + _set(progressive.in_effect, True) + _set(progressive.bend_point_fraction, 0.4) + bends = bend_points_at(parameters, 2054) + maximum = 3 * bends[1] + target = float( + compute_pia(maximum, 2054, bend_points=bends, round_result=False) + ) + for field, value in (("maximum_aime", maximum), ("maximum_pia_target", target)): + _set( + getattr(progressive, field), + value, + "2032-01-01" if field == missing_field else "2054-01-01", + ) + with pytest.raises(ValueError, match=match): + _calculate(parameters, 5000, 2054, 2054) + + +def test_frozen_dollar_override_applies_only_to_its_explicit_cohort(parameters): + p = parameters.gov.contrib.ssa.pia + _set(p.in_effect, True) + progressive = p.progressive_price_indexing + _set(progressive.in_effect, True) + _set(progressive.bend_point_fraction, 0.4) + _set(progressive.threshold, 3500, "2032-01-01") + supplied, _ = formula_path_at(parameters, 2032, 2032) + future, _ = formula_path_at(parameters, 2054, 2054) + assert supplied.threshold_by_year == {2032: 3500} + assert future.threshold_by_year is None + bends = bend_points_at(parameters, 2054) + assert progressive_threshold(2054, future, bend_points=bends) == Decimal( + str(bends[0]) + ) + Decimal(".4") * (Decimal(str(bends[1])) - Decimal(str(bends[0]))) + # Without the fraction, the earlier dollar observation supplies no + # threshold for the later cohort and the affected provision fails. + _set(progressive.bend_point_fraction, None, "2054-01-01") + with pytest.raises(ValueError, match="bend-point fraction"): + _calculate(parameters, 5000, 2054, 2054) diff --git a/policyengine_us/tests/unit/test_ss_pia_service.py b/policyengine_us/tests/unit/test_ss_pia_service.py index 1a8804d5956..b0fbf791010 100644 --- a/policyengine_us/tests/unit/test_ss_pia_service.py +++ b/policyengine_us/tests/unit/test_ss_pia_service.py @@ -9,6 +9,7 @@ from policyengine_us.tools.social_security.pia import ( FormulaPath, compute_pia, + has_active_reform, inverse_pia, inverse_unrounded, progressive_threshold, @@ -105,6 +106,30 @@ def test_fixed_cohort_and_aime_ignore_scoring_year_without_recompute(): assert compute_pia(5000, 2020, path, 2035, bend_points=BENDS) == D("2156.8") +@pytest.mark.parametrize( + "path", + [ + FormulaPath(), + FormulaPath(effective_year=2027, bend_point_multipliers=(1.1, 1)), + FormulaPath(factor_start_year=2027, factor_values=(".95", ".32", ".15")), + FormulaPath(factor_values=(".9", ".32", ".15")), + FormulaPath(full_price_indexing_start_year=2032), + FormulaPath(progressive_price_indexing_start_year=2032), + FormulaPath(s770=True), + ], +) +def test_inactive_or_identity_paths_do_not_require_aime_inference(path): + assert not has_active_reform(path, 2020, 2026) + + +def test_recompute_activation_matches_formula_applicability(): + path = FormulaPath(factor_start_year=2027, factor_values=(".9", ".32", ".05")) + assert not has_active_reform(path, 2020, 2026, "retroactive") + assert has_active_reform(path, 2020, 2027, "retroactive") + assert has_active_reform(FormulaPath(s770=True), 2020, 2026, "retroactive") + assert has_active_reform(FormulaPath(full_price_indexing_start_year=2032), 2032) + + def test_s770_recomputes_old_cohort_at_original_bends_from_2026(): # Introduced S.770 section 2: 95% first factor, 18% first-bend increase, # effective January 2026, with recomputation at initial-eligibility bends. @@ -192,6 +217,14 @@ def test_progressive_indexing_continuity_and_maximum_target(): assert compute_pia(6000, 2032, path, bend_points=(1000, 6000)) == D("2315.3") +def test_progressive_fraction_preserves_exact_dime_boundaries(): + # q=13000/3, F(q)=5900/3 and k=25/34, so at AIME=5988 the + # reformed PIA is exactly (4*5988+16100)/17 = 2356. Converting + # q to a finite Decimal before computing k can lose one dime. + path = _progressive_path(bend_point_fraction=Fraction(2, 3)) + assert compute_pia(5988, 2032, path, bend_points=(1000, 6000)) == 2356 + + def test_progressive_no_change_anchor_has_unit_above_threshold_multiplier(): path = _progressive_path(maximum_pia_target_by_year={2032: 3100}) for aime in (0, 1000, 3000, 6000, 10000, 12000): diff --git a/policyengine_us/tools/social_security/cola.py b/policyengine_us/tools/social_security/cola.py index ee14e7b3b79..174c34734ec 100644 --- a/policyengine_us/tools/social_security/cola.py +++ b/policyengine_us/tools/social_security/cola.py @@ -218,7 +218,8 @@ def read_parameter_events(parameters, through_year: int) -> tuple[ColaEvent, ... try: # Reuse the canonical statutory history supplied by the benefit-lever # route. Its authored event dates preserve irregular historical timing. - raw_history = parameters.gov.ssa.cola_history.rate + history_parameters = parameters.gov.ssa.cola_history + raw_history = history_parameters.rate history_start = str(raw_history.metadata["historical_start"]) history_end = str(raw_history.metadata["historical_end"]) observations = sorted( @@ -238,7 +239,9 @@ def read_parameter_events(parameters, through_year: int) -> tuple[ColaEvent, ... year = int(observation.instant_str[:4]) if year > through_year: continue - node = parameters(observation.instant_str).gov.ssa.cola_history + # Snapshot only these four leaves, not the complete US parameter + # tree for each historical year. + node = history_parameters(observation.instant_str) effective_number = int(node.effective_month) payment_number = int(node.first_payment_month) effective = f"{year}-{effective_number:02d}" @@ -253,9 +256,9 @@ def read_parameter_events(parameters, through_year: int) -> tuple[ColaEvent, ... ) kwargs = {} if year == 1999: - correction = parameters( + correction = parameters.gov.ssa.social_security.cola( observation.instant_str - ).gov.ssa.social_security.cola + ) kwargs = { "as_paid_rate": _decimal(correction.december_1999_as_paid_rate), "correction_payment_month": str( @@ -275,9 +278,10 @@ def read_parameter_events(parameters, through_year: int) -> tuple[ColaEvent, ... # not evidence of a frozen Q3 projection after its last dated # observation. Inspect the raw tree, including runtime extensions, # before reading instant values that could silently carry forward. + q3_parameter = parameters.gov.ssa.uprating q3_years = { int(observation.instant_str[:4]) - for observation in parameters.gov.ssa.uprating.values_list + for observation in q3_parameter.values_list if observation.value is not None and observation.instant_str[5:] == "01-01" } @@ -302,7 +306,7 @@ def read_parameter_events(parameters, through_year: int) -> tuple[ColaEvent, ... f"The frozen SSA Q3 path is missing payment year {min(missing_years)}" ) q3 = { - year: _decimal(parameters(f"{year}-01-01").gov.ssa.uprating) + year: _decimal(q3_parameter(f"{year}-01-01")) for year in range(anchor_year + 1, through_year + 1) } result.extend( diff --git a/policyengine_us/tools/social_security/parameters.py b/policyengine_us/tools/social_security/parameters.py index 425aa9c4c62..82c31872883 100644 --- a/policyengine_us/tools/social_security/parameters.py +++ b/policyengine_us/tools/social_security/parameters.py @@ -23,8 +23,28 @@ def _optional(node, name): return None -def _snapshot(parameters, year): - return parameters(f"{year}-01-01") +def _snapshot(node, year): + # Snapshot only the requested SSA subtree; a root snapshot traverses the + # entire US parameter tree even when the caller needs just two bend points. + return node(f"{year}-01-01") + + +def _frozen_value(node, name, year): + """Require a published January observation for this exact cohort. + + Core normally holds a scalar's last value forward. Frozen indexing paths + instead enumerate every cohort explicitly; carrying an old scale, target + or dollar threshold forward would manufacture an unfrozen reform path. + """ + instant = f"{year}-01-01" + return next( + ( + entry.value + for entry in getattr(node, name).values_list + if entry.instant_str == instant + ), + None, + ) def bend_points_at(parameters, eligibility_year): @@ -34,7 +54,7 @@ def bend_points_at(parameters, eligibility_year): scale. Future years use that scale's existing wage-indexed projections. """ year = _year(eligibility_year) - pia = _snapshot(parameters, year).gov.ssa.social_security.pia + pia = _snapshot(parameters.gov.ssa.social_security.pia, year) if year <= 2026: return (pia.bend_points.first, pia.bend_points.second) return tuple(pia.formula_factors.thresholds[1:3]) @@ -43,11 +63,14 @@ def bend_points_at(parameters, eligibility_year): def formula_path_at(parameters, eligibility_year, payment_year): """Return ``(FormulaPath, recompute_mode)`` for one worker and payment year. - Cohort-only custom factors and bend multipliers read their dated values at - eligibility. An explicit custom recompute reads the payment-year formula - while keeping that worker's initial-eligibility bends. Frozen indexing - scales, thresholds, maximum-career AIMEs and targets always read at the - eligibility year. Any missing frozen data fail in the shared PIA service. + Cohort-only enablement, custom factors and bend multipliers read their + dated values at eligibility and stay fixed for that cohort. Only an + enabled payment-year explicit custom recompute reads the payment-year + formula while keeping that worker's initial-eligibility bends. Frozen indexing + scales, dollar thresholds, maximum-career AIMEs and targets require an + explicit observation at January 1 of the eligibility year. A missing + dollar override falls back to the supplied hold-forward bend-point + fraction; other missing frozen data fail in the shared PIA service. S.770 has its own switch and mandatory older-beneficiary recomputation. Custom gates are resolved here so enabling S.770 cannot accidentally extend @@ -57,14 +80,16 @@ def formula_path_at(parameters, eligibility_year, payment_year): payment = _year(payment_year) if payment < year: raise ValueError("payment year cannot precede eligibility year") - current = _snapshot(parameters, payment) - enabled = current.gov.contrib.ssa.pia.in_effect - custom_recompute = bool(enabled and current.gov.contrib.ssa.pia.recompute_existing) + pia_node = parameters.gov.contrib.ssa.pia + current = _snapshot(pia_node, payment) + cohort = _snapshot(pia_node, year) + custom_recompute = bool(current.in_effect and current.recompute_existing) + enabled = current.in_effect if custom_recompute else cohort.in_effect selection_year = payment if custom_recompute else year - settings = _snapshot(parameters, selection_year).gov.contrib.ssa.pia - cohort = _snapshot(parameters, year).gov.contrib.ssa.pia + settings = _snapshot(pia_node, selection_year) s770 = bool( - current.gov.contrib.congress.s770.section_2.in_effect and payment >= 2026 + _snapshot(parameters.gov.contrib.congress.s770.section_2, payment).in_effect + and payment >= 2026 ) values = {"s770": s770} @@ -83,23 +108,26 @@ def formula_path_at(parameters, eligibility_year, payment_year): full = settings.full_price_indexing if full.in_effect and selection_year >= full.start_year: - scale = _optional(cohort.full_price_indexing, "real_wage_scale") + scale = _frozen_value(pia_node.full_price_indexing, "real_wage_scale", year) values["full_price_indexing_start_year"] = int(full.start_year) values["real_wage_scale_by_year"] = None if scale is None else {year: scale} progressive = settings.progressive_price_indexing if progressive.in_effect and selection_year >= progressive.start_year: - frozen = cohort.progressive_price_indexing values["progressive_price_indexing_start_year"] = int( progressive.start_year ) - values["bend_point_fraction"] = _optional(frozen, "bend_point_fraction") + values["bend_point_fraction"] = _optional( + progressive, "bend_point_fraction" + ) for parameter_name, field in ( ("threshold", "threshold_by_year"), ("maximum_aime", "maximum_aime_by_year"), ("maximum_pia_target", "maximum_pia_target_by_year"), ): - value = _optional(frozen, parameter_name) + value = _frozen_value( + pia_node.progressive_price_indexing, parameter_name, year + ) values[field] = None if value is None else {year: value} mode = "retroactive" if custom_recompute or s770 else "cohort" diff --git a/policyengine_us/tools/social_security/pia.py b/policyengine_us/tools/social_security/pia.py index 10cf064de16..72e9d3a5348 100644 --- a/policyengine_us/tools/social_security/pia.py +++ b/policyengine_us/tools/social_security/pia.py @@ -136,23 +136,82 @@ def _active(start_year, eligibility_year, payment_year, recompute_mode): return year >= start_year +def _computation_years(eligibility_year, payment_year, recompute_mode): + year = _year(eligibility_year, "eligibility year") + if recompute_mode not in ("cohort", "retroactive"): + raise ValueError("recompute_mode must be 'cohort' or 'retroactive'") + if payment_year is not None: + _year(payment_year, "payment year") + if payment_year < year: + raise ValueError("payment year cannot precede eligibility year") + if recompute_mode == "retroactive" and payment_year is None: + raise ValueError("retroactive recomputation requires a payment year") + return year + + +def _active_features(path, year, payment_year, recompute_mode): + """Resolve provision gates once for calculation and inference decisions.""" + features = set() + if _active(path.effective_year, year, payment_year, recompute_mode): + features.add("bend_points") + if path.factor_values is not None and _active( + path.factor_start_year, year, payment_year, recompute_mode + ): + features.add("factors") + if path.s770 and _active(2026, year, payment_year, recompute_mode): + features.add("s770") + for feature, start in ( + ("full_price_indexing", path.full_price_indexing_start_year), + ("progressive_price_indexing", path.progressive_price_indexing_start_year), + ): + if start is not None and _active(start, year, payment_year, recompute_mode): + features.add(feature) + return features + + +def has_active_reform( + formula_path: FormulaPath | None, + eligibility_year: int, + payment_year: int | None = None, + recompute_mode: str = "cohort", +) -> bool: + """Whether a provision applies and can require recovering supplied AIME. + + A configured future provision or identity custom scale must not make a + supplied unreformed PIA go through an unnecessary inverse. Enabled indexing + paths still require validation of their frozen inputs, including at an + identity anchor. + """ + year = _computation_years(eligibility_year, payment_year, recompute_mode) + path = formula_path or FormulaPath() + features = _active_features(path, year, payment_year, recompute_mode) + if features & {"s770", "full_price_indexing", "progressive_price_indexing"}: + return True + if "bend_points" in features: + if len(path.bend_point_multipliers) != 2: + raise ValueError("two bend-point multipliers are required") + if any( + _number(value, "bend-point multiplier") != 1 + for value in path.bend_point_multipliers + ): + return True + return "factors" in features and tuple( + _number(value, "PIA factor") for value in path.factor_values + ) != tuple(Fraction(value) for value in DEFAULT_FACTORS) + + def _cohort_value(path, year, name): if path is None or year not in path: raise ValueError(f"{name} requires a frozen value for eligibility year {year}") return _number(path[year], name) -def progressive_threshold( +def _progressive_threshold( eligibility_year: int, formula_path: FormulaPath, *, bend_points: tuple[Number, Number], -) -> Decimal: - """Return the M8 protected threshold; a supplied dollar path takes priority. - - The fractional threshold uses the unreformed eligibility-year bend points, - including when another provision changes the formula's bend points. - """ +) -> Fraction: year = _year(eligibility_year, "eligibility year") bends, _ = _scale(bend_points, DEFAULT_FACTORS) if formula_path.threshold_by_year is not None: @@ -171,7 +230,24 @@ def progressive_threshold( ) if threshold < bends[0]: raise ValueError("progressive threshold cannot cut the protected first segment") - return _decimal(threshold) + return threshold + + +def progressive_threshold( + eligibility_year: int, + formula_path: FormulaPath, + *, + bend_points: tuple[Number, Number], +) -> Decimal: + """Return the M8 protected threshold; a supplied dollar path takes priority. + + The fractional threshold uses the unreformed eligibility-year bend points, + including when another provision changes the formula's bend points. The + formula itself retains the exact rational threshold through final rounding. + """ + return _decimal( + _progressive_threshold(eligibility_year, formula_path, bend_points=bend_points) + ) def compute_pia( @@ -192,22 +268,15 @@ def compute_pia( inverse lower-endpoint convention and continuous reform sensitivities. ``round_result=False`` exposes the formula before statutory dime truncation. """ - year = _year(eligibility_year, "eligibility year") - if recompute_mode not in ("cohort", "retroactive"): - raise ValueError("recompute_mode must be 'cohort' or 'retroactive'") - if payment_year is not None: - _year(payment_year, "payment year") - if payment_year < year: - raise ValueError("payment year cannot precede eligibility year") - if recompute_mode == "retroactive" and payment_year is None: - raise ValueError("retroactive recomputation requires a payment year") + year = _computation_years(eligibility_year, payment_year, recompute_mode) amount = _number(aime, "AIME") if amount < 0: raise ValueError("AIME must be nonnegative") baseline_bends, rates = _scale(bend_points, factors) bends = baseline_bends path = formula_path or FormulaPath() - if _active(path.effective_year, year, payment_year, recompute_mode): + features = _active_features(path, year, payment_year, recompute_mode) + if "bend_points" in features: if len(path.bend_point_multipliers) != 2: raise ValueError("two bend-point multipliers are required") multipliers = tuple( @@ -215,11 +284,9 @@ def compute_pia( for value in path.bend_point_multipliers ) bends = tuple(bp * multiplier for bp, multiplier in zip(bends, multipliers)) - if path.factor_values is not None and _active( - path.factor_start_year, year, payment_year, recompute_mode - ): + if "factors" in features: _, rates = _scale(baseline_bends, path.factor_values) - if path.s770 and _active(2026, year, payment_year, recompute_mode): + if "s770" in features: rates = (Fraction(95, 100), rates[1], rates[2]) if path.s770_increase_first_bend_point: bends = (bends[0] * Fraction(118, 100), bends[1]) @@ -227,25 +294,15 @@ def compute_pia( # Full price indexing scales every marginal factor by a pinned ratio of # price growth to wage growth, using the same documented cohort index basis. - if path.full_price_indexing_start_year is not None and _active( - path.full_price_indexing_start_year, year, payment_year, recompute_mode - ): + if "full_price_indexing" in features: scale = _cohort_value(path.real_wage_scale_by_year, year, "real-wage scale") if scale <= 0: raise ValueError("real-wage scale must be positive") rates = tuple(rate * scale for rate in rates) result = _raw_pia(amount, bends, rates) - if path.progressive_price_indexing_start_year is not None and _active( - path.progressive_price_indexing_start_year, - year, - payment_year, - recompute_mode, - ): - threshold = _number( - progressive_threshold(year, path, bend_points=baseline_bends), - "progressive threshold", - ) + if "progressive_price_indexing" in features: + threshold = _progressive_threshold(year, path, bend_points=baseline_bends) if threshold < bends[0]: raise ValueError( "progressive threshold cuts the final formula's first segment" From 254e7b2b7dd48e7b228f307cf7861425d223a124 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 03:44:24 -0400 Subject: [PATCH 06/16] Add opt-in supplied-record household and restricted survivor calculators --- docs/_toc.yml | 3 + docs/usage/social-security-calculator.md | 222 +++- docs/usage/social-security/RULINGS.md | 15 + .../ss_calculated_benefit.yaml | 53 + .../unit/test_ss_calculator_differential.py | 227 ++++ .../tests/unit/test_ss_calculator_engine.py | 501 +++++++++ .../unit/test_ss_household_calculator.py | 990 ++++++++++++++++++ policyengine_us/tools/general.py | 5 +- .../tools/social_security/engine.py | 245 +++++ .../tools/social_security/household.py | 689 ++++++++++++ .../ssa/social_security/calculator/inputs.py | 338 ++++++ .../ssa/social_security/calculator/results.py | 170 +++ 12 files changed, 3436 insertions(+), 22 deletions(-) create mode 100644 docs/usage/social-security/RULINGS.md create mode 100644 policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml create mode 100644 policyengine_us/tests/unit/test_ss_calculator_differential.py create mode 100644 policyengine_us/tests/unit/test_ss_calculator_engine.py create mode 100644 policyengine_us/tests/unit/test_ss_household_calculator.py create mode 100644 policyengine_us/tools/social_security/engine.py create mode 100644 policyengine_us/tools/social_security/household.py create mode 100644 policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py create mode 100644 policyengine_us/variables/gov/ssa/social_security/calculator/results.py diff --git a/docs/_toc.yml b/docs/_toc.yml index b6496e344f2..0cb748b3196 100644 --- a/docs/_toc.yml +++ b/docs/_toc.yml @@ -65,6 +65,9 @@ parts: chapters: - file: usage/microsimulation - file: usage/parameter-discovery + - file: usage/social-security-calculator + sections: + - file: usage/social-security/RULINGS - file: usage/speed - caption: Examples chapters: diff --git a/docs/usage/social-security-calculator.md b/docs/usage/social-security-calculator.md index 900933759e6..a7c29ba991a 100644 --- a/docs/usage/social-security-calculator.md +++ b/docs/usage/social-security-calculator.md @@ -1,23 +1,203 @@ # Supplied-record Social Security calculator -This opt-in route will calculate gross monthly retirement benefits from a supplied -unreformed eligibility-year AIME or PIA, and the restricted single-survivor case -from a supplied monthly benefit and composite ratio. Existing public benefit -inputs retain their current behavior. - -Implementation plan: - -1. Share one monthly PIA service across household and future history callers, - with eligibility-year bend points, explicit applicability, baseline inversion, - contributed formula paths and the S.770 section 2 preset. -2. Build an entitlement ledger with cohort claiming adjustments, statutory COLA - and payment rounding, insured-status assertions and the annual earnings test. -3. Require an identified worker record and ordinary, non-WINDEX survivor basis; - derive the death benchmark and propagate supplied-payment rounding intervals. -4. Expose separate calculated results until the benefit source-selector change - merges. Wire those results into its AIME/PIA/survivor modes in one later step. -5. Validate published SSA examples, boundary cases, property invariants and - equality of existing outputs with the calculator disabled. - -The supported computation benchmark begins in 1983. History-derived AIME, -family benefits, disability computations and minimum PIAs are separate work. +The opt-in calculator implements design v3 D0, 4a-1 and the shared 4d core, +including amendments M1–M4, the top-factor structure in M6 and M8. It returns +**gross benefits before Medicare deductions**, from an identified worker record. +Existing public benefit inputs continue to work independently. + +## Inputs and outputs + +Set `ss_calculator_source` to `aime`, `pia` or `survivor`; its default is `off`. +The selector determines the route even when the selected amount is zero. +Omitting the selected amount fails; it is distinct from supplying zero. +Identity/source fields are eternal inputs. Supply exact recipient birth date, +worker ID, entitlement month, insured status and source valuation basis. The +only supported basis is `unreformed_eligibility`; externally reformed sources +fail rather than applying a mechanism twice. Each member of a retired couple +supplies their own record. Disability, spouse, child, minimum and dual-entitlement +computations are outside this route. + +For own retirement, also supply `ss_calculator_eligibility_year` and either +`ss_calculator_supplied_aime` (whole monthly dollars) or +`ss_calculator_supplied_pia` (monthly dimes at initial eligibility). Optional +`ss_calculator_claiming_factor` is an exact decimal **string**; otherwise exact +claiming months, birth-cohort FRA, early reduction and delayed credits determine +it. Delayed credits earned in a midyear claiming year enter the benefit the +following January, or upon reaching 70. A January 1 birth belongs to the previous +attainment cohort. Retirement commencement must satisfy SSA's full-month age-62 +rule. + +For example: + +```python +from policyengine_us import Simulation + +simulation = Simulation( + situation={ + "people": { + "worker": { + "ss_calculator_source": "aime", + "ss_calculator_worker_id": "worker-record-1", + "ss_calculator_birth_date": "1961-01-02", + "ss_calculator_eligibility_year": 2023, + "ss_calculator_entitlement_month": "2023-01", + "ss_calculator_supplied_aime": 3000, + "ss_calculator_insured": True, + "ss_calculator_no_special_monthly_test": True, + "ss_calculator_no_prior_withholding_adjustment": True, + "ss_calculator_earnings_test_no_trigger": True, + } + }, + } +) +# SSA's 2023 example: $1,606.70 PIA, claim at 62/FRA 67 => $1,124. +monthly = simulation.calculate("ss_calculated_benefit", "2023-01") +checks = simulation.calculate("ss_calculated_annual_payment", 2023) +``` + +`ss_calculated_benefit` is the payable amount for an **entitlement month**; +`ss_calculated_payment` is the check paid the following month. +`ss_calculated_annual_entitlement` sums January–December entitlement, whereas +`ss_calculated_annual_payment` sums checks actually paid January–December. +`ss_calculated_retirement` and `ss_calculated_survivors` expose the latter by +selected component. A first entitlement in July normally yields five checks +in that calendar year. COLAs effective December first affect January checks. +S.770 section 2(c)(1) first affects January 2026 benefit entitlement, normally +paid in February. Dated custom payment-year paths use the check year. + +The pure `calculate_year` service returns both totals and a monthly ledger: +eligibility PIA, PIA after each COLA, exact claiming factor, unrounded benefit, +rounded gross benefit, capped earnings-test reduction and payable amount. +The engine also exposes monthly `ss_calculated_eligibility_pia`, annual +`ss_calculated_earnings_test_reduction`, and inferred PIA/AIME interval endpoints. +An absent inference interval is exposed as zero; the source selector identifies +which diagnostic applies. + +## Earnings test and scope assertions + +Supply annual `ss_calculator_annual_earnings`. In the FRA year supply +`ss_calculator_pre_fra_earnings`: only earnings before the retirement FRA month +count. No earnings test applies from FRA onward. Annual excess-earnings +deductions are truncated to whole dollars, allocated to the earliest affected +benefit months and capped at their benefits. Calculating January's check may +also require the previous year's earnings. A `-1` earnings input means missing, +not zero. Alternatively assert `ss_calculator_earnings_test_no_trigger`; supplied +excess earnings contradicting it fail. + +This route requires `ss_calculator_no_special_monthly_test` and +`ss_calculator_no_prior_withholding_adjustment`. These assert that special +first-year monthly/service rules and actuarial adjustments for prior withheld +months do not affect the supplied case. Such cases need a separate computation +or a supplied authoritative claiming factor and a valid scope assertion; this +calculator does not silently approximate those rules. All entitlement before +commencement, or on an uninsured record, is zero. + +The earnings-test implementation covers entitlement years from 2000 onward. +Earlier years require the explicit no-trigger assertion because historical +age limits and deduction rates differ. Positive benefits below one dollar +before December 2006 fail explicitly: their manual year-end payment timing +is outside the recurring monthly ledger. Later sub-dollar benefits retain +their dimes under SSA's payment-rounding exception. + +## Restricted survivor + +Select `survivor` and supply monthly gross paid amount, source valuation check +month, positive decimal-string composite ratio and a description of everything +that ratio includes. The ratio includes the case's survivor reduction and any +worker delayed credits, so no further claiming factor may be supplied. +Assert nonbinding RIB-LIM/family maximum, no dual entitlement, no earnings-test +withholding in the source valuation, and ordinary non-WINDEX scope. + +The `ss_calculator_worker_birth_year`, `death_year`, optional exact worker birth +and death dates, optional `authoritative_year`, and `basis_provenance` identify +the computation benchmark. Without an authoritative basis, assert no prior +worker disability. Derive E as the earlier of death and age-62 attainment. +January 1 attainment uses the preceding year. A year-only fallback requires +`year_only_not_january_1`; death and age-62 attainment in the same year require +exact dates or `same_year_death_before_62` (1/0; -1 means unspecified). + +COLAs for a pre-62 death begin with December of the death benchmark, paid the +following January. Recovery propagates the supplied final-payment interval +backward through the composite ratio and **every rounded COLA**, retaining a +half-open eligibility-PIA interval. The lower admissible dime is the point +convention; baseline forward computation must reproduce the supplied payment. +When reform needs AIME, invert the fixed unreformed PIA scale at that lower +endpoint and expose the corresponding AIME interval. Zero stays zero. + +The default-false parameter +`gov.contrib.congress.s770.section_2.recompute_pre2026_death_before_eligibility` +controls only the 18% first-bend-point increase for the pre-2026 death-before-62 +subset. The 95% first factor still applies when false. Deaths in 2026 or later +receive both changes independently of that switch. See [the recorded modeling +ruling](social-security/RULINGS.md). + +## Shared PIA paths and policies + +`tools.social_security.pia.compute_pia` is the common pure monthly service for +supplied AIME, recovered AIME and future history callers. Its inputs explicitly +separate initial eligibility, formula path, scoring/payment year and cohort vs +retroactive applicability. All computations and inverses require E >= 1983. +Historical bends back to 1979 are separate parameters, preserving legacy scale +values. Future bends use the model's existing wage-indexed projections. + +`gov.contrib.ssa.pia` contains neutral bend-point multipliers, factors and cohort +start, and explicit `recompute_existing`. No top-factor package schedule is +selected. S.770 is separately enabled with +`gov.contrib.congress.s770.section_2.in_effect` and uses original eligibility +bend points for older beneficiaries. + +Full price indexing requires a frozen cohort `real_wage_scale` path: cumulative +price growth divided by cumulative wage growth from the declared anchor. This +scales **all** formula factors. Progressive indexing requires a frozen +maximum-career AIME and PIA target, plus either `bend_point_fraction` or optional +`threshold` dollar path under `gov.contrib.ssa.pia.progressive_price_indexing`. +The dollar path overrides the fraction. Otherwise the protected threshold is +BP1(E) + f * (BP2(E) - BP1(E)). There is no default fraction. Enabling a path +without its required frozen inputs fails. Frozen scales, dollar thresholds, +maximum AIMEs and targets require explicit January observations for each +eligibility cohort; they never silently carry a prior cohort's data forward. +The policy fraction and ordinary factor schedules retain normal dated-policy +semantics. No population percentile or solvency +estimate supplies missing values. Scoring must pin price/wage bases, lags, +anchor, maximum-taxable career, source hashes and combined-policy order. +Composition order is custom bends/factors, S.770, full indexing, progressive +protected/maximum-target construction, and final eligibility dime truncation. + +`gov.contrib.ssa.benefit_levers.cola.pp_change`, +`across_the_board.rate`/`start_year` and `payable.share` are the shared neutral +payment-year parameters reused from #10400. COLA settings also accept an +effective year/month, payment start/end year and a supplied alternative rate. The annual person +input `ss_calculator_withhold_cola` accepts an externally resolved E3 decision +when `cola.withholding_enabled` is true. +Withholding sets that event's COLA to zero, jointly with any rate change; no +second COLA factor is applied. Payable shares must lie in [0,1], and rates must +not imply a negative benefit. A depletion-year midyear blend is supplied in the +annual payable-share path. E2 and E3 income/threshold computation belong to +their respective modules; their policies and jointly calculated tax-unit +outputs can consume this route once public wiring exists. + +## Public source-selector wiring + +Source-selector PR #10400 was open when this route was built. Its canonical +COLA history and common lever parameter files are reused here. Historical bend +points remain in a separate table because copying its legacy scale backfill +would change existing pre-2015 `ss_pia` outputs with this route disabled. This change adds +no `_reported` twins and changes no public benefit formula. Once it merges, +map its supplied-AIME/PIA retirement modes to `ss_calculated_retirement` and its +restricted survivor mode to `ss_calculated_survivors`. Bypass population +PIA/COLA factors and any across/payable factors already applied in this ledger; +perform the earnings test once. Preserve explicit public final overrides. +For joint household tax calculations before that wiring, explicitly supply the +calculated annual checks to the existing public components in a separate +calculation; never write them into `_reported` as if they were original data. + +## Sources and validation + +Published fixtures cite [SSA Supplement 2023 Appendix D](https://www.ssa.gov/policy/docs/statcomps/supplement/2023/apnd.html), +[COLA application](https://www.ssa.gov/oact/COLA/colaapplic.html), and +[2026 earnings-test examples](https://www.ssa.gov/benefits/retirement/planner/whileworking.html). +Historical parameters cite [bend points](https://www.ssa.gov/OACT/COLA/bendpoints.html) +and [COLAs](https://www.ssa.gov/OACT/COLA/colaseries.html). December 1999 retains +its original 2.4% as-paid rate until the 2001 correction, then the corrected 2.5% +path; special one-time arrears are excluded from recurring gross benefits. +Earlier COLA rules are recorded, but E < 1983 routes fail explicitly. diff --git a/docs/usage/social-security/RULINGS.md b/docs/usage/social-security/RULINGS.md new file mode 100644 index 00000000000..b48bd22b55b --- /dev/null +++ b/docs/usage/social-security/RULINGS.md @@ -0,0 +1,15 @@ +# Restricted-survivor modeling ruling + +For the contributed S.770 section 2 preset, a worker who died before 2026 and +before attaining 62 receives the 95% first factor at the death-based computation +benchmark. The parameter +`recompute_pre2026_death_before_eligibility` controls **only** the 18% increase +to that benchmark's first bend point. False therefore retains the 95% factor; +true applies both changes. Deaths after 2025 are outside this switch. + +This is an explicit scenario interpretation, not a statutory conclusion. The +switch defaults false and must be recorded with the scenario. For AIME above +the increased first bend point, the raw monthly gain is .05 * original BP1 +with the switch false, or .1634 * original BP1 with it true. + +Source: [119th Congress S.770, section 2(a) and (c)](https://www.congress.gov/bill/119th-congress/senate-bill/770/text). diff --git a/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml b/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml new file mode 100644 index 00000000000..3c7dcff43d9 --- /dev/null +++ b/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml @@ -0,0 +1,53 @@ +- name: Published SSA 2023 supplied AIME, age 62 and FRA 67 + # SSA Supplement 2023 Appendix D: + # https://www.ssa.gov/policy/docs/statcomps/supplement/2023/apnd.html + period: 2023 + input: + ss_calculator_source: aime + ss_calculator_worker_id: worker-record-1 + ss_calculator_birth_date: '1961-01-02' + ss_calculator_eligibility_year: 2023 + ss_calculator_entitlement_month: '2023-01' + ss_calculator_supplied_aime: 3000 + ss_calculator_insured: true + ss_calculator_no_special_monthly_test: true + ss_calculator_no_prior_withholding_adjustment: true + ss_calculator_earnings_test_no_trigger: true + output: + ss_calculated_eligibility_pia: + 2023-01: 1606.7 + ss_calculated_benefit: + 2023-01: 1124 + # Dec2023 entitlement includes the 3.2% COLA, check paid Jan2024. + ss_calculated_annual_payment: 12364 + # Eleven baseline entitlement months and the COLA-adjusted December. + ss_calculated_annual_entitlement: 13524 + social_security_retirement: 0 + +- name: Supplied PIA zero is selected even when unselected AIME is positive + period: 2026 + input: + ss_calculator_source: pia + ss_calculator_worker_id: worker-record-zero + ss_calculator_birth_date: '1964-01-02' + ss_calculator_eligibility_year: 2026 + ss_calculator_entitlement_month: '2026-01' + ss_calculator_supplied_aime: 5000 + ss_calculator_supplied_pia: 0 + ss_calculator_insured: true + ss_calculator_no_special_monthly_test: true + ss_calculator_no_prior_withholding_adjustment: true + ss_calculator_earnings_test_no_trigger: true + output: + ss_calculated_retirement: 0 + ss_calculated_annual_entitlement: 0 + +- name: The opt-in calculator is disabled by default + period: 2026 + input: + social_security_retirement: 20000 + ss_calculator_supplied_aime: 5000 + output: + ss_calculated_retirement: 0 + ss_calculated_survivors: 0 + social_security_retirement: 20000 diff --git a/policyengine_us/tests/unit/test_ss_calculator_differential.py b/policyengine_us/tests/unit/test_ss_calculator_differential.py new file mode 100644 index 00000000000..e4e7325cc09 --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_calculator_differential.py @@ -0,0 +1,227 @@ +"""The optional calculator leaves the existing model disconnected and unchanged. + +The reference removes the new variables and parameter namespaces entirely. It +therefore detects an accidental dependency even when a new variable's default +value happens to be neutral. This is portable in source distributions and CI; +it does not need a second checkout or git at test time. The implementation's +separate source-diff check establishes that legacy formulas/parameters were not +edited. These comparisons exercise their live SSA and downstream dependency +closures, including every intermediate value actually calculated by reference. +""" + +from copy import deepcopy + +import numpy as np +import pytest +from policyengine_core.reforms import Reform + +from policyengine_us import Simulation +from policyengine_us.tools.general import earliest_input_year + + +CALCULATOR_PREFIXES = ("ss_calculator_", "ss_calculated_") +NEW_PARAMETER_NODES = ( + "gov.contrib.ssa.benefit_levers", + "gov.contrib.ssa.pia", + "gov.contrib.congress.s770", + "gov.ssa.social_security.pia.bend_points", + "gov.ssa.social_security.cola", + "gov.ssa.cola_history", +) +YEAR = 2026 + + +class WithoutHouseholdCalculator(Reform): + """Reconstruct the existing model by removing only this feature's additions.""" + + def apply(self): + self.variables = { + name: variable + for name, variable in self.variables.items() + if not name.startswith(CALCULATOR_PREFIXES) + } + for path in NEW_PARAMETER_NODES: + parent = self.parameters + *parents, name = path.split(".") + for part in parents: + parent = parent.children.get(part) + if parent is None: + break + if parent is not None and name in parent.children: + parent.children.pop(name) + delattr(parent, name) + + +LEGACY_SSA_OUTPUTS = ( + "social_security_retirement", + "social_security_disability", + "social_security_survivors", + "social_security_dependents", + "social_security", + "ss_aime_eligible", + "ss_aime", + "ss_claiming_age", + "ss_covered_earnings_this_year", + "ss_earnings_test_applicable", + "ss_earnings_test_reduction", + "ss_full_retirement_age_months", + "ss_pia", + "ss_quarters_of_coverage", + "ss_retirement_age_adjustment_factor", + "ss_retirement_benefit_before_earnings_test", + "ss_retirement_eligible", +) +DOWNSTREAM_OUTPUTS = ( + "taxable_social_security", + "adjusted_gross_income", + "income_tax", + "net_investment_income_tax", + "medicare_irmaa_magi", + "medicare_irmaa_magi_two_years_prior", + "medicare_part_b_premium", + "ssi", + "household_net_income", +) + + +def _situation(age, benefits, earnings=0, investment_income=0, joint=False): + amounts = dict(zip(LEGACY_SSA_OUTPUTS[:4], benefits)) + person = { + "age": {YEAR: age}, + "employment_income": {YEAR: earnings}, + "taxable_interest_income": {YEAR: investment_income}, + # Supply the existing intermediate to avoid reconstructing a career; + # the legacy helper calculations are deliberately still disconnected + # from the separately supplied public benefit amounts. + "ss_aime": {YEAR: 5_000}, + "ss_claiming_age": {YEAR: 62}, + **{name: {YEAR: value} for name, value in amounts.items()}, + } + people = {"worker": person} + if joint: + people["spouse"] = { + "age": {YEAR: age - 2}, + "social_security_retirement": {YEAR: 12_000}, + "ss_aime": {YEAR: 3_000}, + "ss_claiming_age": {YEAR: 65}, + } + members = list(people) + return { + "people": people, + "tax_units": { + "tax_unit": {"members": members, "tax_unit_itemizes": {YEAR: False}} + }, + "spm_units": {"spm_unit": {"members": members}}, + "families": {"family": {"members": members}}, + "marital_units": {"marital_unit": {"members": members}}, + "households": {"household": {"members": members, "state_code": {YEAR: "NY"}}}, + } + + +def _cached_reference_values(simulation): + """Capture the whole exercised dependency closure before comparing values.""" + return [ + (name, period, holder.get_array(period).copy()) + for population in simulation.populations.values() + for name, holder in population._holders.items() + for period in holder.get_known_periods() + if holder.get_array(period) is not None + ] + + +@pytest.mark.parametrize( + "situation", + [ + _situation(45, (0, 0, 0, 0), earnings=50_000), + _situation(62, (18_000, 0, 0, 0), earnings=33_400), + _situation(67, (0, 0, 24_000, 0), investment_income=90_000), + _situation(50, (0, 16_000, 0, 4_000), earnings=2_000), + _situation(75, (30_000, 0, 0, 0), investment_income=150_000, joint=True), + ], + ids=("working", "early-retirement", "survivor", "disability", "own-record-couple"), +) +def test_calculator_off_matches_model_without_feature(situation): + isolated = Simulation.default_tax_benefit_system_instance.clone() + isolated.apply_reform_set(WithoutHouseholdCalculator) + reference = Simulation( + situation=deepcopy(situation), + tax_benefit_system=isolated, + reform=WithoutHouseholdCalculator, + ) + off_inputs = deepcopy(situation) + for person in off_inputs["people"].values(): + person["ss_calculator_source"] = "off" + # An unselected amount must never activate a source by positivity. + person["ss_calculator_supplied_aime"] = 12_345 + person["ss_calculator_supplied_pia"] = 4_321.0 + actual = Simulation(situation=off_inputs) + + assert not any( + name.startswith(CALCULATOR_PREFIXES) + for name in reference.tax_benefit_system.variables + ) + for name in LEGACY_SSA_OUTPUTS + DOWNSTREAM_OUTPUTS: + expected = reference.calculate(name, YEAR) + np.testing.assert_array_equal( + actual.calculate(name, YEAR), expected, err_msg=name + ) + + # Check every legacy intermediate reached by these outputs, not only the + # handful of final totals chosen above. Exact equality includes zero inputs. + for name, period, expected in _cached_reference_values(reference): + np.testing.assert_array_equal( + actual.calculate(name, period), expected, err_msg=f"{name} at {period}" + ) + for name in ( + "ss_calculated_annual_entitlement", + "ss_calculated_annual_payment", + "ss_calculated_retirement", + "ss_calculated_survivors", + ): + np.testing.assert_array_equal(actual.calculate(name, YEAR), 0) + + +@pytest.mark.parametrize("amount", [0, 18_000]) +def test_legacy_public_input_and_later_zero_override_survive(amount): + situation = _situation(70, (amount, 0, 0, 0)) + actual = Simulation(situation=situation) + np.testing.assert_array_equal( + actual.calculate("social_security_retirement", YEAR), [amount] + ) + actual.set_input("social_security_retirement", YEAR, np.array([0])) + np.testing.assert_array_equal( + actual.calculate("social_security_retirement", YEAR), [0] + ) + + +def test_off_unselected_history_does_not_change_irmaa_lookback(): + """Calculator records are not a past-year tax return supplied to the model.""" + situation = _situation(75, (30_000, 0, 0, 0), investment_income=150_000) + isolated = Simulation.default_tax_benefit_system_instance.clone() + isolated.apply_reform_set(WithoutHouseholdCalculator) + reference = Simulation( + situation=deepcopy(situation), + tax_benefit_system=isolated, + reform=WithoutHouseholdCalculator, + ) + situation["people"]["worker"].update( + { + "ss_calculator_source": "off", + "ss_calculator_annual_earnings": {2020: 50_000}, + "ss_calculator_pre_fra_earnings": {2020: 20_000}, + "ss_calculator_withhold_cola": {2020: True}, + } + ) + actual = Simulation(situation=situation) + assert earliest_input_year(reference) == YEAR + assert earliest_input_year(actual) == YEAR + for name in ( + "medicare_irmaa_magi_two_years_prior", + "medicare_part_b_premium", + "household_net_income", + ): + np.testing.assert_array_equal( + actual.calculate(name, YEAR), + reference.calculate(name, YEAR), + err_msg=name, + ) diff --git a/policyengine_us/tests/unit/test_ss_calculator_engine.py b/policyengine_us/tests/unit/test_ss_calculator_engine.py new file mode 100644 index 00000000000..b7605d71bd6 --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_calculator_engine.py @@ -0,0 +1,501 @@ +"""Simulation API integration for supplied Social Security records. + +The pure services carry the statutory examples/properties. These small model +cases exercise string/object inputs, float32 money restoration, mixed source +vectors, parameter scheduling and annual-versus-monthly output adapters. +Simulation reuses the default runtime system; only parameter reforms detach it. +""" + +from copy import deepcopy +from decimal import Decimal, ROUND_FLOOR + +import numpy as np +import pytest + +from policyengine_us import Simulation +from policyengine_us.tools.social_security.cola import read_parameter_events + + +def _simulation(*, situation, reform=None): + """Apply parameter-only variants to an isolated, processed runtime clone. + + Supplying the prepared system avoids reconstructing the full country for + every variant. Keep the reform argument as the Simulation baseline marker; + Core does not apply it again when a tax-benefit system is supplied. + """ + if reform is None: + return Simulation(situation=situation) + isolated = Simulation.default_tax_benefit_system_instance.clone() + isolated.apply_reform_set(reform) + return Simulation( + situation=situation, + tax_benefit_system=isolated, + reform=reform, + ) + + +def _record(worker_id="worker", **overrides): + values = { + "ss_calculator_source": "pia", + "ss_calculator_worker_id": worker_id, + "ss_calculator_birth_date": "1964-01-02", + "ss_calculator_entitlement_month": "2026-01", + "ss_calculator_eligibility_year": 2026, + "ss_calculator_supplied_pia": 1000, + "ss_calculator_claiming_factor": "1", + "ss_calculator_insured": True, + "ss_calculator_no_special_monthly_test": True, + "ss_calculator_no_prior_withholding_adjustment": True, + "ss_calculator_earnings_test_no_trigger": True, + } + values.update(overrides) + return values + + +def _situation(people): + members = list(people) + return { + "people": people, + "tax_units": {"tax_unit": {"members": members}}, + "families": {"family": {"members": members}}, + "spm_units": {"spm_unit": {"members": members}}, + "households": {"household": {"members": members}}, + } + + +def test_source_off_requires_no_record_fields_and_does_not_activate_amount(): + simulation = _simulation( + situation=_situation( + { + "missing": {}, + "unselected": { + "ss_calculator_source": "off", + "ss_calculator_supplied_aime": 5000, + "ss_calculator_supplied_pia": 2000, + }, + } + ) + ) + for variable, period in ( + ("ss_calculated_annual_payment", 2026), + ("ss_calculated_retirement", 2026), + ("ss_calculated_survivors", 2026), + ("ss_calculated_benefit", "2026-01"), + ("ss_calculated_payment", "2026-01"), + ): + np.testing.assert_array_equal(simulation.calculate(variable, period), [0, 0]) + + +def test_mixed_aime_pia_sources_preserve_explicit_zero_and_string_inputs(): + people = {} + for source, amount in (("aime", 0), ("pia", 0), ("aime", 3000), ("pia", 1606.7)): + name = f"{source}_{amount}" + people[name] = _record( + name, + ss_calculator_source=source, + ss_calculator_birth_date="1961-01-02", + ss_calculator_entitlement_month="2023-01", + ss_calculator_eligibility_year=2023, + **{"ss_calculator_supplied_" + source: amount}, + ) + simulation = _simulation(situation=_situation(people)) + # SSA Supplement2023 AppendixD's AIME3000->PIA1606.70 also exercises + # restoration of the supplied float32 PIA to its original dime value. + np.testing.assert_allclose( + simulation.calculate("ss_calculated_eligibility_pia", "2023-01"), + [0, 0, 1606.7, 1606.7], + atol=0.0001, + ) + np.testing.assert_array_equal( + simulation.calculate("ss_calculated_payment", "2023-01"), [0, 0, 0, 0] + ) + np.testing.assert_array_equal( + simulation.calculate("ss_calculated_payment", "2023-02"), [0, 0, 1606, 1606] + ) + np.testing.assert_array_equal( + simulation.calculate("ss_calculated_retirement", 2023), + [0, 0, 1606 * 11, 1606 * 11], + ) + + +@pytest.mark.parametrize("source", ["aime", "pia"]) +def test_selected_source_requires_an_amount_distinct_from_supplied_zero(source): + record = _record(ss_calculator_source=source) + record.pop("ss_calculator_supplied_" + source, None) + simulation = _simulation(situation=_situation({"worker": record})) + with pytest.raises(ValueError, match="Supplied (AIME|eligibility PIA) must"): + simulation.calculate("ss_calculated_payment", "2026-02") + + +def test_fractional_aime_reaches_service_validation_without_input_truncation(): + simulation = _simulation( + situation=_situation( + { + "worker": _record( + ss_calculator_source="aime", + ss_calculator_supplied_aime=3000.5, + ) + } + ) + ) + with pytest.raises(ValueError, match="whole monthly dollar"): + simulation.calculate("ss_calculated_payment", "2026-02") + + +def test_couple_uses_distinct_own_records_and_keeps_public_inputs_independent(): + people = { + "first": _record( + "first-worker", + ss_calculator_supplied_pia=1000.1, + ss_calculator_entitlement_month="2026-07", + social_security_retirement={2026: 9000}, + ), + "second": _record( + "second-worker", + ss_calculator_supplied_pia=2000.2, + ss_calculator_entitlement_month="2026-07", + ss_calculator_claiming_factor="0.7", + social_security_retirement={2026: 12000}, + ), + } + situation = _situation(people) + situation["marital_units"] = {"couple": {"members": list(people)}} + simulation = _simulation(situation=situation) + np.testing.assert_allclose( + simulation.calculate("ss_calculated_eligibility_pia", "2026-07"), + [1000.1, 2000.2], + atol=0.0002, + ) + np.testing.assert_array_equal( + simulation.calculate("ss_calculated_payment", "2026-08"), [1000, 1400] + ) + np.testing.assert_array_equal( + simulation.calculate("ss_calculated_annual_payment", 2026), [5000, 7000] + ) + np.testing.assert_array_equal( + simulation.calculate("social_security_retirement", 2026), [9000, 12000] + ) + np.testing.assert_array_equal( + simulation.calculate("ss_calculated_survivors", 2026), [0, 0] + ) + + +def test_exported_couple_checks_compose_with_benefit_tax_thresholds_and_niit(): + # Before the public source-selector integration, the documented one-step + # wiring exports each own record's checks to the existing public input. + calculated = _simulation( + situation=_situation( + { + "first": _record("first-worker", ss_calculator_supplied_pia=1000), + "second": _record("second-worker", ss_calculator_supplied_pia=2000), + } + ) + ).calculate("ss_calculated_retirement", 2026) + np.testing.assert_array_equal(calculated, [11000, 22000]) + people = { + name: { + "age": {2026: 62}, + "is_tax_unit_head": {2026: index == 0}, + "is_tax_unit_spouse": {2026: index == 1}, + "social_security_retirement": {2026: float(calculated[index])}, + "taxable_interest_income": {2026: (20000, 10000)[index]}, + } + for index, name in enumerate(("first", "second")) + } + situation = _situation(people) + situation["tax_units"]["tax_unit"]["filing_status"] = {2026: "JOINT"} + # This interest-only witness takes the standard deduction in every case. + # Declare that election so this integration test does not run the model's + # unrelated state/federal itemization search for each parameter variant. + situation["tax_units"]["tax_unit"]["tax_unit_itemizes"] = {2026: False} + situation["marital_units"] = {"couple": {"members": list(people)}} + benefit_thresholds = { + "gov.irs.social_security.taxability.threshold.base.main.JOINT": { + "2026-01-01": 64000 + }, + "gov.irs.social_security.taxability.threshold.adjusted_base.main.JOINT": { + "2026-01-01": 88000 + }, + } + investment_threshold = { + "gov.irs.investment.net_investment_income_tax.threshold.JOINT": { + "2026-01-01": 35000 + } + } + cases = { + "baseline": ({}, 8125, 38125, 0), + "benefit_thresholds": (benefit_thresholds, 0, 30000, 0), + "investment_threshold": (investment_threshold, 8125, 38125, 118.75), + "combined": ({**benefit_thresholds, **investment_threshold}, 0, 30000, 0), + } + income_taxes = {} + for name, (reform, taxable_benefits, agi, investment_tax) in cases.items(): + simulation = _simulation(situation=deepcopy(situation), reform=reform or None) + np.testing.assert_array_equal( + simulation.calculate("social_security_retirement", 2026), calculated + ) + assert ( + simulation.calculate("tax_unit_social_security_for_taxability", 2026)[0] + == 33000 + ) + assert ( + simulation.calculate("tax_unit_taxable_social_security", 2026)[0] + == taxable_benefits + ) + assert simulation.calculate("adjusted_gross_income", 2026)[0] == agi + assert simulation.calculate("net_investment_income", 2026)[0] == 30000 + assert simulation.calculate("net_investment_income_tax", 2026)[ + 0 + ] == pytest.approx(investment_tax) + income_taxes[name] = simulation.calculate("income_tax", 2026)[0] + # Provisional income46500: .85*(46500-44000)+6000=8125 taxable. + # Lowering existing NIIT's joint threshold gives .038*(38125-35000) + # =118.75; excluding these benefits from AGI removes that excess too. + assert income_taxes["benefit_thresholds"] < income_taxes["baseline"] + assert income_taxes["combined"] < income_taxes["investment_threshold"] + + +def test_annual_earnings_input_is_allocated_to_entitlement_months_before_checks(): + simulation = _simulation( + situation=_situation( + { + "worker": _record( + ss_calculator_earnings_test_no_trigger=False, + ss_calculator_annual_earnings={2026: 26480}, + ) + } + ) + ) + # $2,000 above the 2026 exemption gives a $1,000 annual deduction, + # allocated to January entitlement (the February check). + assert ( + simulation.calculate("ss_calculated_earnings_test_reduction", 2026)[0] == 1000 + ) + assert simulation.calculate("ss_calculated_benefit", "2026-01")[0] == 0 + assert simulation.calculate("ss_calculated_payment", "2026-02")[0] == 0 + assert simulation.calculate("ss_calculated_payment", "2026-03")[0] == 1000 + assert simulation.calculate("ss_calculated_annual_entitlement", 2026)[0] == 11000 + assert simulation.calculate("ss_calculated_annual_payment", 2026)[0] == 10000 + + +def test_s770_parameter_schedule_reaches_old_cohort_at_2026(): + simulation = _simulation( + situation=_situation( + { + "worker": _record( + ss_calculator_source="aime", + ss_calculator_supplied_aime=5000, + ss_calculator_birth_date="1960-01-02", + ss_calculator_entitlement_month="2020-01", + ss_calculator_eligibility_year=2020, + ) + } + ), + reform={"gov.contrib.congress.s770.section_2.in_effect": {"2026-01-01": True}}, + ) + assert simulation.calculate("ss_calculated_eligibility_pia", "2025-01")[ + 0 + ] == pytest.approx(2156.8) + assert simulation.calculate("ss_calculated_eligibility_pia", "2026-01")[ + 0 + ] == pytest.approx(2313.6) + # Section2(c)(1) first changes January2026 entitlement, paid in February. + # January's check still pays December2025 entitlement at baseline PIA. + assert simulation.calculate("ss_calculated_payment", "2026-01")[0] == 2734 + assert simulation.calculate("ss_calculated_payment", "2026-02")[0] == 2933 + + +def test_turning_70_releases_deferred_claim_year_credits_in_the_birthday_month(): + simulation = _simulation( + situation=_situation( + { + "worker": _record( + ss_calculator_birth_date="1956-04-02", + ss_calculator_eligibility_year=2018, + ss_calculator_entitlement_month="2026-02", + ss_calculator_claiming_factor="", + ) + } + ) + ) + # https://secure.ssa.gov/poms.nsf/lnx/0300615690 + # Before70 the claim-year delayed credits wait; attaining70 + # in April releases the final claim-year credit immediately. Sequential + # eligibility2018 COLAs produce PIA1324 in2026. January credits41months + # give1324*(1+41/150)->1685; all42credits give1324*1.28->1694. + assert simulation.calculate("ss_calculated_benefit", "2026-03")[0] == 1685 + assert simulation.calculate("ss_calculated_benefit", "2026-04")[0] == 1694 + assert simulation.calculate("ss_calculated_payment", "2026-04")[0] == 1685 + assert simulation.calculate("ss_calculated_payment", "2026-05")[0] == 1694 + + +def test_next_january_reform_is_included_in_december_entitlement_row(): + simulation = _simulation( + situation=_situation({"worker": _record()}), + reform={"gov.contrib.congress.s770.section_2.in_effect": {"2027-01-01": True}}, + ) + assert simulation.calculate("ss_calculated_payment", "2026-12")[0] == 1000 + # PIA1000 implies AIME1000/.9; .95 factor ->1055.5 after dime + # truncation, then December2026 COLA3.6% ->1093.4 ->1093 check. + assert simulation.calculate("ss_calculated_benefit", "2026-12")[0] == 1093 + assert simulation.calculate("ss_calculated_payment", "2027-01")[0] == 1093 + assert simulation.calculate("ss_calculated_annual_entitlement", 2026)[0] == 12093 + assert simulation.calculate("ss_calculated_annual_payment", 2026)[0] == 11000 + + +def test_joint_cola_withholding_pp_change_and_payment_factors_apply_once(): + situation = _situation( + { + "with_cola": _record("with-cola"), + "withheld": _record( + "withheld-cola", ss_calculator_withhold_cola={2027: True} + ), + } + ) + simulation = _simulation( + situation=situation, + reform={ + "gov.contrib.ssa.benefit_levers.cola.pp_change": {"2027-01-01": 0.0015}, + "gov.contrib.ssa.benefit_levers.cola.start_year": {"2027-01-01": 2027}, + "gov.contrib.ssa.benefit_levers.cola.withholding_enabled": { + "2027-01-01": True + }, + "gov.contrib.ssa.benefit_levers.across_the_board.rate": {"2027-01-01": 0.1}, + "gov.contrib.ssa.benefit_levers.across_the_board.start_year": { + "2027-01-01": 2027 + }, + "gov.contrib.ssa.benefit_levers.payable.share": {"2027-01-01": 0.8}, + }, + ) + # Joint COLA is3.6%+.15%=3.75% or zero when withheld. Dime-rounded + # PIA1037.5/1000, then benefit factors1.10*.80 ->913/880 whole dollars. + np.testing.assert_array_equal( + simulation.calculate("ss_calculated_payment", "2027-01"), [913, 880] + ) + + +def test_common_cola_alternative_rate_effective_window_and_withholding_gate(): + people = { + "worker": _record(ss_calculator_withhold_cola={2027: True}), + } + simulation = _simulation( + situation=_situation(people), + reform={ + "gov.contrib.ssa.benefit_levers.cola.alternative_rate": { + "2027-01-01": 0.02 + }, + "gov.contrib.ssa.benefit_levers.cola.pp_change": {"2027-01-01": 0.0015}, + # The effective-date selector overrides the unused start-year + # selector, and the end year includes this first affected event. + "gov.contrib.ssa.benefit_levers.cola.effective_year": {"2027-01-01": 2026}, + "gov.contrib.ssa.benefit_levers.cola.effective_month": {"2027-01-01": 12}, + "gov.contrib.ssa.benefit_levers.cola.end_year": {"2027-01-01": 2027}, + }, + ) + # Withholding stays disabled, so the person's decision cannot suppress + # the alternative2%+.15% COLA: PIA1000 ->1021.5 ->1021 check. + assert simulation.calculate("ss_calculated_payment", "2027-01")[0] == 1021 + # End-year gating changes no later COLA; the earlier level persists. + parameters = simulation.tax_benefit_system.parameters + next_rate = next( + event.rate + for event in read_parameter_events(parameters, 2028) + if event.payment_month == "2028-01" + ) + expected = int( + (Decimal("1021.5") * (1 + next_rate)).quantize( + Decimal(".1"), rounding=ROUND_FLOOR + ) + ) + assert simulation.calculate("ss_calculated_payment", "2028-01")[0] == expected + + +def test_absolute_alternative_cola_replaces_1999_original_and_corrected_rate(): + simulation = _simulation( + situation=_situation( + { + "worker": _record( + ss_calculator_birth_date="1937-01-02", + ss_calculator_eligibility_year=1999, + ss_calculator_entitlement_month="1999-01", + ) + } + ), + reform={ + "gov.contrib.ssa.benefit_levers.cola.alternative_rate": { + "2000-01-01": 0.03 + }, + "gov.contrib.ssa.benefit_levers.cola.start_year": {"2000-01-01": 2000}, + "gov.contrib.ssa.benefit_levers.cola.end_year": {"2000-01-01": 2000}, + }, + ) + assert simulation.calculate("ss_calculated_payment", "2000-01")[0] == 1030 + # The later historical correction must retain the supplied absolute3% + # rate rather than reconstructing the statutory2.5% COLA for1999. + assert simulation.calculate("ss_calculated_payment", "2001-08")[0] == 1066 + + +def _survivor(): + return _record( + "deceased-worker", + ss_calculator_source="survivor", + ss_calculator_birth_date="1950-01-02", + ss_calculator_eligibility_year=0, + ss_calculator_entitlement_month="2025-09", + ss_calculator_claiming_factor="", + ss_calculator_worker_birth_year=1970, + ss_calculator_worker_birth_date="1970-06-15", + ss_calculator_death_year=2025, + ss_calculator_death_date="2025-08-12", + ss_calculator_basis_provenance="Supplied exact worker birth and death dates", + ss_calculator_no_prior_disability=True, + ss_calculator_ordinary_non_windex=True, + ss_calculator_monthly_amount=2375, + ss_calculator_valuation_month="2026-01", + ss_calculator_composite_ratio="1", + ss_calculator_ratio_description="Supplied composite including survivor reductions", + ss_calculator_nonbinding_rib_lim=True, + ss_calculator_nonbinding_family_maximum=True, + ss_calculator_no_dual_entitlement=True, + ss_calculator_no_earnings_test_at_valuation=True, + ) + + +def test_survivor_engine_derives_death_benchmark_and_first_cola(): + simulation = _simulation(situation=_situation({"survivor": _survivor()})) + # Death-year2025 rather than hypothetical age62 year2032 supplies + # the benchmark and December2025 COLA first paid January2026. + assert simulation.calculate("ss_calculated_payment", "2025-12")[0] == 2310 + assert simulation.calculate("ss_calculated_payment", "2026-01")[0] == 2375 + assert simulation.calculate("ss_calculated_retirement", 2026)[0] == 0 + assert simulation.calculate("ss_calculated_survivors", 2026)[0] == 2375 * 12 + assert simulation.calculate("ss_calculated_pia_lower", 2026)[0] == pytest.approx( + 2310.4 + ) + + +def test_survivor_selected_source_requires_a_supplied_monthly_amount(): + record = _survivor() + record.pop("ss_calculator_monthly_amount") + simulation = _simulation(situation=_situation({"survivor": record})) + with pytest.raises(ValueError, match="Supply a nonnegative gross monthly payment"): + simulation.calculate("ss_calculated_payment", "2026-02") + + +@pytest.mark.parametrize("increase,expected", [(False, 2371.7), (True, 2510.7)]) +def test_survivor_engine_s770_flag_changes_bend_increase_only(increase, expected): + simulation = _simulation( + situation=_situation({"survivor": deepcopy(_survivor())}), + reform={ + "gov.contrib.congress.s770.section_2.in_effect": {"2026-01-01": True}, + "gov.contrib.congress.s770.section_2.recompute_pre2026_death_before_eligibility": { + "2026-01-01": increase + }, + }, + ) + # Supplied-dollar inversion recovers lower-endpoint eligibility PIA2310.4. + # Factor-only gain=.05*1226=61.3; factor+bend gain=.1634*1226=200.3284. + assert simulation.calculate("ss_calculated_eligibility_pia", "2026-01")[ + 0 + ] == pytest.approx(expected) + assert simulation.calculate("ss_calculated_payment", "2026-01")[0] == 2375 diff --git a/policyengine_us/tests/unit/test_ss_household_calculator.py b/policyengine_us/tests/unit/test_ss_household_calculator.py new file mode 100644 index 00000000000..634489c18ba --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_household_calculator.py @@ -0,0 +1,990 @@ +"""Acceptance tests for identified supplied-record household calculations. + +SSA examples are cited locally. Synthetic cases keep eligibility PIA, COLAs, +claiming, earnings testing and check-month timing independently observable. +""" + +from dataclasses import replace +from datetime import date +from decimal import Decimal +from fractions import Fraction + +import pytest +from hypothesis import given, settings, strategies as st + +from policyengine_us.tools.social_security.cola import ColaEvent, apply_colas +from policyengine_us.tools.social_security.household import ( + BenefitPolicies, + SuppliedRecord, + SurvivorBasis, + calculate_year, + claiming_factor, + full_retirement_age_months, +) +from policyengine_us.tools.social_security.pia import FormulaPath + + +D = Decimal +BENDS = (960, 5785) + + +def retirement(**overrides): + values = dict( + source="pia", + worker_id="worker-1", + birth_date=date(1960, 1, 2), + eligibility_year=2022, + entitlement_month="2022-01", + insured=True, + pia=D(1000), + no_special_monthly_test=True, + no_prior_withholding_adjustment=True, + earnings_test_no_trigger=True, + ) + values.update(overrides) + return SuppliedRecord(**values) + + +def survivor_basis(**overrides): + values = dict( + worker_birth_year=1970, + death_year=2020, + worker_birth_date=date(1970, 6, 15), + death_date=date(2020, 8, 12), + provenance="Supplied worker birth and death dates", + no_prior_disability=True, + ordinary_non_windex=True, + ) + values.update(overrides) + return SurvivorBasis(**values) + + +def survivor(**overrides): + values = dict( + source="survivor", + worker_id="deceased-worker-1", + birth_date=date(1950, 1, 2), + entitlement_month="2021-01", + insured=True, + survivor=survivor_basis(), + monthly_amount=D(2000), + valuation_month="2025-01", + composite_ratio=D(1), + ratio_description="Supplied composite includes all survivor reductions and delayed credits", + nonbinding_rib_lim=True, + nonbinding_family_maximum=True, + no_dual_entitlement=True, + no_earnings_test_at_valuation=True, + no_special_monthly_test=True, + no_prior_withholding_adjustment=True, + earnings_test_no_trigger=True, + ) + values.update(overrides) + return SuppliedRecord(**values) + + +def compute(record, year=2026, **kwargs): + return calculate_year(record, year, bend_points=BENDS, **kwargs) + + +def row_for(result, entitlement_month): + return next( + row for row in result.ledger if row.entitlement_month == entitlement_month + ) + + +def test_ssa_published_supplied_aime_and_pia_claim_at_62(): + # 2023 Supplement Appendix D: E2023 AIME3000 -> PIA1606.70; + # claiming at62 with FRA67 -> monthly1124 after statutory rounding. + # https://www.ssa.gov/policy/docs/statcomps/supplement/2023/apnd.html + record = retirement( + source="aime", + aime=3000, + birth_date=date(1961, 1, 2), + eligibility_year=2023, + entitlement_month="2023-01", + ) + direct = calculate_year(record, 2023, bend_points=(1115, 6721)) + supplied = calculate_year( + replace(record, source="pia", pia=D("1606.7")), 2023, bend_points=(1115, 6721) + ) + assert row_for(direct, "2023-01").eligibility_pia == D("1606.7") + assert direct.entitlement_total == D(1124 * 12) + assert direct.payment_total == D(1124 * 11) + assert direct.ledger == supplied.ledger + + +@pytest.mark.parametrize("source", ["aime", "pia"]) +def test_explicit_source_selector_preserves_supplied_zero(source): + record = retirement( + source=source, + aime=0 if source == "aime" else 5000, + pia=0 if source == "pia" else 1000, + ) + result = compute( + record, formula_path=FormulaPath(s770=True), recompute_mode="retroactive" + ) + assert result.entitlement_total == 0 + assert result.payment_total == 0 + assert all(row.eligibility_pia == 0 for row in result.ledger) + assert result.inferred_aime_interval is None + + +@pytest.mark.parametrize( + "path", + [ + FormulaPath(effective_year=2032, bend_point_multipliers=(D("1.1"), 1)), + FormulaPath( + factor_start_year=2032, factor_values=(D(".9"), D(".32"), D(".05")) + ), + FormulaPath(full_price_indexing_start_year=2032), + FormulaPath(progressive_price_indexing_start_year=2032), + FormulaPath(s770=True), + FormulaPath(effective_year=2026), + ], +) +def test_inactive_or_identity_pia_paths_preserve_supplied_pia_without_inversion(path): + # A cohort-only reform cannot require inference for this 2022 cohort. + record = retirement(pia=D("1000.1")) + baseline = compute(record) + result = compute(record, formula_path=path) + assert result.ledger == baseline.ledger + assert result.inferred_aime_interval is None + + +@pytest.mark.parametrize("source", ["aime", "pia", "survivor"]) +def test_cola_iterators_preserve_the_same_history_for_every_ledger_read(source): + record = ( + survivor(monthly_amount=D(2200)) + if source == "survivor" + else retirement(source=source, aime=3000) + ) + events = [ + ColaEvent("2020-12", "2021-01", D(".1")), + ColaEvent("2022-12", "2023-01", D(".02")), + ] + assert compute(record, cola_events=iter(events)) == compute( + record, cola_events=events + ) + + +@pytest.mark.parametrize( + "age,year,factor,monthly", + [ + (62, 2022, Fraction(7, 10), 700), + (65, 2025, Fraction(13, 15), 866), + (67, 2027, Fraction(1), 1000), + (70, 2030, Fraction(31, 25), 1240), + ], +) +def test_exact_claiming_months_62_65_fra_70(age, year, factor, monthly): + record = retirement(entitlement_month=f"{year}-01") + assert claiming_factor(record.birth_date, record.entitlement_month) == factor + assert compute(record, year).entitlement_total == D(monthly * 12) + + +def test_claiming_uses_months_and_birth_cohort_fra(): + assert full_retirement_age_months(date(1956, 4, 2)) == 796 + assert full_retirement_age_months(date(1960, 1, 2)) == 804 + # One month early is 1 - 5/9 of one percent, not a whole-year age band. + assert claiming_factor(date(1960, 1, 2), "2026-12") == Fraction(179, 180) + + +def test_ssa_published_delayed_retirement_credit_example(): + # https://www.ssa.gov/policy/docs/statcomps/supplement/2023/apnd.html + # DOB April1956, FRA August2022, claim January2023, five DRC months. + record = retirement( + birth_date=date(1956, 4, 2), + eligibility_year=2018, + entitlement_month="2023-01", + pia=D("1553.9"), + ) + result = compute(record, 2023) + assert row_for(result, "2023-01").payable_benefit == D(1605) + + +def test_midyear_claim_defers_current_calendar_year_drcs_until_january(): + # https://secure.ssa.gov/poms.nsf/lnx/0300615690 + record = retirement( + birth_date=date(1956, 4, 2), + eligibility_year=2018, + entitlement_month="2023-07", + pia=D("1500"), + ) + current, following = compute(record, 2023), compute(record, 2024) + assert row_for(current, "2023-07").payable_benefit == D(1550) + assert row_for(following, "2024-01").payable_benefit == D(1610) + + +def test_partial_year_distinguishes_entitlement_month_and_check_month(): + record = retirement( + birth_date=date(1964, 1, 2), + eligibility_year=2026, + entitlement_month="2026-07", + supplied_claiming_factor=D(1), + ) + events = [ColaEvent("2026-12", "2027-01", D(".1"))] + current = compute(record, 2026, cola_events=events) + following = compute(record, 2027, cola_events=events) + assert current.entitlement_total == 6100 # July-Nov1000; Dec1100. + assert current.payment_total == 5000 # Five checks August-December. + assert following.payment_total == 13200 + assert row_for(current, "2026-12").payment_month == "2027-01" + + +def test_colas_from_eligibility_include_years_before_claiming(): + record = retirement(entitlement_month="2027-01", supplied_claiming_factor=D(1)) + events = [ + ColaEvent("2022-12", "2023-01", D(".1")), + ColaEvent("2023-12", "2024-01", D(".1")), + ] + result = compute(record, 2027, cola_events=events) + assert row_for(result, "2027-01").cola_pia == 1210 + assert result.entitlement_total == 14520 + + +def test_insured_status_is_an_explicit_input(): + result = compute(retirement(insured=False)) + assert result.entitlement_total == result.payment_total == 0 + + +def test_supplied_claiming_factor_is_used_once(): + result = compute(retirement(supplied_claiming_factor=D(".8"))) + assert result.entitlement_total == 9600 + + +def test_known_pia_and_aime_use_the_same_reformed_service(): + known = retirement(pia=D(1000), supplied_claiming_factor=D(".7")) + direct = replace(known, source="aime", aime=1385) + options = dict(formula_path=FormulaPath(s770=True), recompute_mode="retroactive") + assert compute(known, **options).ledger == compute(direct, **options).ledger + assert row_for(compute(known, **options), "2026-01").eligibility_pia == D("1156.8") + + +def test_every_month_is_zero_in_year_before_commencement(): + result = compute(retirement(entitlement_month="2030-01")) + assert result.entitlement_total == result.payment_total == 0 + assert all(row.payable_benefit == 0 for row in result.ledger) + + +def test_retired_couple_keeps_independent_worker_records(): + first = retirement( + worker_id="first-worker", + entitlement_month="2027-01", + supplied_claiming_factor=D(1), + ) + second = retirement( + worker_id="second-worker", + pia=D(1500), + entitlement_month="2027-01", + supplied_claiming_factor=D(".8"), + ) + assert compute(first, 2027).entitlement_total == 12000 + assert compute(second, 2027).entitlement_total == 14400 + assert ( + compute(first, 2027).entitlement_total + compute(second, 2027).entitlement_total + == 26400 + ) + + +def test_combined_pia_cola_across_board_and_payable_policies_apply_once(): + record = retirement( + source="aime", + aime=5000, + birth_date=date(1958, 1, 2), + eligibility_year=2020, + entitlement_month="2020-01", + supplied_claiming_factor=D(".7"), + ) + event = ColaEvent("2020-12", "2021-01", D(".1")) + policies = BenefitPolicies( + cola_rates={"2021-01": D(".11")}, + across_the_board={2026: D(".1")}, + payable_share={2026: D(".8")}, + ) + result = compute( + record, + formula_path=FormulaPath(s770=True), + cola_events=[event], + policies=policies, + recompute_mode="retroactive", + ) + row = row_for(result, "2026-01") + assert row.eligibility_pia == D("2313.6") + assert row.cola_pia == D("2568.0") + assert row.payable_benefit == 1581 # 2568 x .7 x 1.1 x .8 ->1581.888. + + +def test_joint_cola_withholding_bypasses_a_simultaneous_cola_increase(): + record = retirement(entitlement_month="2027-01", supplied_claiming_factor=D(1)) + event = ColaEvent("2026-12", "2027-01", D(".02")) + result = compute( + record, + 2027, + cola_events=[event], + policies=BenefitPolicies(cola_rates={"2027-01": D(0)}), + ) + assert result.entitlement_total == 12000 + + +def test_complete_payable_cut_is_valid_and_negative_benefits_are_rejected(): + record = retirement(supplied_claiming_factor=D(1)) + assert ( + compute( + record, policies=BenefitPolicies(payable_share={2026: D(0)}) + ).payment_total + == 0 + ) + assert ( + compute( + record, policies=BenefitPolicies(across_the_board={2026: D(-1)}) + ).payment_total + == 0 + ) + for policies in ( + BenefitPolicies(payable_share={2026: D("1.01")}), + BenefitPolicies(payable_share={2026: D("-.01")}), + BenefitPolicies(across_the_board={2026: D("-1.01")}), + ): + with pytest.raises(ValueError): + compute(record, policies=policies) + + +def test_ssa_published_under_fra_earnings_test(): + # https://www.ssa.gov/benefits/retirement/planner/whileworking.html + record = retirement( + birth_date=date(1964, 1, 2), + eligibility_year=2026, + entitlement_month="2026-01", + pia=D(800), + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + result = compute(record, earnings={2026: 33400}, lower_exempt={2026: 24480}) + assert result.earnings_test_reduction == 4460 + assert result.entitlement_total == 5140 + assert all( + row.earnings_test_reduction <= row.gross_benefit for row in result.ledger + ) + + +def test_ssa_published_fra_year_earnings_test_counts_only_pre_fra_months(): + # https://www.ssa.gov/benefits/retirement/planner/whileworking.html + # Birth October1959 yields retirement FRA66y10m in August2026. + record = retirement( + birth_date=date(1959, 10, 2), + eligibility_year=2021, + entitlement_month="2026-01", + pia=D(800), + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + result = compute( + record, + earnings={2026: 1_000_000}, + pre_fra_earnings={2026: 66000}, + higher_exempt={2026: 65160}, + ) + assert result.earnings_test_reduction == 280 + assert result.entitlement_total == 9320 + assert ( + sum( + row.payable_benefit + for row in result.ledger + if "2026-08" <= row.entitlement_month <= "2026-12" + ) + == 4000 + ) + + +def test_earnings_test_floors_work_deduction_before_monthly_allocation(): + # RS02501.080 drops cents from excess earnings /2 or /3. + # https://secure.ssa.gov/poms.nsf/links/0302501080 + record = retirement( + birth_date=date(1964, 1, 2), + eligibility_year=2026, + entitlement_month="2026-01", + pia=D(800), + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + result = compute(record, earnings={2026: 24481}, lower_exempt={2026: 24480}) + assert result.earnings_test_reduction == 0 + assert result.entitlement_total == 9600 + + +def test_earnings_after_retirement_fra_do_not_reduce_benefits(): + record = retirement( + entitlement_month="2027-01", + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + assert compute(record, 2027, earnings={2027: 1_000_000}).entitlement_total == 12000 + + +def test_previous_december_withholding_and_request_order_are_consistent(): + record = retirement( + birth_date=date(1964, 1, 2), + eligibility_year=2026, + entitlement_month="2026-01", + pia=D(800), + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + inputs = dict( + earnings={2026: 43080, 2027: 0}, lower_exempt={2026: 24480, 2027: 24480} + ) + later = compute(record, 2027, **inputs) + earlier = compute(record, 2026, **inputs) + assert row_for(earlier, "2026-12") == row_for(later, "2026-12") + assert later.payment_total == 9100 # December2026 remaining check300 +11x800. + + +def test_no_earnings_test_assertion_rejects_conflicting_observed_earnings(): + with pytest.raises(ValueError, match="conflicts"): + compute(retirement(), earnings={2025: 30000}, lower_exempt={2025: 20000}) + + +@pytest.mark.parametrize( + "assertion", ["no_special_monthly_test", "no_prior_withholding_adjustment"] +) +def test_restricted_worker_route_requires_special_rule_assertions(assertion): + with pytest.raises(ValueError, match="Assert"): + compute(retirement(**{assertion: False})) + + +@pytest.mark.parametrize( + "changes", + [ + {"source": "unknown"}, + {"worker_id": ""}, + {"source_basis": "already_reformed"}, + {"source": "aime", "aime": D("1.5")}, + {"source": "aime", "aime": -1}, + {"pia": D("1.05")}, + {"pia": -1}, + {"eligibility_year": 2023}, + {"supplied_claiming_factor": D(0)}, + ], +) +def test_invalid_or_ambiguous_retirement_inputs_fail(changes): + with pytest.raises(ValueError): + compute(retirement(**changes)) + + +def test_first_reduced_retirement_month_and_january_1_cohort(): + record = retirement( + birth_date=date(1964, 6, 3), eligibility_year=2026, entitlement_month="2026-06" + ) + with pytest.raises(ValueError, match="first eligible month"): + compute(record) + assert compute(replace(record, entitlement_month="2026-07")).entitlement_total > 0 + january = retirement( + birth_date=date(1964, 1, 1), eligibility_year=2025, entitlement_month="2026-01" + ) + assert january.benchmark() == 2025 + assert full_retirement_age_months(date(1960, 1, 1)) == 802 + + +def test_rejects_retirement_benchmark_before_1983(): + with pytest.raises(ValueError, match="before 1983"): + compute( + retirement( + birth_date=date(1920, 1, 2), + eligibility_year=1982, + entitlement_month="1982-01", + ) + ) + + +def test_survivor_authoritative_and_derived_benchmarks(): + basis = survivor_basis() + assert basis.benchmark() == (2020, True) + assert replace( + basis, + authoritative_year=2018, + no_prior_disability=False, + provenance="Authoritative computation year", + ).benchmark() == (2018, True) + after62 = survivor_basis( + worker_birth_year=1950, worker_birth_date=date(1950, 6, 15), death_year=2020 + ) + assert after62.benchmark() == (2012, False) + + +def test_survivor_january_1_birth_and_same_year_date_disambiguation(): + basis = survivor_basis( + worker_birth_year=1964, + worker_birth_date=date(1964, 1, 1), + death_year=2026, + death_date=date(2026, 6, 15), + ) + assert basis.benchmark() == (2025, False) + same = survivor_basis( + worker_birth_year=1964, + worker_birth_date=date(1964, 6, 15), + death_year=2026, + death_date=date(2026, 6, 13), + ) + assert same.benchmark() == (2026, True) + assert replace(same, death_date=date(2026, 6, 14)).benchmark() == (2026, False) + + +def test_survivor_year_only_fallback_requires_stated_assumption_and_same_year_assertion(): + basis = survivor_basis(worker_birth_date=None, death_date=None) + with pytest.raises(ValueError, match="not-January-1"): + basis.benchmark() + assert replace(basis, year_only_not_january_1=True).benchmark() == (2020, True) + same = replace(basis, worker_birth_year=1958, year_only_not_january_1=True) + with pytest.raises(ValueError, match="Same-year"): + same.benchmark() + assert replace(same, same_year_death_before_62=True).benchmark() == (2020, True) + + +@pytest.mark.parametrize( + "changes,match", + [ + ({"no_prior_disability": False}, "authoritative"), + ({"ordinary_non_windex": False}, "WINDEX"), + ({"provenance": ""}, "provenance"), + ({"death_year": 1969, "death_date": None}, "precede birth"), + ({"worker_birth_year": 1969}, "disagree"), + ({"death_year": 2019}, "disagree"), + ({"authoritative_year": 1982}, "before 1983"), + ], +) +def test_survivor_scope_and_benchmark_rejections(changes, match): + with pytest.raises(ValueError, match=match): + survivor_basis(**changes).benchmark() + + +def test_survivor_death_based_cola_origin_and_composite_ratio_once(): + event = ColaEvent("2020-12", "2021-01", D(".1")) + record = survivor( + monthly_amount=D(880), composite_ratio=D(".8"), valuation_month="2021-02" + ) + result = compute(record, cola_events=[event]) + assert result.eligibility_pia_interval == (D(1000), D("1001.2")) + assert row_for(result, "2026-01").cola_pia == 1100 + assert result.entitlement_total == 10560 + + +@pytest.mark.parametrize( + "field", + [ + "nonbinding_rib_lim", + "nonbinding_family_maximum", + "no_dual_entitlement", + "no_earnings_test_at_valuation", + ], +) +def test_survivor_requires_every_identification_assertion(field): + with pytest.raises(ValueError, match="Survivor inversion"): + compute(survivor(**{field: False})) + + +@pytest.mark.parametrize( + "changes", + [ + {"composite_ratio": D(0)}, + {"composite_ratio": D(-1)}, + {"ratio_description": ""}, + {"monthly_amount": D(-1)}, + {"valuation_month": "2020-12"}, + {"monthly_amount": D("2000.5")}, + {"supplied_claiming_factor": D("1.2")}, + ], +) +def test_survivor_rejects_ambiguous_or_inconsistent_amount_and_ratio(changes): + with pytest.raises(ValueError): + compute(survivor(**changes)) + + +@pytest.mark.parametrize( + "flag,expected_pia", [(False, D("2048.0")), (True, D("2156.8"))] +) +@pytest.mark.parametrize("death_year", [2020, 2025]) +def test_s770_pre2026_death_flag_changes_only_first_bend_increase( + flag, expected_pia, death_year +): + # M1 correction: factor-only gain .05*960=48; full raw gain + # .1634*960=156.864, then initial-PIA dime truncation. + record = survivor( + survivor=survivor_basis( + death_year=death_year, death_date=date(death_year, 8, 12) + ), + entitlement_month=f"{death_year}-09", + valuation_month=f"{death_year}-11", + ) + result = compute( + record, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + s770_survivor_bend_increase=flag, + ) + assert row_for(result, "2026-01").eligibility_pia == expected_pia + + +def test_s770_post2025_death_before62_does_not_use_pre2026_flag(): + record = survivor( + survivor=survivor_basis(death_year=2026, death_date=date(2026, 1, 15)), + entitlement_month="2026-02", + valuation_month="2026-04", + ) + off = compute( + record, + 2027, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + s770_survivor_bend_increase=False, + ) + on = compute( + record, + 2027, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + s770_survivor_bend_increase=True, + ) + assert off.ledger == on.ledger + assert row_for(off, "2027-01").eligibility_pia == D("2156.8") + + +def test_s770_death_after62_does_not_use_pre2026_death_before62_flag(): + record = survivor( + survivor=survivor_basis( + worker_birth_year=1950, worker_birth_date=date(1950, 6, 15) + ) + ) + off = compute( + record, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + s770_survivor_bend_increase=False, + ) + on = compute( + record, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + s770_survivor_bend_increase=True, + ) + assert off.ledger == on.ledger + assert row_for(off, "2026-01").eligibility_pia == D("2156.8") + + +@pytest.mark.parametrize( + "flag,expected_pia,expected_cola,expected_payment", + [ + (False, D("2048.0"), D("2341.3"), D(2060)), + (True, D("2156.8"), D("2465.8"), D(2169)), + ], +) +def test_survivor_other_levers_apply_independently_of_s770_flag( + flag, expected_pia, expected_cola, expected_payment +): + record = survivor(monthly_amount=D(2200)) + events = [ + ColaEvent("2020-12", "2021-01", D(".1")), + ColaEvent("2025-12", "2026-01", D(".02")), + ] + policies = BenefitPolicies( + cola_rates={"2021-01": D(".11"), "2026-01": D(".03")}, + across_the_board={2026: D(".1")}, + payable_share={2026: D(".8")}, + ) + result = compute( + record, + cola_events=events, + policies=policies, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + s770_survivor_bend_increase=flag, + ) + row = row_for(result, "2026-01") + assert row.eligibility_pia == expected_pia + assert row.cola_pia == expected_cola + assert row.payable_benefit == expected_payment + + +def test_sub_dollar_payment_exception_and_zero_survivor(): + record = retirement(pia=D(".9"), supplied_claiming_factor=D(1)) + assert row_for(compute(record), "2026-01").payable_benefit == D(".9") + zero = compute(survivor(monthly_amount=D(0))) + assert zero.entitlement_total == 0 + assert zero.eligibility_pia_interval == (D(0), D(".1")) + + +def test_historical_sub_dollar_entitlement_rejects_unmodeled_year_end_payments(): + # Before December 2006, SSA held sub-$1 benefits for manual year-end + # payment. The restricted ledger cannot represent those as monthly checks. + # https://secure.ssa.gov/poms.nsf/lnx/0300601020 + record = retirement( + birth_date=date(1940, 1, 2), + eligibility_year=2002, + entitlement_month="2006-11", + pia=D(".9"), + supplied_claiming_factor=D(1), + ) + with pytest.raises(ValueError, match="year-end manual payment timing"): + compute(record, 2006) + supported = compute(replace(record, entitlement_month="2006-12"), 2006) + assert row_for(supported, "2006-12").payable_benefit == D(".9") + assert supported.entitlement_total == D(".9") + assert supported.payment_total == 0 + + +def test_historical_sub_dollar_survivor_source_cannot_be_inverted_as_monthly_cash(): + record = survivor( + birth_date=date(1940, 1, 2), + survivor=survivor_basis( + worker_birth_year=1950, + worker_birth_date=date(1950, 6, 15), + death_year=2005, + death_date=date(2005, 8, 12), + ), + entitlement_month="2005-09", + valuation_month="2006-12", + monthly_amount=D(".9"), + ) + with pytest.raises(ValueError, match="year-end manual payment timing"): + compute(record) + supported = compute(replace(record, valuation_month="2007-01")) + assert supported.entitlement_total == D("10.8") + + +def test_historical_earnings_test_requires_explicit_no_trigger_assertion(): + # The earnings test before 2000 included ages and deduction rates that + # differ from this route's modern FRA-based computation. + record = retirement( + birth_date=date(1933, 1, 2), + eligibility_year=1995, + entitlement_month="1999-01", + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + with pytest.raises(ValueError, match="Earnings testing before 2000"): + compute(record, 1999) + assert ( + compute(replace(record, earnings_test_no_trigger=True), 1999).entitlement_total + == 12000 + ) + + +@settings(max_examples=40, deadline=None) +@given( + pia_dimes=st.integers(min_value=0, max_value=100_000), + claim_month=st.integers(min_value=1, max_value=12), +) +def test_property_benefits_are_zero_before_entitlement(pia_dimes, claim_month): + record = retirement( + pia=D(pia_dimes) / 10, + birth_date=date(1964, 1, 2), + eligibility_year=2026, + entitlement_month=f"2026-{claim_month:02d}", + ) + result = compute(record) + assert all( + row.payable_benefit == 0 + for row in result.ledger + if row.entitlement_month < record.entitlement_month + ) + + +@settings(max_examples=40, deadline=None) +@given( + monthly=st.integers(min_value=0, max_value=5000), + annual_earnings=st.integers(min_value=0, max_value=500_000), +) +def test_property_earnings_test_never_exceeds_benefit(monthly, annual_earnings): + record = retirement( + pia=D(monthly), + birth_date=date(1964, 1, 2), + eligibility_year=2026, + entitlement_month="2026-01", + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + result = compute( + record, earnings={2026: annual_earnings}, lower_exempt={2026: 24480} + ) + assert D(0) <= result.earnings_test_reduction <= D(monthly * 12) + assert all( + D(0) <= row.earnings_test_reduction <= row.gross_benefit + for row in result.ledger + ) + assert all(row.payable_benefit >= 0 for row in result.ledger) + + +@settings(max_examples=50, deadline=None) +@given( + pia_dimes=st.integers(min_value=100, max_value=100_000), + ratio_hundredths=st.integers(min_value=50, max_value=150), + rate_thousandths=st.integers(min_value=0, max_value=100), +) +def test_property_survivor_recovered_interval_reproduces_supplied_amount( + pia_dimes, ratio_hundredths, rate_thousandths +): + pia, ratio = D(pia_dimes) / 10, D(ratio_hundredths) / 100 + events = [ColaEvent("2020-12", "2021-01", D(rate_thousandths) / 1000)] + current_pia = apply_colas(pia, 2020, "2025-01", events) + supplied = D(int(current_pia * ratio)) + result = compute( + survivor(monthly_amount=supplied, composite_ratio=ratio), cola_events=events + ) + lower, upper = result.eligibility_pia_interval + assert lower <= pia < upper + assert D(int(apply_colas(lower, 2020, "2025-01", events) * ratio)) == supplied + assert row_for(result, "2026-01").payable_benefit == supplied + + +def test_age_70_releases_deferred_credits_in_the_claim_calendar_year(): + # RS00615.690: claim-year credits become effective at age70 even before + # the following January. Credits stop accruing when benefits commence. + # https://secure.ssa.gov/poms.nsf/lnx/0300615690 + record = retirement( + birth_date=date(1957, 9, 15), + eligibility_year=2019, + entitlement_month="2027-06", + pia=D(1500), + ) + result = compute(record, 2027) + assert row_for(result, "2027-08").claiming_factor == D(1840) / D(1500) + assert row_for(result, "2027-08").payable_benefit == 1840 + assert row_for(result, "2027-09").claiming_factor == D("1.26") + assert row_for(result, "2027-09").payable_benefit == 1890 + assert row_for(compute(record, 2028), "2028-01").payable_benefit == 1890 + + +def test_january_1_birth_uses_previous_cohort_fra_and_full_first_month(): + # The worker attains62 on December31,2021 but is first62 throughout + # January2022. The1959 cohort gives FRA66y10m, attained October2026. + # https://secure.ssa.gov/poms.nsf/lnx/0200302400 + # https://secure.ssa.gov/poms.nsf/lnx/0300201001 + record = retirement( + birth_date=date(1960, 1, 1), + eligibility_year=2021, + entitlement_month="2022-01", + ) + assert record.benchmark() == 2021 + assert full_retirement_age_months(record.birth_date) == 802 + assert claiming_factor(record.birth_date, "2026-10") == 1 + assert claiming_factor(record.birth_date, "2022-01") == Fraction(57, 80) + assert compute(record, 2022).entitlement_total > 0 + with pytest.raises(ValueError, match="first eligible month"): + compute(replace(record, entitlement_month="2021-12"), 2021) + + +def test_authoritative_survivor_year_does_not_require_fallback_birth_assumption(): + basis = survivor_basis( + worker_birth_date=None, + death_date=None, + authoritative_year=2018, + provenance="Authoritative computation year", + no_prior_disability=False, + year_only_not_january_1=False, + ) + assert basis.benchmark() == (2018, True) + assert compute(survivor(survivor=basis)).entitlement_total == 24_000 + + +def test_exact_survivor_death_date_cannot_precede_birth_in_the_same_year(): + basis = survivor_basis( + worker_birth_year=2020, + worker_birth_date=date(2020, 5, 1), + death_year=2020, + death_date=date(2020, 4, 30), + ) + with pytest.raises(ValueError, match="Death cannot precede birth"): + basis.benchmark() + + +def test_survivor_entitlement_cannot_precede_known_death_month(): + record = survivor(entitlement_month="2020-07") + with pytest.raises(ValueError, match="entitlement cannot precede"): + compute(record) + + +def test_prior_year_earnings_test_does_not_require_older_earnings_history(): + # The record has been entitled since2022. January2026's check depends on + # the2025 annual test, not on an unnecessary recursive read of2024/2023. + record = retirement( + pia=D(800), + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + result = compute( + record, + 2026, + earnings={2025: 43_080, 2026: 0}, + lower_exempt={2025: 24_480, 2026: 24_480}, + ) + assert row_for(result, "2025-12").earnings_test_reduction == 500 + assert row_for(result, "2025-12").payable_benefit == 300 + assert result.entitlement_total == 9600 + assert result.payment_total == 9100 + + +def test_claiming_dime_truncation_precedes_contributed_benefit_factor(): + # 1001.3*.7=700.91 ->700.9; then*1.1=770.99 ->770. + # Multiplying the untruncated700.91 by1.1 would incorrectly pay771. + record = retirement(pia=D("1001.3"), supplied_claiming_factor=D(".7")) + result = compute(record, policies=BenefitPolicies(across_the_board={2026: D(".1")})) + row = row_for(result, "2026-01") + assert row.unrounded_benefit == D("700.91") + assert row.gross_benefit == row.payable_benefit == 770 + + +@pytest.mark.parametrize("source", ["aime", "pia"]) +@settings(max_examples=15, deadline=None) +@given(scoring_year=st.integers(min_value=1983, max_value=2025)) +def test_property_reform_before_benchmark_keeps_benefit_zero(source, scoring_year): + record = retirement( + source=source, + aime=5000, + birth_date=date(1964, 1, 2), + eligibility_year=2026, + entitlement_month="2026-01", + ) + result = compute( + record, + scoring_year, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + ) + assert result.entitlement_total == result.payment_total == 0 + assert all(row.payable_benefit == 0 for row in result.ledger) + assert result.inferred_aime_interval is None + + +def test_s770_starts_with_january_entitlement_and_its_february_check(): + # Section2(c)(1) applies to benefits for months from January2026; + # January's check still pays the unreformed December2025 entitlement. + # https://www.congress.gov/bill/119th-congress/senate-bill/770/text + record = retirement( + source="aime", + aime=5000, + birth_date=date(1958, 1, 2), + eligibility_year=2020, + entitlement_month="2020-01", + supplied_claiming_factor=D(1), + ) + result = compute( + record, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + ) + december = row_for(result, "2025-12") + january = row_for(result, "2026-01") + assert december.payment_month == "2026-01" + assert december.eligibility_pia == D("2156.8") + assert december.payable_benefit == 2156 + assert january.payment_month == "2026-02" + assert january.eligibility_pia == D("2313.6") + assert january.payable_benefit == 2313 + assert result.payment_total == 27_599 + assert result.entitlement_total == 27_756 + + +@pytest.mark.parametrize("birth", [date(2010, 1, 2), date(1970, 1, 2)]) +def test_restricted_survivor_excludes_child_and_disabled_early_entitlement(birth): + with pytest.raises(ValueError, match="restricted survivor route excludes"): + compute(survivor(birth_date=birth)) diff --git a/policyengine_us/tools/general.py b/policyengine_us/tools/general.py index 2f8254e327c..0fdd43fdaa1 100644 --- a/policyengine_us/tools/general.py +++ b/policyengine_us/tools/general.py @@ -53,7 +53,9 @@ def earliest_input_year(simulation): later one. Inputs of a variable the tax-benefit system no longer has, or has - neutralized, are skipped: they are never read. As with + neutralized, are skipped: they are never read. Social Security calculator + record inputs are also skipped: a historical earnings-test amount or COLA + decision is not a tax-year income return for the IRMAA lookback. As with ``has_input_for_period``, core versions before 3.32.27 can keep an input key after the input is deleted, and a value recalculated for that period then still counts. Formulas that read this cache their @@ -66,6 +68,7 @@ def earliest_input_year(simulation): if ( branch_name in visible_branches and period.unit != ETERNITY + and not variable.startswith("ss_calculator_") and variable in variables and not variables[variable].is_neutralized ): diff --git a/policyengine_us/tools/social_security/engine.py b/policyengine_us/tools/social_security/engine.py new file mode 100644 index 00000000000..6a6ffa290c5 --- /dev/null +++ b/policyengine_us/tools/social_security/engine.py @@ -0,0 +1,245 @@ +"""Thin Person-variable adapter for the pure supplied-record calculator.""" + +from datetime import date +from decimal import Decimal + +import numpy as np + +from .cola import read_parameter_events +from .household import BenefitPolicies, SuppliedRecord, SurvivorBasis, calculate_year +from .parameters import bend_points_at, formula_path_at +from .pia import FormulaPath + + +def calculator_output(person, period, parameters, output): + """Evaluate enabled records only, preserving ordinary public benefits. + + No calculated result is stored as a reported input. All source fields are + explicit inputs, so a supplied zero follows the selected route unchanged. + Source extraction can export these structural inputs without inverting a + reformed public result. Per-call state keeps branches independent. + """ + year = period.start.year + sources = person("ss_calculator_source", period) + result = np.zeros(len(sources)) + for index, source in enumerate(sources): + if source == "off": + continue + + def value(name, when=period): + scalar = person("ss_calculator_" + name, when)[index] + return scalar.item() if hasattr(scalar, "item") else scalar + + def text(name): + return str(value(name)) + + def optional_date(name): + raw = text(name) + return date.fromisoformat(raw) if raw else None + + def money(name, when=period): + # Core input floats are float32. Restore the declared cents/dimes + # before passing monthly money to the exact Decimal service. + return Decimal(str(round(float(value(name, when)), 2))) + + kwargs = {} + if source == "survivor": + same_year = int(value("same_year_death_before_62")) + if same_year not in (-1, 0, 1): + raise ValueError("Same-year death assertion must be -1, 0 or 1") + kwargs["survivor"] = SurvivorBasis( + worker_birth_year=int(value("worker_birth_year")), + death_year=int(value("death_year")), + provenance=text("basis_provenance"), + worker_birth_date=optional_date("worker_birth_date"), + death_date=optional_date("death_date"), + authoritative_year=int(value("authoritative_year")) or None, + no_prior_disability=bool(value("no_prior_disability")), + ordinary_non_windex=bool(value("ordinary_non_windex")), + year_only_not_january_1=bool(value("year_only_not_january_1")), + same_year_death_before_62=None if same_year == -1 else bool(same_year), + ) + kwargs.update( + monthly_amount=money("monthly_amount"), + valuation_month=text("valuation_month"), + composite_ratio=Decimal(text("composite_ratio")), + ratio_description=text("ratio_description"), + nonbinding_rib_lim=bool(value("nonbinding_rib_lim")), + nonbinding_family_maximum=bool(value("nonbinding_family_maximum")), + no_dual_entitlement=bool(value("no_dual_entitlement")), + no_earnings_test_at_valuation=bool( + value("no_earnings_test_at_valuation") + ), + ) + record = SuppliedRecord( + source=str(source), + worker_id=text("worker_id"), + birth_date=date.fromisoformat(text("birth_date")), + entitlement_month=text("entitlement_month"), + insured=bool(value("insured")), + eligibility_year=int(value("eligibility_year")) or None, + aime=Decimal(str(value("supplied_aime"))), + pia=money("supplied_pia"), + source_basis=text("source_basis"), + supplied_claiming_factor=Decimal(text("claiming_factor")) + if text("claiming_factor") + else None, + no_special_monthly_test=bool(value("no_special_monthly_test")), + no_prior_withholding_adjustment=bool( + value("no_prior_withholding_adjustment") + ), + earnings_test_no_trigger=bool(value("earnings_test_no_trigger")), + **kwargs, + ) + benchmark = record.benchmark() + # Include the following January to price December entitlement, and any + # supplied source valuation used for baseline survivor recovery. + through = max( + year + 1, + int(record.valuation_month[:4]) if record.valuation_month else year, + ) + events = read_parameter_events(parameters, through) + earnings, before_fra, lower, higher = {}, {}, {}, {} + paths, modes, flags = {}, {}, {} + for payment_year in (year - 1, year, year + 1): + if payment_year >= benchmark: + paths[payment_year], modes[payment_year] = formula_path_at( + parameters, benchmark, payment_year + ) + else: + paths[payment_year], modes[payment_year] = FormulaPath(), "cohort" + flags[payment_year] = ( + bool( + parameters.gov.contrib.congress.s770.section_2( + f"{payment_year}-01-01" + ).recompute_pre2026_death_before_eligibility + ) + if payment_year >= 1983 + else False + ) + for earnings_year in (year - 1, year): + when = str(earnings_year) + amount = money("annual_earnings", when) + pre = money("pre_fra_earnings", when) + if amount >= 0: + earnings[earnings_year] = amount + if pre >= 0: + before_fra[earnings_year] = pre + test = parameters.gov.ssa.social_security.earnings_test(f"{when}-01-01") + lower[earnings_year] = test.exempt_amount_under_fra + higher[earnings_year] = test.exempt_amount_year_of_fra + changes, absolute_rates, withheld_years, across, payable = {}, {}, [], {}, {} + for event in events: + payment_year = int(event.payment_month[:4]) + if payment_year < 1983: + continue + policy = parameters.gov.contrib.ssa.benefit_levers.cola( + f"{payment_year}-01-01" + ) + if not 1 <= policy.effective_month <= 12: + raise ValueError("COLA effective month must lie in [1, 12]") + delta = Decimal(str(policy.pp_change)) + alternative = Decimal(str(policy.alternative_rate)) + if ( + not delta.is_finite() + or not alternative.is_finite() + or (alternative < 0 and alternative != -1) + ): + raise ValueError( + "COLA change must be finite; alternative rate must be nonnegative or -1" + ) + applies = ( + event.effective_month + >= f"{int(policy.effective_year):04d}-{int(policy.effective_month):02d}" + if policy.effective_year + else payment_year >= policy.start_year + ) + applies = applies and ( + not policy.end_year or payment_year <= policy.end_year + ) + withheld = bool( + policy.withholding_enabled and value("withhold_cola", str(payment_year)) + ) + changes[payment_year] = delta if applies else Decimal(0) + if applies and alternative >= 0: + # An absolute alternative replaces both 1999's as-paid rate + # and its corrected rate. Ordinary baseline+delta changes + # instead retain that historical distinction in adjusted_events. + absolute_rates[event.payment_month] = ( + Decimal(0) if withheld else max(Decimal(0), alternative + delta) + ) + if withheld: + withheld_years.append(payment_year) + for payment_year in (year - 1, year, year + 1): + if payment_year < 1983: + across[payment_year], payable[payment_year] = Decimal(0), Decimal(1) + continue + settings = parameters.gov.contrib.ssa.benefit_levers( + f"{payment_year}-01-01" + ) + across[payment_year] = ( + Decimal(str(settings.across_the_board.rate)) + if payment_year >= settings.across_the_board.start_year + else Decimal(0) + ) + # Both supported routes are OASI, so oasi_only reaches them just + # as a combined-OASDI payable share does. + payable[payment_year] = Decimal(str(settings.payable.share)) + annual = calculate_year( + record, + year, + bend_points=bend_points_at(parameters, benchmark), + formula_path=paths, + recompute_mode=modes, + s770_survivor_bend_increase=flags, + cola_events=events, + policies=BenefitPolicies( + cola_rates=absolute_rates, + across_the_board=across, + payable_share=payable, + cola_pp_changes=changes, + withheld_cola_years=tuple(withheld_years), + ), + earnings=earnings, + pre_fra_earnings=before_fra, + lower_exempt=lower, + higher_exempt=higher, + ) + if output in ("retirement", "survivors"): + selected = ( + source != "survivor" if output == "retirement" else source == "survivor" + ) + result[index] = float(annual.payment_total) if selected else 0 + elif output == "annual_entitlement": + result[index] = float(annual.entitlement_total) + elif output == "annual_payment": + result[index] = float(annual.payment_total) + elif output == "earnings_test_reduction": + result[index] = float(annual.earnings_test_reduction) + elif output in ("benefit", "payment", "eligibility_pia"): + target = ( + str(period)[:7] + if period.size == 1 and period.unit == "month" + else f"{year}-01" + ) + row = next( + row + for row in annual.ledger + if (row.payment_month if output == "payment" else row.entitlement_month) + == target + ) + result[index] = float( + row.eligibility_pia + if output == "eligibility_pia" + else row.payable_benefit + ) + elif output.startswith("pia_") or output.startswith("aime_"): + interval = ( + annual.eligibility_pia_interval + if output.startswith("pia_") + else annual.inferred_aime_interval + ) + result[index] = float(interval[output.endswith("upper")]) if interval else 0 + else: + raise ValueError(f"Unknown calculator output {output}") + return result diff --git a/policyengine_us/tools/social_security/household.py b/policyengine_us/tools/social_security/household.py new file mode 100644 index 00000000000..060e256f1d7 --- /dev/null +++ b/policyengine_us/tools/social_security/household.py @@ -0,0 +1,689 @@ +"""Opt-in gross Social Security ledger for supplied, identified worker records. + +All amounts are monthly dollars. A ledger row is a benefit entitlement month; +its check is paid in the following month. Both annual entitlement and check +totals are returned, so a partial year never becomes annual benefit / 12. +This module does not compute family, disability, WINDEX or minimum benefits. +""" + +from dataclasses import dataclass, replace +from datetime import date, timedelta +from decimal import Decimal, ROUND_CEILING +from fractions import Fraction +from typing import Mapping + +from policyengine_us.tools.social_security.cola import ( + adjusted_events as adjust_cola_events, + apply_colas, + reverse_colas_interval, +) +from policyengine_us.tools.social_security.pia import ( + FormulaPath, + compute_pia, + has_active_reform, + inverse_pia, +) + + +def decimal(value): + return Decimal(str(value)) + + +def rational(value): + return value if isinstance(value, Fraction) else Fraction(str(value)) + + +def as_decimal(value): + value = rational(value) + return Decimal(value.numerator) / Decimal(value.denominator) + + +def truncate_dime(value): + return Decimal(int(rational(value) * 10)) / 10 + + +def payment_round(value): + """RS 00601.020: retain a positive benefit below one dollar.""" + value = truncate_dime(value) + return value if value < 1 else Decimal(int(value)) + + +def month_number(value): + parts = str(value).split("-") + if len(parts) != 2 or not 1 <= int(parts[1]) <= 12: + raise ValueError("A month must have YYYY-MM format") + return int(parts[0]) * 12 + int(parts[1]) - 1 + + +def month_string(number): + year, month = divmod(number, 12) + return f"{year:04d}-{month + 1:02d}" + + +def attainment_month(birth_date, age_months): + # GN 00302.400: attain an age the day before the birthday. A January 1 + # birthday also belongs to the preceding birth cohort for FRA/DRCs. + shifted = birth_date - timedelta(days=1) + return shifted.year * 12 + shifted.month - 1 + age_months + + +def cohort_year(birth_date): + return (birth_date - timedelta(days=1)).year + + +def full_retirement_age_months(birth_date): + """42 USC 416(l); birth-cohort age in months (not survivor FRA).""" + year = cohort_year(birth_date) + if year < 1938: + return 780 + if year < 1943: + return 780 + 2 * (year - 1937) + if year < 1955: + return 792 + return min(804, 792 + 2 * (year - 1954)) + + +def delayed_credit_rate(birth_date): + year = cohort_year(birth_date) + if year < 1917: + return Fraction(1, 100) + if year < 1925: + return Fraction(3, 100) + return min(Fraction(8, 100), Fraction(35 + 5 * ((year - 1925) // 2), 1000)) + + +def claiming_factor(birth_date, entitlement_month, benefit_month=None): + """Exact early months and cohort DRCs, including deferred current-year DRCs. + + Credits in a midyear claim before 70 enter the benefit in January of the + next year. At 70, all eligible delayed months are credited immediately. + Sources: RS 00615.101 and RS 00615.690. + """ + claim = month_number(entitlement_month) + fra = attainment_month(birth_date, full_retirement_age_months(birth_date)) + if claim < fra: + early = fra - claim + return ( + 1 + - min(early, 36) * Fraction(1, 180) + - max(early - 36, 0) * Fraction(1, 240) + ) + age70 = attainment_month(birth_date, 840) + end = min(claim, age70) + benefit = claim if benefit_month is None else month_number(benefit_month) + if claim < age70 and benefit < age70 and benefit // 12 == claim // 12: + end = min(end, (claim // 12) * 12) + credits = max(0, end - fra) + return 1 + credits * delayed_credit_rate(birth_date) / 12 + + +@dataclass(frozen=True) +class SurvivorBasis: + worker_birth_year: int + death_year: int + provenance: str + worker_birth_date: date | None = None + death_date: date | None = None + authoritative_year: int | None = None + no_prior_disability: bool = False + ordinary_non_windex: bool = False + year_only_not_january_1: bool = False + same_year_death_before_62: bool | None = None + + def benchmark(self): + if not self.provenance.strip(): + raise ValueError("Survivor computation-basis provenance is required") + if not self.ordinary_non_windex: + raise ValueError( + "Only ordinary non-WINDEX survivor computations are supported" + ) + if not self.no_prior_disability and self.authoritative_year is None: + raise ValueError( + "Prior disability requires an authoritative computation basis" + ) + if ( + self.worker_birth_date + and self.worker_birth_date.year != self.worker_birth_year + ): + raise ValueError("Worker birth date and birth year disagree") + if self.death_date and self.death_date.year != self.death_year: + raise ValueError("Death date and death year disagree") + if ( + self.death_date + and self.worker_birth_date + and self.death_date < self.worker_birth_date + ): + raise ValueError("Death cannot precede birth") + if self.death_year < self.worker_birth_year: + raise ValueError("Death cannot precede birth") + if self.worker_birth_date: + b = self.worker_birth_date + # February 29 attains age 62 on February 28 in a non-leap year. + try: + birthday62 = b.replace(year=b.year + 62) + except ValueError: + birthday62 = date(b.year + 62, 3, 1) + attained62 = birthday62 - timedelta(days=1) + year62 = attained62.year + else: + if not self.year_only_not_january_1 and self.authoritative_year is None: + raise ValueError( + "Year-only birth basis requires a not-January-1 assertion" + ) + year62 = self.worker_birth_year + 62 + attained62 = None + if self.death_year == year62: + if self.death_date and attained62: + pre62 = self.death_date < attained62 + elif self.same_year_death_before_62 is not None: + pre62 = self.same_year_death_before_62 + else: + raise ValueError( + "Same-year death/age-62 attainment needs dates or an assertion" + ) + else: + pre62 = self.death_year < year62 + year = ( + self.authoritative_year + if self.authoritative_year is not None + else min(year62, self.death_year) + ) + if year < 1983: + raise ValueError("Computation benchmarks before 1983 are unsupported") + return year, pre62 + + +@dataclass(frozen=True) +class SuppliedRecord: + source: str + worker_id: str + birth_date: date # recipient; worker for an own-retirement record + entitlement_month: str + insured: bool + eligibility_year: int | None = None + aime: Decimal | int | None = None + pia: Decimal | int | None = None + source_basis: str = "unreformed_eligibility" + supplied_claiming_factor: Decimal | None = None + survivor: SurvivorBasis | None = None + monthly_amount: Decimal | None = None + valuation_month: str | None = None + composite_ratio: Decimal | None = None + ratio_description: str = "" + nonbinding_rib_lim: bool = False + nonbinding_family_maximum: bool = False + no_dual_entitlement: bool = False + no_earnings_test_at_valuation: bool = False + no_special_monthly_test: bool = False + no_prior_withholding_adjustment: bool = False + earnings_test_no_trigger: bool = False + + def benchmark(self): + if not self.worker_id.strip(): + raise ValueError("An explicit worker record ID is required") + if self.source not in ("aime", "pia", "survivor"): + raise ValueError("Choose an explicit aime, pia or survivor source") + if self.source_basis != "unreformed_eligibility": + raise ValueError("Only explicitly unreformed source amounts are supported") + month_number(self.entitlement_month) + if self.source == "survivor": + if self.survivor is None: + raise ValueError("The survivor route requires a deceased-worker basis") + if month_number(self.entitlement_month) < attainment_month( + self.birth_date, 720 + ): + raise ValueError( + "The restricted survivor route excludes child, caregiver and disabled-survivor entitlement before age 60" + ) + return self.survivor.benchmark()[0] + year = attainment_month(self.birth_date, 744) // 12 + if self.eligibility_year != year: + raise ValueError( + "Own-retirement eligibility year must equal age-62 attainment year" + ) + if year < 1983: + raise ValueError("Computation benchmarks before 1983 are unsupported") + # RS 00201.001: the worker must be 62 throughout the first reduced + # entitlement month. Birthdays on day 1 or 2 permit the birth month. + earliest = year * 12 + self.birth_date.month - 1 + if self.birth_date.day == 1: + earliest = attainment_month(self.birth_date, 744) + 1 + elif self.birth_date.day > 2: + earliest += 1 + if month_number(self.entitlement_month) < earliest: + raise ValueError("Retirement entitlement precedes the first eligible month") + if self.survivor is not None: + raise ValueError( + "Own-retirement records cannot invoke survivor computation" + ) + return year + + +@dataclass(frozen=True) +class BenefitPolicies: + """Already resolved joint COLA decisions and payment-year factors. + + A withheld COLA has rate zero; changed rates already include any statutory + floor and policy precision. This accepts E3 decisions without reading tax + income or constructing a cycle. Medicare deductions are never included. + """ + + cola_rates: Mapping[str, Decimal] | None = None + across_the_board: Mapping[int, Decimal] | None = None + payable_share: Mapping[int, Decimal] | None = None + cola_pp_changes: Mapping[int, Decimal] | None = None + withheld_cola_years: tuple[int, ...] = () + + def factor(self, payment_year): + rate = decimal((self.across_the_board or {}).get(payment_year, 0)) + share = decimal((self.payable_share or {}).get(payment_year, 1)) + if rate < -1 or not 0 <= share <= 1: + raise ValueError("Benefit rate must be >= -1 and payable share in [0, 1]") + return (1 + rate) * share + + +@dataclass(frozen=True) +class EntitlementMonth: + entitlement_month: str + payment_month: str + eligibility_pia: Decimal + cola_pia: Decimal + claiming_factor: Decimal + unrounded_benefit: Decimal + gross_benefit: Decimal + earnings_test_reduction: Decimal + payable_benefit: Decimal + + +@dataclass(frozen=True) +class AnnualBenefit: + ledger: tuple[EntitlementMonth, ...] + entitlement_total: Decimal + payment_total: Decimal + earnings_test_reduction: Decimal + eligibility_pia_interval: tuple[Decimal, Decimal] | None = None + inferred_aime_interval: tuple[Decimal, Decimal] | None = None + + +def _source_pia(record, year, bends, baseline_events): + if record.source == "aime": + if ( + record.aime is None + or rational(record.aime) < 0 + or rational(record.aime).denominator != 1 + ): + raise ValueError( + "Supplied AIME must be a nonnegative whole monthly dollar amount" + ) + return compute_pia(record.aime, year, bend_points=bends), record.aime, None + if record.source == "pia": + if ( + record.pia is None + or rational(record.pia) < 0 + or truncate_dime(record.pia) != decimal(record.pia) + ): + raise ValueError( + "Supplied eligibility PIA must be nonnegative and dime-valued" + ) + return decimal(record.pia), None, None + if not all( + ( + record.nonbinding_rib_lim, + record.nonbinding_family_maximum, + record.no_dual_entitlement, + record.no_earnings_test_at_valuation, + ) + ): + raise ValueError( + "Survivor inversion requires nonbinding limits, no dual entitlement and no valuation withholding" + ) + if record.supplied_claiming_factor is not None: + raise ValueError( + "The composite survivor ratio already includes claiming adjustments" + ) + if ( + not record.ratio_description.strip() + or record.composite_ratio is None + or rational(record.composite_ratio) <= 0 + ): + raise ValueError( + "A positive composite survivor ratio and its description are required" + ) + if ( + record.monthly_amount is None + or rational(record.monthly_amount) < 0 + or record.valuation_month is None + ): + raise ValueError( + "Supply a nonnegative gross monthly payment and its valuation month" + ) + if month_number(record.valuation_month) <= month_number(record.entitlement_month): + raise ValueError( + "Survivor source valuation must be after entitlement commencement" + ) + if record.survivor.death_year > int(record.valuation_month[:4]): + raise ValueError("Source valuation precedes the worker's death") + amount = decimal(record.monthly_amount) + if 0 < amount < 1 and month_number(record.valuation_month) < month_number( + "2007-01" + ): + raise ValueError( + "Sub-dollar survivor source checks before January 2007 require " + "unsupported year-end manual payment timing" + ) + # Paid-dollar interval is wider than the exact-dime eligibility interval. + # The sub-dollar exception retains dimes (RS 00601.020). + width = Decimal("0.1") if amount < 1 else Decimal(1) + ratio = decimal(record.composite_ratio) + lower, upper = reverse_colas_interval( + rational(amount) / rational(ratio), + rational(amount + width) / rational(ratio), + year, + record.valuation_month, + baseline_events, + ) + lower = (lower * 10).to_integral_value(rounding=ROUND_CEILING) / 10 + if lower >= upper: + raise ValueError( + "Supplied survivor amount has no consistent dime-valued eligibility PIA" + ) + reproduced = payment_round( + rational(apply_colas(lower, year, record.valuation_month, baseline_events)) + * rational(ratio) + ) + if reproduced != amount: + raise ValueError( + "Supplied survivor amount is inconsistent with the stated payment rounding" + ) + return lower, None, (lower, upper) + + +def calculate_year( + record, + year, + *, + bend_points, + formula_path=None, + cola_events=(), + policies=None, + earnings=None, + pre_fra_earnings=None, + lower_exempt=None, + higher_exempt=None, + recompute_mode="cohort", + s770_survivor_bend_increase=False, + _include_previous_check=True, +): + """Return a 13-row ledger (previous December plus January–December). + + The extra December identifies January's check. Earnings maps are keyed by + entitlement year; the prior year is required when January's check could + have been withheld. The ordinary annual test is allocated to the earliest + affected months. Special monthly/service tests and adjustments for earlier + withheld months require explicit no-trigger assertions in this route. + """ + # The inverse, its reproduction check, and the prior-year earnings-test + # ledger all need the same immutable history, including for iterator input. + cola_events = tuple(cola_events) + benchmark = record.benchmark() + baseline_pia, aime, pia_interval = _source_pia( + record, benchmark, bend_points, cola_events + ) + paths = formula_path + policies = policies or BenefitPolicies() + if not record.no_special_monthly_test or not record.no_prior_withholding_adjustment: + raise ValueError( + "Assert no special monthly/service test and no prior-withholding actuarial adjustment" + ) + restricted_survivor = False + if record.source == "survivor": + _, before62 = record.survivor.benchmark() + restricted_survivor = before62 and record.survivor.death_year < 2026 + death_month = ( + record.survivor.death_date.strftime("%Y-%m") + if record.survivor.death_date + else f"{record.survivor.death_year}-01" + ) + if month_number(record.entitlement_month) < month_number(death_month): + raise ValueError("Survivor entitlement cannot precede the worker's death") + policy_events = adjust_cola_events( + cola_events, policies.cola_pp_changes, policies.withheld_cola_years + ) + adjusted_events = tuple( + replace( + event, + rate=decimal(policies.cola_rates[event.payment_month]), + as_paid_rate=decimal(policies.cola_rates[event.payment_month]) + if event.as_paid_rate is not None + else None, + ) + if event.payment_month in (policies.cola_rates or {}) + else event + for event in policy_events + ) + if any(event.rate < 0 for event in adjusted_events): + raise ValueError("Joint COLA rates cannot reduce nominal PIA") + fra = attainment_month( + record.birth_date, full_retirement_age_months(record.birth_date) + ) + claim = month_number(record.entitlement_month) + rows = [] + inferred_interval = None + for number in range(year * 12 - int(_include_previous_check), (year + 1) * 12): + entitlement = month_string(number) + payment = month_string(number + 1) + payment_year = (number + 1) // 12 + path = ( + paths[payment_year] if isinstance(paths, Mapping) else paths + ) or FormulaPath() + # S.770 section 2(c)(1) reaches benefit months from January 2026; + # the ordinary check for that month follows in February. COLA changes + # instead key off check months, as specified in their policy contract. + if number < 2026 * 12 and path.s770: + path = replace(path, s770=False) + mode = ( + recompute_mode[payment_year] + if isinstance(recompute_mode, Mapping) + else recompute_mode + ) + flag = ( + s770_survivor_bend_increase[payment_year] + if isinstance(s770_survivor_bend_increase, Mapping) + else s770_survivor_bend_increase + ) + if restricted_survivor and path.s770: + path = replace(path, s770_increase_first_bend_point=flag) + # Only infer AIME if the selected path actually changes the baseline. + pia = baseline_pia + if payment_year >= benchmark and has_active_reform( + path, benchmark, payment_year, mode + ): + if aime is None and baseline_pia != 0: + inferred = inverse_pia(baseline_pia, benchmark, bend_points=bend_points) + aime = inferred.lower + upper_pia = ( + pia_interval[1] if pia_interval else baseline_pia + Decimal("0.1") + ) + inferred_interval = ( + inferred.lower, + inverse_pia(upper_pia, benchmark, bend_points=bend_points).lower, + ) + reformed = compute_pia( + aime if aime is not None else 0, + benchmark, + path, + payment_year, + mode, + bend_points=bend_points, + ) + # The supplied unreformed PIA is authoritative; one ratio, once. + pia = ( + Decimal(0) + if baseline_pia == 0 + else truncate_dime( + rational(baseline_pia) + * rational(reformed) + / rational(compute_pia(aime, benchmark, bend_points=bend_points)) + ) + ) + cola_pia = apply_colas(pia, benchmark, payment, adjusted_events) + factor = ( + rational(record.composite_ratio) + if record.source == "survivor" + else rational(record.supplied_claiming_factor) + if record.supplied_claiming_factor is not None + else claiming_factor( + record.birth_date, record.entitlement_month, entitlement + ) + ) + if factor <= 0: + raise ValueError("Supplied claiming adjustment must be positive") + raw = rational(cola_pia) * factor + # Preserve SSA's separate claiming-adjustment dime step before any + # contributed payable/across-the-board mechanism and dollar payment. + adjusted_benefit = rational(truncate_dime(raw)) * rational( + policies.factor(payment_year) + ) + gross = ( + payment_round(adjusted_benefit) + if record.insured and number >= claim + else Decimal(0) + ) + if 0 < gross < 1 and number < month_number("2006-12"): + # RS 00601.020 D.3: these benefits were held for manual year-end + # payment before December 2006, not paid as recurring dime checks. + raise ValueError( + "Sub-dollar entitlement before December 2006 requires " + "unsupported year-end manual payment timing" + ) + rows.append( + EntitlementMonth( + entitlement, + payment, + pia, + cola_pia, + as_decimal(factor), + as_decimal(raw), + gross, + Decimal(0), + gross, + ) + ) + # Evaluate full entitlement years, even when only their last month's check + # falls in the requested payment year. This makes request order irrelevant. + by_month = {row.entitlement_month: row for row in rows} + for earnings_year in (year - 1, year) if _include_previous_check else (year,): + if ( + earnings_year < 2000 + and not record.earnings_test_no_trigger + and record.insured + and claim < (earnings_year + 1) * 12 + ): + raise ValueError( + "Earnings testing before 2000 is unsupported; supply an explicit " + "no-trigger assertion for historical entitlement" + ) + if earnings_year * 12 >= fra or not record.insured: + continue + relevant = [ + n + for n in range(earnings_year * 12, (earnings_year + 1) * 12) + if claim <= n < fra + ] + if not relevant: + continue + if record.earnings_test_no_trigger: + # A caller asserting no trigger must not also supply excess earnings. + values = earnings or {} + high = fra // 12 == earnings_year + limit = (higher_exempt if high else lower_exempt) or {} + observed = ( + (pre_fra_earnings or {}).get(earnings_year) + if high + else values.get(earnings_year) + ) + if observed is not None and ( + earnings_year not in limit + or decimal(observed) > decimal(limit[earnings_year]) + ): + raise ValueError( + "No-earnings-test assertion conflicts with supplied earnings" + ) + continue + high = fra // 12 == earnings_year + values = pre_fra_earnings if high else earnings + limits = higher_exempt if high else lower_exempt + if ( + values is None + or earnings_year not in values + or limits is None + or earnings_year not in limits + ): + raise ValueError( + "Supply annual earnings, and pre-FRA-month earnings in the FRA year, plus exempt amounts" + ) + if decimal(values[earnings_year]) < 0: + raise ValueError("Earnings-test earnings must be nonnegative") + remaining = max( + Decimal(0), decimal(values[earnings_year]) - decimal(limits[earnings_year]) + ) / (3 if high else 2) + # RS 02501.080: truncate the annual deduction to whole dollars. + remaining = Decimal(int(remaining)) + # Fill missing earlier months using the same pure ledger calculation. + if earnings_year == year - 1 and remaining: + earlier = calculate_year( + record, + earnings_year, + bend_points=bend_points, + formula_path=paths, + cola_events=cola_events, + policies=policies, + earnings=earnings, + pre_fra_earnings=pre_fra_earnings, + lower_exempt=lower_exempt, + higher_exempt=higher_exempt, + recompute_mode=recompute_mode, + s770_survivor_bend_increase=s770_survivor_bend_increase, + _include_previous_check=False, + ) + old = earlier.ledger[-1] + by_month[old.entitlement_month] = old + continue + for n in relevant: + key = month_string(n) + if key not in by_month: + continue + row = by_month[key] + reduction = min(row.gross_benefit, remaining) + remaining -= reduction + by_month[key] = replace( + row, + earnings_test_reduction=reduction, + payable_benefit=row.gross_benefit - reduction, + ) + rows = tuple(by_month[row.entitlement_month] for row in rows) + return AnnualBenefit( + rows, + sum( + ( + r.payable_benefit + for r in rows + if r.entitlement_month.startswith(str(year)) + ), + Decimal(0), + ), + sum( + (r.payable_benefit for r in rows if r.payment_month.startswith(str(year))), + Decimal(0), + ), + sum( + ( + r.earnings_test_reduction + for r in rows + if r.entitlement_month.startswith(str(year)) + ), + Decimal(0), + ), + pia_interval, + inferred_interval, + ) diff --git a/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py b/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py new file mode 100644 index 00000000000..b408e1093db --- /dev/null +++ b/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py @@ -0,0 +1,338 @@ +"""Explicit source inputs for the opt-in supplied-record calculator. + +The selector, rather than amount positivity, determines the source. These are +separate from reported public benefit inputs and carry no automatic uprating. +""" + +from policyengine_us.model_api import * + + +class ss_calculator_source(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "off" + label = "Social Security calculator source" + documentation = "Explicit source: off, aime, pia or survivor." + + +class ss_calculator_worker_id(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator worker id" + documentation = ( + "Underlying worker record identifier; each own record has a distinct ID." + ) + + +class ss_calculator_birth_date(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator birth date" + documentation = "Recipient exact birth date, YYYY-MM-DD; also the worker date for own retirement." + + +class ss_calculator_entitlement_month(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator entitlement month" + documentation = ( + "First benefit entitlement month, YYYY-MM; the check follows one month later." + ) + + +class ss_calculator_eligibility_year(Variable): + value_type = int + entity = Person + definition_period = ETERNITY + default_value = 0 + label = "Social Security calculator eligibility year" + documentation = "Own-retirement initial age-62 eligibility year." + + +class ss_calculator_supplied_aime(Variable): + # Preserve fractional input so the service can reject it, rather than + # Core silently truncating it while coercing an integer-valued variable. + value_type = float + entity = Person + definition_period = ETERNITY + default_value = -1 + label = "Social Security calculator supplied aime" + documentation = "Unreformed eligibility AIME, whole monthly dollars; zero is a supplied zero and -1 means missing." + unit = USD + + +class ss_calculator_supplied_pia(Variable): + value_type = float + entity = Person + definition_period = ETERNITY + default_value = -1 + label = "Social Security calculator supplied pia" + documentation = "Unreformed eligibility PIA, monthly dollars valued before subsequent COLAs; -1 means missing." + unit = USD + + +class ss_calculator_source_basis(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "unreformed_eligibility" + label = "Social Security calculator source basis" + documentation = "Source valuation basis; only unreformed_eligibility is supported." + + +class ss_calculator_claiming_factor(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator claiming factor" + documentation = "Optional exact claiming adjustment as a decimal string; empty computes exact months." + + +class ss_calculator_insured(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator insured" + documentation = "Assert insured status for the selected underlying worker record." + + +class ss_calculator_no_special_monthly_test(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator no special monthly test" + documentation = ( + "Assert the first-year monthly/service earnings test does not trigger." + ) + + +class ss_calculator_no_prior_withholding_adjustment(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator no prior withholding adjustment" + documentation = ( + "Assert no actuarial adjustment for earlier withheld months is needed." + ) + + +class ss_calculator_earnings_test_no_trigger(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator earnings test no trigger" + documentation = "Assert earnings do not trigger the annual earnings test in the requested years." + + +class ss_calculator_worker_birth_year(Variable): + value_type = int + entity = Person + definition_period = ETERNITY + default_value = 0 + label = "Social Security calculator worker birth year" + documentation = "Deceased worker birth year for the restricted survivor route." + + +class ss_calculator_worker_birth_date(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator worker birth date" + documentation = "Optional deceased worker exact birth date, YYYY-MM-DD." + + +class ss_calculator_death_year(Variable): + value_type = int + entity = Person + definition_period = ETERNITY + default_value = 0 + label = "Social Security calculator death year" + documentation = "Deceased worker death year." + + +class ss_calculator_death_date(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator death date" + documentation = "Optional exact worker death date, YYYY-MM-DD." + + +class ss_calculator_authoritative_year(Variable): + value_type = int + entity = Person + definition_period = ETERNITY + default_value = 0 + label = "Social Security calculator authoritative year" + documentation = ( + "Optional authoritative survivor computation benchmark; zero means derive." + ) + + +class ss_calculator_basis_provenance(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator basis provenance" + documentation = ( + "Provenance identifying the supplied or derived survivor computation basis." + ) + + +class ss_calculator_no_prior_disability(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator no prior disability" + documentation = "Assert the deceased had no prior disability benefit computation." + + +class ss_calculator_ordinary_non_windex(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator ordinary non windex" + documentation = "Assert an ordinary non-WINDEX survivor computation." + + +class ss_calculator_year_only_not_january_1(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator year only not january 1" + documentation = "Assert the year-only deceased birth basis assumes a birthday other than January 1." + + +class ss_calculator_same_year_death_before_62(Variable): + value_type = int + entity = Person + definition_period = ETERNITY + default_value = -1 + label = "Social Security calculator same year death before 62" + documentation = "Same-year death/age62 assertion: 1 before62, 0 after62, -1 requires exact dates." + + +class ss_calculator_monthly_amount(Variable): + value_type = float + entity = Person + definition_period = ETERNITY + default_value = -1 + label = "Social Security calculator monthly amount" + documentation = "Supplied unreformed gross survivor monthly payment at the valuation month; -1 means missing." + unit = USD + + +class ss_calculator_valuation_month(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator valuation month" + documentation = ( + "Survivor source check month, YYYY-MM, including its baseline COLAs." + ) + + +class ss_calculator_composite_ratio(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator composite ratio" + documentation = "Exact positive survivor-to-worker PIA ratio as a decimal string, including all reductions/credits." + + +class ss_calculator_ratio_description(Variable): + value_type = str + entity = Person + definition_period = ETERNITY + default_value = "" + label = "Social Security calculator ratio description" + documentation = ( + "Description of what the supplied survivor composite ratio includes." + ) + + +class ss_calculator_nonbinding_rib_lim(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator nonbinding rib lim" + documentation = "Assert the survivor RIB-LIM is nonbinding." + + +class ss_calculator_nonbinding_family_maximum(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator nonbinding family maximum" + documentation = "Assert the family maximum is nonbinding." + + +class ss_calculator_no_dual_entitlement(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator no dual entitlement" + documentation = "Assert the survivor has no dual entitlement." + + +class ss_calculator_no_earnings_test_at_valuation(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator no earnings test at valuation" + documentation = ( + "Assert the supplied survivor valuation has no earnings-test withholding." + ) + + +class ss_calculator_annual_earnings(Variable): + value_type = float + entity = Person + definition_period = YEAR + default_value = -1 + label = "Social Security calculator annual earnings" + documentation = "Annual earnings subject to the annual test; -1 means missing." + unit = USD + + +class ss_calculator_pre_fra_earnings(Variable): + value_type = float + entity = Person + definition_period = YEAR + default_value = -1 + label = "Social Security calculator pre fra earnings" + documentation = "Earnings only before the retirement FRA month; -1 means missing." + unit = USD + + +class ss_calculator_withhold_cola(Variable): + value_type = bool + entity = Person + definition_period = YEAR + default_value = False + label = "Social Security calculator withhold cola" + documentation = "Already-resolved COLA withholding decision for this check year, for example from an E3 policy." diff --git a/policyengine_us/variables/gov/ssa/social_security/calculator/results.py b/policyengine_us/variables/gov/ssa/social_security/calculator/results.py new file mode 100644 index 00000000000..9c7aa92b71b --- /dev/null +++ b/policyengine_us/variables/gov/ssa/social_security/calculator/results.py @@ -0,0 +1,170 @@ +"""Opt-in results; the public benefit source selector can consume these once.""" + +from policyengine_us.model_api import * +from policyengine_us.tools.social_security.engine import calculator_output + + +class ss_calculated_retirement(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security retirement" + documentation = ( + "Gross annual retirement checks on the selected supplied own record." + ) + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "retirement") + + +class ss_calculated_survivors(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security survivors" + documentation = ( + "Gross annual survivor checks on the selected restricted survivor record." + ) + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "survivors") + + +class ss_calculated_annual_entitlement(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security annual entitlement" + documentation = "Sum of payable entitlement months in the calendar year, before Medicare deductions." + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "annual_entitlement") + + +class ss_calculated_annual_payment(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security annual payment" + documentation = "Sum of gross checks paid in the calendar year; each check follows entitlement by one month." + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "annual_payment") + + +class ss_calculated_earnings_test_reduction(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security earnings test reduction" + documentation = ( + "Annual earnings-test reduction capped at affected entitlement benefits." + ) + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "earnings_test_reduction") + + +class ss_calculated_benefit(Variable): + value_type = float + entity = Person + definition_period = MONTH + unit = USD + label = "Calculated Social Security benefit" + documentation = "Payable gross benefit for this entitlement month; the check follows next month." + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "benefit") + + +class ss_calculated_payment(Variable): + value_type = float + entity = Person + definition_period = MONTH + unit = USD + label = "Calculated Social Security payment" + documentation = ( + "Gross benefit check in this month for the preceding entitlement month." + ) + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "payment") + + +class ss_calculated_eligibility_pia(Variable): + value_type = float + entity = Person + definition_period = MONTH + unit = USD + label = "Calculated Social Security eligibility pia" + documentation = "Reformed monthly eligibility PIA underlying this entitlement month, before COLAs." + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "eligibility_pia") + + +class ss_calculated_pia_lower(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security pia lower" + documentation = ( + "Lower endpoint of the survivor source eligibility-PIA rounding interval." + ) + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "pia_lower") + + +class ss_calculated_pia_upper(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security pia upper" + documentation = "Exclusive upper endpoint of the survivor source eligibility-PIA rounding interval." + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "pia_upper") + + +class ss_calculated_aime_lower(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security aime lower" + documentation = "Lower-endpoint AIME inferred from the supplied baseline PIA when a PIA reform requires it." + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "aime_lower") + + +class ss_calculated_aime_upper(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security aime upper" + documentation = "Exclusive upper endpoint of inferred AIME including source payment-rounding uncertainty." + reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + + def formula(person, period, parameters): + return calculator_output(person, period, parameters, "aime_upper") From 718ef1cc2a7187002b945e7153ab27dcb6f956f3 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 03:51:42 -0400 Subject: [PATCH 07/16] Isolate calculator API checks on the existing simulation test runner --- Makefile | 8 +++- docs/usage/social-security-calculator.md | 8 +++- .../code_health/test_rest_python_groups.py | 47 +++++++++++++++++-- 3 files changed, 56 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index a3dc2fcbe44..8e23dd21a4c 100644 --- a/Makefile +++ b/Makefile @@ -23,6 +23,10 @@ TESTS := policyengine_us/tests REST_SPM_TESTS := $(TESTS)/core/test_spm_policy_family.py \ $(TESTS)/core/test_spm_simulation_isolation.py \ $(TESTS)/core/test_spm_system.py +# Calculator Simulation/API contracts use that same runner, with each file +# in its own process so its reform trees are released before the next suite. +REST_SIMULATION_API_TESTS := $(TESTS)/unit/test_ss_calculator_engine.py \ + $(TESTS)/unit/test_ss_calculator_differential.py # The remaining Python tests run as one pytest process per group, one after # another, so each exit releases its heap before the next group starts. As a # single process they peaked at 15.7 GB RSS on the 16 GB runner, with 1.5M @@ -95,7 +99,7 @@ REST_REMAINING_HEAVY_TESTS := $(TESTS)/test_niit_section_911_magi.py \ $(TESTS)/test_schedule_d_filer_net_capital_gain.py REST_LISTED_TESTS := $(REST_CACHED_ARRAY_TESTS) $(REST_HEAVY_A_TESTS) $(REST_HEAVY_B_TESTS) \ $(REST_CORE_HEAVY_TESTS) $(REST_POLICY_PARAMETER_TESTS) $(REST_REMAINING_HEAVY_TESTS) -REST_IGNORES := $(addprefix --ignore=,$(TESTS)/policy/contrib $(TESTS)/microsimulation $(REST_SPM_TESTS)) +REST_IGNORES := $(addprefix --ignore=,$(TESTS)/policy/contrib $(TESTS)/microsimulation $(REST_SPM_TESTS) $(REST_SIMULATION_API_TESTS)) # $(call rest_pytest,,,) is the pytest # command for one group. CI sets REST_REPORT_DIR, and each group then writes # its own JUnit XML and GNU time report there: rest-python-.xml and @@ -302,6 +306,8 @@ test-other-python: pytest policyengine_us/tests/ --maxfail=0 --ignore=$(TESTS)/policy/contrib --ignore=$(TESTS)/microsimulation test-other-python-spm: pytest $(REST_SPM_TESTS) --maxfail=0 + pytest $(TESTS)/unit/test_ss_calculator_engine.py --maxfail=0 $(if $(findstring --junitxml=,$(PYTEST_ADDOPTS)),--junitxml=simulation-ss-calculator-engine.xml) + pytest $(TESTS)/unit/test_ss_calculator_differential.py --maxfail=0 $(if $(findstring --junitxml=,$(PYTEST_ADDOPTS)),--junitxml=simulation-ss-calculator-differential.xml) # Every group runs even after one fails; the target fails if any group did. test-other-python-rest: @failed=""; for group in $(REST_PYTHON_SELECTED_GROUPS); do \ diff --git a/docs/usage/social-security-calculator.md b/docs/usage/social-security-calculator.md index a7c29ba991a..bac6db0e6cd 100644 --- a/docs/usage/social-security-calculator.md +++ b/docs/usage/social-security-calculator.md @@ -141,7 +141,7 @@ Historical bends back to 1979 are separate parameters, preserving legacy scale values. Future bends use the model's existing wage-indexed projections. `gov.contrib.ssa.pia` contains neutral bend-point multipliers, factors and cohort -start, and explicit `recompute_existing`. No top-factor package schedule is +start, an `in_effect` opt-in gate, and explicit `recompute_existing`. No top-factor package schedule is selected. S.770 is separately enabled with `gov.contrib.congress.s770.section_2.in_effect` and uses original eligibility bend points for older beneficiaries. @@ -157,7 +157,11 @@ without its required frozen inputs fails. Frozen scales, dollar thresholds, maximum AIMEs and targets require explicit January observations for each eligibility cohort; they never silently carry a prior cohort's data forward. The policy fraction and ordinary factor schedules retain normal dated-policy -semantics. No population percentile or solvency +semantics. Both indexing paths also require their own `in_effect` switch and +start cohort; setting a fraction alone does not activate progressive indexing. +Ordinary settings read the eligibility-year snapshot. Explicit older-cohort +recomputation reads payment-year settings while retaining original-cohort +bend points and frozen indexing inputs. No population percentile or solvency estimate supplies missing values. Scoring must pin price/wage bases, lags, anchor, maximum-taxable career, source hashes and combined-policy order. Composition order is custom bends/factors, S.770, full indexing, progressive diff --git a/policyengine_us/tests/code_health/test_rest_python_groups.py b/policyengine_us/tests/code_health/test_rest_python_groups.py index 293b2a7f947..8324c99de34 100644 --- a/policyengine_us/tests/code_health/test_rest_python_groups.py +++ b/policyengine_us/tests/code_health/test_rest_python_groups.py @@ -249,12 +249,20 @@ def old_command(): """The pytest arguments of the single process the groups replace. It was test-other-python, the Python tests outside contrib and - microsimulation, with the SPM files left to their own step. + microsimulation, with the SPM and Simulation/API files left to their + own sequential processes on the Microsimulation runner. """ (other,) = dry_run("test-other-python") - (spm,) = dry_run("test-other-python-spm") - assert other[0] == spm[0] == "pytest", (other, spm) - spm_files = [arg for arg in spm[1:] if not arg.startswith("-")] + simulation_commands = dry_run("test-other-python-spm") + assert other[0] == "pytest" + assert simulation_commands + assert all(command[0] == "pytest" for command in simulation_commands) + spm_files = [ + arg + for command in simulation_commands + for arg in command[1:] + if not arg.startswith("-") + ] return other[1:] + [f"--ignore={file}" for file in spm_files] @@ -513,6 +521,37 @@ def test_spm_and_dataset_suites_run_once_in_separate_steps_with_reports(workflow assert uploads[0]["with"]["name"] != "rest-test-timings" +def test_calculator_api_files_run_once_in_separate_simulation_processes(): + commands = dry_run("test-other-python-spm") + files_by_process = [ + [arg for arg in command[1:] if not arg.startswith("-")] for command in commands + ] + files = [file for process_files in files_by_process for file in process_files] + assert len(files) == len(set(files)), "Simulation files run more than once" + for name in ("engine", "differential"): + file = f"policyengine_us/tests/unit/test_ss_calculator_{name}.py" + assert [process for process in files_by_process if file in process] == [ + [file] + ], f"{file} must run once in its own process" + + # The CI step gives SPM a JUnit path through PYTEST_ADDOPTS. Later + # processes need separate reports so they do not overwrite that suite. + reported = dry_run( + "test-other-python-spm", "PYTEST_ADDOPTS=--junitxml=simulation-spm.xml" + ) + reports = [ + arg.removeprefix("--junitxml=") + for command in reported + for arg in command[1:] + if arg.startswith("--junitxml=") + ] + assert reports == [ + "simulation-ss-calculator-engine.xml", + "simulation-ss-calculator-differential.xml", + ] + assert len(set(reports + ["simulation-spm.xml"])) == 3 + + def test_groups_run_as_plain_pytest_without_a_report_dir(groups): """Locally the same groups run without GNU time, which macOS lacks.""" plain = dry_run("test-other-python-rest") From 397f507f7176ac59399a6b36268171305d462afa Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 03:56:44 -0400 Subject: [PATCH 08/16] Support Core empty-node parsing in calculator parameter fixtures --- policyengine_us/tests/unit/test_ss_calculator_parameters.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/policyengine_us/tests/unit/test_ss_calculator_parameters.py b/policyengine_us/tests/unit/test_ss_calculator_parameters.py index 7a01fecf8b1..6d9ff107cf6 100644 --- a/policyengine_us/tests/unit/test_ss_calculator_parameters.py +++ b/policyengine_us/tests/unit/test_ss_calculator_parameters.py @@ -27,7 +27,7 @@ def calculator_parameters(reference_parameters): the adapter's production paths intact while avoiding a whole-US tree copy and whole-US instant snapshots for each isolated parameter reform. """ - root = ParameterNode() + root = ParameterNode(data={}) for path in ( "gov.ssa.social_security.pia", "gov.contrib.ssa.pia", @@ -43,7 +43,8 @@ def calculator_parameters(reference_parameters): else: if part not in destination.children: destination.add_child( - part, ParameterNode(name=".".join(parts[: index + 1])) + part, + ParameterNode(name=".".join(parts[: index + 1]), data={}), ) destination = destination.children[part] return root From ff7cdf41d6528b27e5f116f4358d2c6301669a5a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 04:13:17 -0400 Subject: [PATCH 09/16] Tighten calculator API isolation and correct integration fixtures --- .github/workflows/push.yaml | 6 +++++ .github/workflows/python-tests.yaml | 6 +++++ .../unit/test_ss_calculator_differential.py | 27 +++++++++---------- .../tests/unit/test_ss_calculator_engine.py | 19 ++++++------- policyengine_us/tools/general.py | 7 ++--- 5 files changed, 39 insertions(+), 26 deletions(-) diff --git a/.github/workflows/push.yaml b/.github/workflows/push.yaml index 1456db83bec..059bb83c364 100644 --- a/.github/workflows/push.yaml +++ b/.github/workflows/push.yaml @@ -484,6 +484,12 @@ jobs: env: PYTHONUNBUFFERED: 1 PYTEST_ADDOPTS: "--durations=25 -p no:unraisableexception -p no:threadexception" + OMP_NUM_THREADS: 4 + OPENBLAS_NUM_THREADS: 4 + MKL_NUM_THREADS: 4 + VECLIB_MAXIMUM_THREADS: 4 + NUMEXPR_NUM_THREADS: 4 + OMP_WAIT_POLICY: PASSIVE steps: - name: Checkout repo uses: actions/checkout@v6 diff --git a/.github/workflows/python-tests.yaml b/.github/workflows/python-tests.yaml index 4e682b6ed72..51fc0ad7569 100644 --- a/.github/workflows/python-tests.yaml +++ b/.github/workflows/python-tests.yaml @@ -140,6 +140,12 @@ jobs: env: PYTHONUNBUFFERED: 1 PYTEST_ADDOPTS: "--durations=25 -p no:unraisableexception -p no:threadexception" + OMP_NUM_THREADS: 4 + OPENBLAS_NUM_THREADS: 4 + MKL_NUM_THREADS: 4 + VECLIB_MAXIMUM_THREADS: 4 + NUMEXPR_NUM_THREADS: 4 + OMP_WAIT_POLICY: PASSIVE steps: - name: Checkout repo uses: actions/checkout@v6 diff --git a/policyengine_us/tests/unit/test_ss_calculator_differential.py b/policyengine_us/tests/unit/test_ss_calculator_differential.py index e4e7325cc09..2014996c4ba 100644 --- a/policyengine_us/tests/unit/test_ss_calculator_differential.py +++ b/policyengine_us/tests/unit/test_ss_calculator_differential.py @@ -129,6 +129,15 @@ def _cached_reference_values(simulation): ] +def _reference_simulation(situation): + """Let the US wrapper clone once and Core remove the feature once.""" + return Simulation( + situation=deepcopy(situation), + tax_benefit_system=Simulation.default_tax_benefit_system_instance, + reform=WithoutHouseholdCalculator, + ) + + @pytest.mark.parametrize( "situation", [ @@ -141,13 +150,7 @@ def _cached_reference_values(simulation): ids=("working", "early-retirement", "survivor", "disability", "own-record-couple"), ) def test_calculator_off_matches_model_without_feature(situation): - isolated = Simulation.default_tax_benefit_system_instance.clone() - isolated.apply_reform_set(WithoutHouseholdCalculator) - reference = Simulation( - situation=deepcopy(situation), - tax_benefit_system=isolated, - reform=WithoutHouseholdCalculator, - ) + reference = _reference_simulation(situation) off_inputs = deepcopy(situation) for person in off_inputs["people"].values(): person["ss_calculator_source"] = "off" @@ -197,19 +200,15 @@ def test_legacy_public_input_and_later_zero_override_survive(amount): def test_off_unselected_history_does_not_change_irmaa_lookback(): """Calculator records are not a past-year tax return supplied to the model.""" situation = _situation(75, (30_000, 0, 0, 0), investment_income=150_000) - isolated = Simulation.default_tax_benefit_system_instance.clone() - isolated.apply_reform_set(WithoutHouseholdCalculator) - reference = Simulation( - situation=deepcopy(situation), - tax_benefit_system=isolated, - reform=WithoutHouseholdCalculator, - ) + reference = _reference_simulation(situation) situation["people"]["worker"].update( { "ss_calculator_source": "off", "ss_calculator_annual_earnings": {2020: 50_000}, "ss_calculator_pre_fra_earnings": {2020: 20_000}, "ss_calculator_withhold_cola": {2020: True}, + "ss_calculated_retirement": {2020: 0}, + "ss_calculated_payment": {"2020-01": 0}, } ) actual = Simulation(situation=situation) diff --git a/policyengine_us/tests/unit/test_ss_calculator_engine.py b/policyengine_us/tests/unit/test_ss_calculator_engine.py index b7605d71bd6..eb09cc6fe38 100644 --- a/policyengine_us/tests/unit/test_ss_calculator_engine.py +++ b/policyengine_us/tests/unit/test_ss_calculator_engine.py @@ -17,19 +17,18 @@ def _simulation(*, situation, reform=None): - """Apply parameter-only variants to an isolated, processed runtime clone. + """Apply each variant once to the wrapper's isolated runtime clone. - Supplying the prepared system avoids reconstructing the full country for - every variant. Keep the reform argument as the Simulation baseline marker; - Core does not apply it again when a tax-benefit system is supplied. + Passing the processed default system avoids reconstructing the country. + The US wrapper clones supplied policy when a reform is present, and Core + then applies the reform. Precloning or preapplying here would duplicate + that work and keep a second full policy tree alive during construction. """ if reform is None: return Simulation(situation=situation) - isolated = Simulation.default_tax_benefit_system_instance.clone() - isolated.apply_reform_set(reform) return Simulation( situation=situation, - tax_benefit_system=isolated, + tax_benefit_system=Simulation.default_tax_benefit_system_instance, reform=reform, ) @@ -274,7 +273,9 @@ def test_annual_earnings_input_is_allocated_to_entitlement_months_before_checks( assert simulation.calculate("ss_calculated_benefit", "2026-01")[0] == 0 assert simulation.calculate("ss_calculated_payment", "2026-02")[0] == 0 assert simulation.calculate("ss_calculated_payment", "2026-03")[0] == 1000 - assert simulation.calculate("ss_calculated_annual_entitlement", 2026)[0] == 11000 + # December entitlement includes the 3.6% COLA first paid January2027; + # that $36 increase belongs to this entitlement total, not 2026 checks. + assert simulation.calculate("ss_calculated_annual_entitlement", 2026)[0] == 11036 assert simulation.calculate("ss_calculated_annual_payment", 2026)[0] == 10000 @@ -285,7 +286,7 @@ def test_s770_parameter_schedule_reaches_old_cohort_at_2026(): "worker": _record( ss_calculator_source="aime", ss_calculator_supplied_aime=5000, - ss_calculator_birth_date="1960-01-02", + ss_calculator_birth_date="1958-01-02", ss_calculator_entitlement_month="2020-01", ss_calculator_eligibility_year=2020, ) diff --git a/policyengine_us/tools/general.py b/policyengine_us/tools/general.py index 0fdd43fdaa1..891bfdd10f9 100644 --- a/policyengine_us/tools/general.py +++ b/policyengine_us/tools/general.py @@ -54,8 +54,9 @@ def earliest_input_year(simulation): Inputs of a variable the tax-benefit system no longer has, or has neutralized, are skipped: they are never read. Social Security calculator - record inputs are also skipped: a historical earnings-test amount or COLA - decision is not a tax-year income return for the IRMAA lookback. As with + records and output overrides are also skipped: a historical earnings-test + amount, COLA decision or calculator result is not a tax-year income return + for the IRMAA lookback. As with ``has_input_for_period``, core versions before 3.32.27 can keep an input key after the input is deleted, and a value recalculated for that period then still counts. Formulas that read this cache their @@ -68,7 +69,7 @@ def earliest_input_year(simulation): if ( branch_name in visible_branches and period.unit != ETERNITY - and not variable.startswith("ss_calculator_") + and not variable.startswith(("ss_calculator_", "ss_calculated_")) and variable in variables and not variables[variable].is_neutralized ): From 88bfa1bd1df4082ac8f597b185942fb96009d9aa Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 23 Oct 2026 04:56:44 -0400 Subject: [PATCH 10/16] Require exact-year earnings and COLA withholding records --- docs/usage/social-security-calculator.md | 5 +++- .../tests/unit/test_ss_calculator_engine.py | 10 +++++++ .../tools/social_security/engine.py | 29 ++++++++++++++----- 3 files changed, 36 insertions(+), 8 deletions(-) diff --git a/docs/usage/social-security-calculator.md b/docs/usage/social-security-calculator.md index bac6db0e6cd..04b764b5b9e 100644 --- a/docs/usage/social-security-calculator.md +++ b/docs/usage/social-security-calculator.md @@ -81,7 +81,8 @@ count. No earnings test applies from FRA onward. Annual excess-earnings deductions are truncated to whole dollars, allocated to the earliest affected benefit months and capped at their benefits. Calculating January's check may also require the previous year's earnings. A `-1` earnings input means missing, -not zero. Alternatively assert `ss_calculator_earnings_test_no_trigger`; supplied +not zero. Each annual earnings record must be supplied for its exact year; +an earlier record never carries forward. Alternatively assert `ss_calculator_earnings_test_no_trigger`; supplied excess earnings contradicting it fail. This route requires `ss_calculator_no_special_monthly_test` and @@ -173,6 +174,8 @@ payment-year parameters reused from #10400. COLA settings also accept an effective year/month, payment start/end year and a supplied alternative rate. The annual person input `ss_calculator_withhold_cola` accepts an externally resolved E3 decision when `cola.withholding_enabled` is true. +Each withholding decision applies only in its supplied year; an absent year's +decision is false. Withholding sets that event's COLA to zero, jointly with any rate change; no second COLA factor is applied. Payable shares must lie in [0,1], and rates must not imply a negative benefit. A depletion-year midyear blend is supplied in the diff --git a/policyengine_us/tests/unit/test_ss_calculator_engine.py b/policyengine_us/tests/unit/test_ss_calculator_engine.py index eb09cc6fe38..16c6fa9d6af 100644 --- a/policyengine_us/tests/unit/test_ss_calculator_engine.py +++ b/policyengine_us/tests/unit/test_ss_calculator_engine.py @@ -277,6 +277,10 @@ def test_annual_earnings_input_is_allocated_to_entitlement_months_before_checks( # that $36 increase belongs to this entitlement total, not 2026 checks. assert simulation.calculate("ss_calculated_annual_entitlement", 2026)[0] == 11036 assert simulation.calculate("ss_calculated_annual_payment", 2026)[0] == 10000 + # Country input carry-forward must not reuse the 2026 earnings record as + # a supplied 2027 observation. The next year's annual test needs its data. + with pytest.raises(ValueError, match="Supply annual earnings"): + simulation.calculate("ss_calculated_annual_payment", 2027) def test_s770_parameter_schedule_reaches_old_cohort_at_2026(): @@ -373,6 +377,12 @@ def test_joint_cola_withholding_pp_change_and_payment_factors_apply_once(): np.testing.assert_array_equal( simulation.calculate("ss_calculated_payment", "2027-01"), [913, 880] ) + # Only the supplied 2027 decision withholds a COLA. January2028's 1.1% + # baseline plus .15 percentage points applies to both records; after the + # continuing .88 payment factor, the checks are924 and891 dollars. + np.testing.assert_array_equal( + simulation.calculate("ss_calculated_payment", "2028-01"), [924, 891] + ) def test_common_cola_alternative_rate_effective_window_and_withholding_gate(): diff --git a/policyengine_us/tools/social_security/engine.py b/policyengine_us/tools/social_security/engine.py index 6a6ffa290c5..38b8d312055 100644 --- a/policyengine_us/tools/social_security/engine.py +++ b/policyengine_us/tools/social_security/engine.py @@ -5,6 +5,8 @@ import numpy as np +from policyengine_us.tools.general import has_input_for_period + from .cola import read_parameter_events from .household import BenefitPolicies, SuppliedRecord, SurvivorBasis, calculate_year from .parameters import bend_points_at, formula_path_at @@ -119,12 +121,19 @@ def money(name, when=period): ) for earnings_year in (year - 1, year): when = str(earnings_year) - amount = money("annual_earnings", when) - pre = money("pre_fra_earnings", when) - if amount >= 0: - earnings[earnings_year] = amount - if pre >= 0: - before_fra[earnings_year] = pre + # These are dated records. Core otherwise carries an earlier pure + # annual input forward, which would turn missing earnings into an + # invented observation for a later earnings-test year. + for field, destination in ( + ("annual_earnings", earnings), + ("pre_fra_earnings", before_fra), + ): + if has_input_for_period( + person.simulation, "ss_calculator_" + field, when + ): + amount = money(field, when) + if amount >= 0: + destination[earnings_year] = amount test = parameters.gov.ssa.social_security.earnings_test(f"{when}-01-01") lower[earnings_year] = test.exempt_amount_under_fra higher[earnings_year] = test.exempt_amount_year_of_fra @@ -158,7 +167,13 @@ def money(name, when=period): not policy.end_year or payment_year <= policy.end_year ) withheld = bool( - policy.withholding_enabled and value("withhold_cola", str(payment_year)) + policy.withholding_enabled + and has_input_for_period( + person.simulation, + "ss_calculator_withhold_cola", + str(payment_year), + ) + and value("withhold_cola", str(payment_year)) ) changes[payment_year] = delta if applies else Decimal(0) if applies and alternative >= 0: From e82050412b84e162eca9c8df47ce04e7f4914ebc Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 26 Oct 2026 03:23:21 -0700 Subject: [PATCH 11/16] Preserve S.770 bend increase for prior disability survivors --- docs/usage/social-security-calculator.md | 17 +++++---- docs/usage/social-security/RULINGS.md | 23 +++++++----- ...pute_pre2026_death_before_eligibility.yaml | 2 +- .../unit/test_ss_household_calculator.py | 36 +++++++++++++++++++ .../tools/social_security/household.py | 6 +++- 5 files changed, 68 insertions(+), 16 deletions(-) diff --git a/docs/usage/social-security-calculator.md b/docs/usage/social-security-calculator.md index 04b764b5b9e..88a06aa516e 100644 --- a/docs/usage/social-security-calculator.md +++ b/docs/usage/social-security-calculator.md @@ -117,8 +117,9 @@ January 1 attainment uses the preceding year. A year-only fallback requires `year_only_not_january_1`; death and age-62 attainment in the same year require exact dates or `same_year_death_before_62` (1/0; -1 means unspecified). -COLAs for a pre-62 death begin with December of the death benchmark, paid the -following January. Recovery propagates the supplied final-payment interval +COLAs begin with December of the accepted computation benchmark, paid the +following January. For a pre-62 death without prior eligibility, this is the +death benchmark. Recovery propagates the supplied final-payment interval backward through the composite ratio and **every rounded COLA**, retaining a half-open eligibility-PIA interval. The lower admissible dime is the point convention; baseline forward computation must reproduce the supplied payment. @@ -127,10 +128,14 @@ endpoint and expose the corresponding AIME interval. Zero stays zero. The default-false parameter `gov.contrib.congress.s770.section_2.recompute_pre2026_death_before_eligibility` -controls only the 18% first-bend-point increase for the pre-2026 death-before-62 -subset. The 95% first factor still applies when false. Deaths in 2026 or later -receive both changes independently of that switch. See [the recorded modeling -ruling](social-security/RULINGS.md). +controls only the 18% first-bend-point increase for pre-2026 deaths before any +initial eligibility. This requires both death before age 62 and the +`no_prior_disability` assertion. The 95% first factor still applies when false. +An accepted authoritative prior-disability benchmark receives both changes +regardless of the switch, as do deaths in 2026 or later. S.770 section 2(c)(2)(B) includes +initial disability eligibility before 2026. See [the recorded modeling +ruling](social-security/RULINGS.md) and [the bill +text](https://www.congress.gov/bill/119th-congress/senate-bill/770/text). ## Shared PIA paths and policies diff --git a/docs/usage/social-security/RULINGS.md b/docs/usage/social-security/RULINGS.md index b48bd22b55b..318e358b4a8 100644 --- a/docs/usage/social-security/RULINGS.md +++ b/docs/usage/social-security/RULINGS.md @@ -1,15 +1,22 @@ # Restricted-survivor modeling ruling -For the contributed S.770 section 2 preset, a worker who died before 2026 and -before attaining 62 receives the 95% first factor at the death-based computation -benchmark. The parameter +For the contributed S.770 section 2 preset, a worker who died before 2026, +before attaining 62, and without prior disability eligibility receives the 95% +first factor at the death-based computation benchmark. The parameter `recompute_pre2026_death_before_eligibility` controls **only** the 18% increase to that benchmark's first bend point. False therefore retains the 95% factor; -true applies both changes. Deaths after 2025 are outside this switch. +true applies both changes. Deaths after 2025 and workers with accepted +authoritative prior-disability eligibility are outside this switch. -This is an explicit scenario interpretation, not a statutory conclusion. The -switch defaults false and must be recorded with the scenario. For AIME above -the increased first bend point, the raw monthly gain is .05 * original BP1 -with the switch false, or .1634 * original BP1 with it true. +Section 2(c)(2)(B) covers workers who “initially became eligible for old-age or +disability insurance benefits before January 1, 2026”. Prior disability is +initial eligibility, so the 18% increase applies at that earlier benchmark +regardless of this switch. + +For deaths without prior initial eligibility, this is an explicit scenario +interpretation, not a statutory conclusion. The switch defaults false and +must be recorded with the scenario. For AIME above the increased first bend +point, the raw monthly gain is .05 * original BP1 with the switch false, or +.1634 * original BP1 with it true. Source: [119th Congress S.770, section 2(a) and (c)](https://www.congress.gov/bill/119th-congress/senate-bill/770/text). diff --git a/policyengine_us/parameters/gov/contrib/congress/s770/section_2/recompute_pre2026_death_before_eligibility.yaml b/policyengine_us/parameters/gov/contrib/congress/s770/section_2/recompute_pre2026_death_before_eligibility.yaml index 9757a0f3e9f..804c8a15178 100644 --- a/policyengine_us/parameters/gov/contrib/congress/s770/section_2/recompute_pre2026_death_before_eligibility.yaml +++ b/policyengine_us/parameters/gov/contrib/congress/s770/section_2/recompute_pre2026_death_before_eligibility.yaml @@ -1,4 +1,4 @@ -description: Whether S.770 section 2 increases the first bend point for a pre-2026 death before age-62 eligibility; the 95 percent first factor applies either way in this modeled interpretation. +description: Whether S.770 section 2 increases the first bend point for a pre-2026 death before any initial eligibility, requiring death before age 62 and no prior disability eligibility; the 95 percent first factor applies either way in this modeled interpretation. Accepted authoritative prior-disability eligibility receives both increases regardless of this switch. values: 1983-01-01: false metadata: diff --git a/policyengine_us/tests/unit/test_ss_household_calculator.py b/policyengine_us/tests/unit/test_ss_household_calculator.py index 634489c18ba..71ae3792c88 100644 --- a/policyengine_us/tests/unit/test_ss_household_calculator.py +++ b/policyengine_us/tests/unit/test_ss_household_calculator.py @@ -988,3 +988,39 @@ def test_s770_starts_with_january_entitlement_and_its_february_check(): def test_restricted_survivor_excludes_child_and_disabled_early_entitlement(birth): with pytest.raises(ValueError, match="restricted survivor route excludes"): compute(survivor(birth_date=birth)) + + +@pytest.mark.parametrize("flag", [False, True]) +def test_s770_prior_disability_survivor_retains_bend_increase(flag): + # The worker was continuously DIB-eligible from 2018 until death in 2020. + # Section 2(c)(2)(B) treats prior disability as initial eligibility: + # https://www.congress.gov/bill/119th-congress/senate-bill/770/text + # Historical bends and COLAs: + # https://www.ssa.gov/oact/cola/bendpoints.html + # https://www.ssa.gov/oact/cola/colaseries.html + record = survivor( + survivor=survivor_basis( + authoritative_year=2018, + no_prior_disability=False, + provenance="Continuous DIB eligibility from 2018 until August 2020 death", + ), + entitlement_month="2020-08", + monthly_amount=D(2088), + valuation_month="2020-11", + ) + rates = (".028", ".016", ".013", ".059", ".087", ".032", ".025", ".028") + events = [ + ColaEvent(f"{year}-12", f"{year + 1}-01", D(rate)) + for year, rate in zip(range(2018, 2026), rates) + ] + result = calculate_year( + record, + 2026, + bend_points=(895, 5397), + cola_events=events, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + s770_survivor_bend_increase=flag, + ) + assert record.benchmark() == 2018 + assert row_for(result, "2026-01").payable_benefit == 2841 diff --git a/policyengine_us/tools/social_security/household.py b/policyengine_us/tools/social_security/household.py index 060e256f1d7..02eb43551e7 100644 --- a/policyengine_us/tools/social_security/household.py +++ b/policyengine_us/tools/social_security/household.py @@ -438,7 +438,11 @@ def calculate_year( restricted_survivor = False if record.source == "survivor": _, before62 = record.survivor.benchmark() - restricted_survivor = before62 and record.survivor.death_year < 2026 + restricted_survivor = ( + before62 + and record.survivor.death_year < 2026 + and record.survivor.no_prior_disability + ) death_month = ( record.survivor.death_date.strftime("%Y-%m") if record.survivor.death_date From cc165d4d856b3ab7b554fb77b75284a219d0e896 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 26 Oct 2026 04:13:19 -0700 Subject: [PATCH 12/16] Defer partial earnings-test payments until dated settlement --- .../ss-household-calculator-4a1.added.md | 1 + docs/usage/social-security-calculator.md | 29 +++++- .../ss_calculated_benefit.yaml | 78 ++++++++++++++++ .../tests/unit/test_ss_calculator_engine.py | 6 ++ .../unit/test_ss_household_calculator.py | 90 +++++++++++++++++-- .../tools/social_security/engine.py | 61 +++++++++++-- .../tools/social_security/household.py | 85 ++++++++++++++++-- .../ssa/social_security/calculator/inputs.py | 33 +++++++ .../ssa/social_security/calculator/results.py | 52 +++++++++-- 9 files changed, 407 insertions(+), 28 deletions(-) diff --git a/changelog.d/ss-household-calculator-4a1.added.md b/changelog.d/ss-household-calculator-4a1.added.md index a27f457f59b..173fbed2677 100644 --- a/changelog.d/ss-household-calculator-4a1.added.md +++ b/changelog.d/ss-household-calculator-4a1.added.md @@ -1 +1,2 @@ Add an opt-in supplied-AIME/PIA Social Security household calculator and shared eligibility-year PIA service. +Preserve S.770 bend increases after prior disability eligibility and use whole-month earnings-test withholding with explicitly dated later settlements by default. diff --git a/docs/usage/social-security-calculator.md b/docs/usage/social-security-calculator.md index 88a06aa516e..49103d47285 100644 --- a/docs/usage/social-security-calculator.md +++ b/docs/usage/social-security-calculator.md @@ -56,7 +56,9 @@ checks = simulation.calculate("ss_calculated_annual_payment", 2023) ``` `ss_calculated_benefit` is the payable amount for an **entitlement month**; -`ss_calculated_payment` is the check paid the following month. +`ss_calculated_payment` is cash paid in the requested month, including any +supplied earnings-test settlement. Ordinary checks follow entitlement by one +month, subject to whole-month earnings-test withholding. `ss_calculated_annual_entitlement` sums January–December entitlement, whereas `ss_calculated_annual_payment` sums checks actually paid January–December. `ss_calculated_retirement` and `ss_calculated_survivors` expose the latter by @@ -85,6 +87,31 @@ not zero. Each annual earnings record must be supplied for its exact year; an earlier record never carries forward. Alternatively assert `ss_calculator_earnings_test_no_trigger`; supplied excess earnings contradicting it fail. +The default cash schedule withholds whole months, including the month whose +deduction leaves a partial entitlement. That remainder is deferred until +closed-year earnings reporting. [SSA Handbook §1806.2](https://www.ssa.gov/OP_Home/handbook/handbook.18/handbook-1806.html) +says, “The partial payment is paid only at the close of the taxable year”, +“unless otherwise requested”. [POMS RS 02501.110](https://secure.ssa.gov/poms.nsf/lnx/0302501110) +says, “Once we receive the closed-year earnings, pay a partial monthly benefit, if due.” + +`ss_calculated_deferred_earnings_test_payment` reports the remainder deferred +from this entitlement year. Supply `ss_calculator_earnings_test_settlement_month` +for the **original earnings year**, with its actual later `YYYY-MM` payment +month, to include settlement in that month's and year's cash totals. A date +in or before the earnings year fails. Without a supplied date, the settlement +remains pending; the calculator does not assume when earnings are reported. +Settlement never changes the original entitlement or earnings-test deduction. + +Set `ss_calculator_immediate_earnings_test_payment` to true only when immediate +partial payment was requested; it defaults false. The pure `calculate_year` +API exposes the same choice as `immediate_earnings_test_payment` and accepts +an earnings-year-to-month `earnings_test_settlement_months` mapping. Ledger +rows retain `payable_benefit` as entitlement and expose `payment_amount` after +deferral; dated settlement payments appear separately in `AnnualBenefit.settlements`. +For January 2026 commencement, $800 monthly benefits and $33,400 earnings, +the deduction is $4,460 and annual entitlement $5,140. Default 2026 checks total +$4,000 with $340 deferred; requested immediate partial payment gives $4,340. + This route requires `ss_calculator_no_special_monthly_test` and `ss_calculator_no_prior_withholding_adjustment`. These assert that special first-year monthly/service rules and actuarial adjustments for prior withheld diff --git a/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml b/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml index 3c7dcff43d9..cbd0e0cc19a 100644 --- a/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml +++ b/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml @@ -51,3 +51,81 @@ ss_calculated_retirement: 0 ss_calculated_survivors: 0 social_security_retirement: 20000 + +- name: Whole-month earnings withholding defers the partial month until a supplied settlement + # Handbook 1806.2 and POMS RS 02501.110: partial payment follows closed-year reporting. + # https://www.ssa.gov/OP_Home/handbook/handbook.18/handbook-1806.html + # https://secure.ssa.gov/poms.nsf/lnx/0302501110 + period: 2026 + input: &earnings_test_record + # Hold COLAs at zero to isolate the published $800 earnings-test example. + gov.contrib.ssa.benefit_levers.cola.alternative_rate: 0 + gov.contrib.ssa.benefit_levers.cola.start_year: 2026 + ss_calculator_source: pia + ss_calculator_worker_id: worker-earnings-test + ss_calculator_birth_date: '1964-01-02' + ss_calculator_eligibility_year: 2026 + ss_calculator_entitlement_month: '2026-01' + ss_calculator_supplied_pia: 800 + ss_calculator_claiming_factor: '1' + ss_calculator_insured: true + ss_calculator_no_special_monthly_test: true + ss_calculator_no_prior_withholding_adjustment: true + ss_calculator_annual_earnings: + 2026: 33400 + 2027: 0 + 2028: 0 + ss_calculator_earnings_test_settlement_month: + 2026: '2027-03' + output: + ss_calculated_earnings_test_reduction: + 2026: 4460 + 2027: 0 + ss_calculated_annual_entitlement: + 2026: 5140 + 2027: 9600 + ss_calculated_annual_payment: + 2026: 4000 + 2027: 9940 + ss_calculated_deferred_earnings_test_payment: + 2026: 340 + 2027: 0 + ss_calculated_benefit: + 2026-06: 340 + ss_calculated_payment: + 2026-07: 0 + 2026-08: 800 + 2027-02: 800 + 2027-03: 1140 + 2027-04: 800 + 2028-03: 800 + +- name: Requested immediate partial earnings-test payment is explicit + period: 2026 + input: + <<: *earnings_test_record + ss_calculator_immediate_earnings_test_payment: true + output: + ss_calculated_earnings_test_reduction: 4460 + ss_calculated_annual_entitlement: 5140 + ss_calculated_deferred_earnings_test_payment: 0 + ss_calculated_annual_payment: + 2026: 4340 + 2027: 9600 + ss_calculated_payment: + 2026-07: 340 + 2027-03: 800 + +- name: Delayed earnings-test settlement loads its original earnings year + period: 2028 + input: + <<: *earnings_test_record + ss_calculator_earnings_test_settlement_month: + 2026: '2028-03' + output: + ss_calculated_annual_payment: + 2027: 9600 + 2028: 9940 + ss_calculated_payment: + 2027-03: 800 + 2028-03: 1140 diff --git a/policyengine_us/tests/unit/test_ss_calculator_engine.py b/policyengine_us/tests/unit/test_ss_calculator_engine.py index 16c6fa9d6af..59c236c7392 100644 --- a/policyengine_us/tests/unit/test_ss_calculator_engine.py +++ b/policyengine_us/tests/unit/test_ss_calculator_engine.py @@ -281,6 +281,12 @@ def test_annual_earnings_input_is_allocated_to_entitlement_months_before_checks( # a supplied 2027 observation. The next year's annual test needs its data. with pytest.raises(ValueError, match="Supply annual earnings"): simulation.calculate("ss_calculated_annual_payment", 2027) + # Reject a same-year settlement immediately, using this existing model. + simulation.set_input( + "ss_calculator_earnings_test_settlement_month", 2026, ["2026-07"] + ) + with pytest.raises(ValueError, match="must follow the earnings year"): + simulation.calculate("ss_calculated_payment", "2026-04") def test_s770_parameter_schedule_reaches_old_cohort_at_2026(): diff --git a/policyengine_us/tests/unit/test_ss_household_calculator.py b/policyengine_us/tests/unit/test_ss_household_calculator.py index 71ae3792c88..f8a6c04b9de 100644 --- a/policyengine_us/tests/unit/test_ss_household_calculator.py +++ b/policyengine_us/tests/unit/test_ss_household_calculator.py @@ -350,7 +350,8 @@ def test_complete_payable_cut_is_valid_and_negative_benefits_are_rejected(): compute(record, policies=policies) -def test_ssa_published_under_fra_earnings_test(): +@pytest.mark.parametrize("immediate", [None, False, True]) +def test_ssa_published_under_fra_earnings_test(immediate): # https://www.ssa.gov/benefits/retirement/planner/whileworking.html record = retirement( birth_date=date(1964, 1, 2), @@ -360,14 +361,86 @@ def test_ssa_published_under_fra_earnings_test(): supplied_claiming_factor=D(1), earnings_test_no_trigger=False, ) - result = compute(record, earnings={2026: 33400}, lower_exempt={2026: 24480}) + options = ( + {} if immediate is None else {"immediate_earnings_test_payment": immediate} + ) + result = compute( + record, earnings={2026: 33400}, lower_exempt={2026: 24480}, **options + ) assert result.earnings_test_reduction == 4460 assert result.entitlement_total == 5140 + # Handbook 1806.2 and RS02501.110 defer the partial June benefit until + # closed-year earnings reporting unless immediate payment is requested. + # https://www.ssa.gov/OP_Home/handbook/handbook.18/handbook-1806.html + # https://secure.ssa.gov/poms.nsf/lnx/0302501110 + june = row_for(result, "2026-06") + assert june.payable_benefit == 340 + assert june.payment_month == "2026-07" + assert june.payment_amount == (340 if immediate else 0) + assert result.deferred_earnings_test_payment == (0 if immediate else 340) + assert result.payment_total == (4340 if immediate else 4000) + assert not result.settlements assert all( row.earnings_test_reduction <= row.gross_benefit for row in result.ledger ) +@pytest.mark.parametrize("settlement_month", ["2027-03", "2028-03"]) +def test_deferred_earnings_test_payment_requires_a_dated_closed_year_settlement( + settlement_month, +): + record = retirement( + birth_date=date(1964, 1, 2), + eligibility_year=2026, + entitlement_month="2026-01", + pia=D(800), + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + year = int(settlement_month[:4]) + inputs = dict( + earnings={year - 1: 0, year: 0, 2026: 33400}, + lower_exempt={2026: 24480, year - 1: 24480, year: 24480}, + ) + pending = compute(record, year, **inputs) + settled = compute( + record, + year, + earnings_test_settlement_months={2026: settlement_month}, + **inputs, + ) + assert pending.payment_total == 9600 + assert settled.payment_total == 9940 + assert settled.entitlement_total == 9600 + assert settled.earnings_test_reduction == 0 + assert settled.deferred_earnings_test_payment == 0 + assert len(settled.settlements) == 1 + settlement = settled.settlements[0] + assert (settlement.earnings_year, settlement.payment_month, settlement.amount) == ( + 2026, + settlement_month, + 340, + ) + immediate = compute( + record, + year, + immediate_earnings_test_payment=True, + earnings_test_settlement_months={2026: settlement_month}, + **inputs, + ) + assert immediate.payment_total == 9600 + assert not immediate.settlements + + +@pytest.mark.parametrize("settlement_month", ["2026-07", "2026-12", "2025-12"]) +def test_earnings_test_settlement_cannot_precede_closed_year(settlement_month): + with pytest.raises(ValueError, match="must follow the earnings year"): + compute( + retirement(), + earnings_test_settlement_months={2026: settlement_month}, + ) + + def test_ssa_published_fra_year_earnings_test_counts_only_pre_fra_months(): # https://www.ssa.gov/benefits/retirement/planner/whileworking.html # Birth October1959 yields retirement FRA66y10m in August2026. @@ -422,7 +495,8 @@ def test_earnings_after_retirement_fra_do_not_reduce_benefits(): assert compute(record, 2027, earnings={2027: 1_000_000}).entitlement_total == 12000 -def test_previous_december_withholding_and_request_order_are_consistent(): +@pytest.mark.parametrize("immediate", [False, True]) +def test_previous_december_withholding_and_request_order_are_consistent(immediate): record = retirement( birth_date=date(1964, 1, 2), eligibility_year=2026, @@ -432,12 +506,15 @@ def test_previous_december_withholding_and_request_order_are_consistent(): earnings_test_no_trigger=False, ) inputs = dict( - earnings={2026: 43080, 2027: 0}, lower_exempt={2026: 24480, 2027: 24480} + earnings={2026: 43080, 2027: 0}, + lower_exempt={2026: 24480, 2027: 24480}, + immediate_earnings_test_payment=immediate, ) later = compute(record, 2027, **inputs) earlier = compute(record, 2026, **inputs) assert row_for(earlier, "2026-12") == row_for(later, "2026-12") - assert later.payment_total == 9100 # December2026 remaining check300 +11x800. + assert row_for(earlier, "2026-12").payable_benefit == 300 + assert later.payment_total == (9100 if immediate else 8800) def test_no_earnings_test_assertion_rejects_conflicting_observed_earnings(): @@ -919,8 +996,9 @@ def test_prior_year_earnings_test_does_not_require_older_earnings_history(): ) assert row_for(result, "2025-12").earnings_test_reduction == 500 assert row_for(result, "2025-12").payable_benefit == 300 + assert row_for(result, "2025-12").payment_amount == 0 assert result.entitlement_total == 9600 - assert result.payment_total == 9100 + assert result.payment_total == 8800 def test_claiming_dime_truncation_precedes_contributed_benefit_factor(): diff --git a/policyengine_us/tools/social_security/engine.py b/policyengine_us/tools/social_security/engine.py index 38b8d312055..7d1c35734cd 100644 --- a/policyengine_us/tools/social_security/engine.py +++ b/policyengine_us/tools/social_security/engine.py @@ -8,7 +8,13 @@ from policyengine_us.tools.general import has_input_for_period from .cola import read_parameter_events -from .household import BenefitPolicies, SuppliedRecord, SurvivorBasis, calculate_year +from .household import ( + BenefitPolicies, + SuppliedRecord, + SurvivorBasis, + calculate_year, + month_number, +) from .parameters import bend_points_at, formula_path_at from .pia import FormulaPath @@ -102,8 +108,26 @@ def money(name, when=period): ) events = read_parameter_events(parameters, through) earnings, before_fra, lower, higher = {}, {}, {}, {} + settlement_months = {} + earnings_years = {year - 1, year} + for earnings_year in range(benchmark, year + 1): + when = str(earnings_year) + if not has_input_for_period( + person.simulation, + "ss_calculator_earnings_test_settlement_month", + when, + ): + continue + settlement_month = str(value("earnings_test_settlement_month", when)) + if not settlement_month: + continue + settlement_year = month_number(settlement_month) // 12 + settlement_months[earnings_year] = settlement_month + if settlement_year == year: + earnings_years.add(earnings_year) + payment_years = earnings_years | {when + 1 for when in earnings_years} paths, modes, flags = {}, {}, {} - for payment_year in (year - 1, year, year + 1): + for payment_year in sorted(payment_years): if payment_year >= benchmark: paths[payment_year], modes[payment_year] = formula_path_at( parameters, benchmark, payment_year @@ -119,7 +143,7 @@ def money(name, when=period): if payment_year >= 1983 else False ) - for earnings_year in (year - 1, year): + for earnings_year in sorted(earnings_years): when = str(earnings_year) # These are dated records. Core otherwise carries an earlier pure # annual input forward, which would turn missing earnings into an @@ -185,7 +209,7 @@ def money(name, when=period): ) if withheld: withheld_years.append(payment_year) - for payment_year in (year - 1, year, year + 1): + for payment_year in sorted(payment_years): if payment_year < 1983: across[payment_year], payable[payment_year] = Decimal(0), Decimal(1) continue @@ -219,6 +243,10 @@ def money(name, when=period): pre_fra_earnings=before_fra, lower_exempt=lower, higher_exempt=higher, + immediate_earnings_test_payment=bool( + value("immediate_earnings_test_payment") + ), + earnings_test_settlement_months=settlement_months, ) if output in ("retirement", "survivors"): selected = ( @@ -231,6 +259,8 @@ def money(name, when=period): result[index] = float(annual.payment_total) elif output == "earnings_test_reduction": result[index] = float(annual.earnings_test_reduction) + elif output == "deferred_earnings_test_payment": + result[index] = float(annual.deferred_earnings_test_payment) elif output in ("benefit", "payment", "eligibility_pia"): target = ( str(period)[:7] @@ -243,11 +273,24 @@ def money(name, when=period): if (row.payment_month if output == "payment" else row.entitlement_month) == target ) - result[index] = float( - row.eligibility_pia - if output == "eligibility_pia" - else row.payable_benefit - ) + if output == "payment": + result[index] = float( + row.payment_amount + + sum( + ( + settlement.amount + for settlement in annual.settlements + if settlement.payment_month == target + ), + Decimal(0), + ) + ) + else: + result[index] = float( + row.eligibility_pia + if output == "eligibility_pia" + else row.payable_benefit + ) elif output.startswith("pia_") or output.startswith("aime_"): interval = ( annual.eligibility_pia_interval diff --git a/policyengine_us/tools/social_security/household.py b/policyengine_us/tools/social_security/household.py index 02eb43551e7..a2ccaf19ecf 100644 --- a/policyengine_us/tools/social_security/household.py +++ b/policyengine_us/tools/social_security/household.py @@ -1,7 +1,8 @@ """Opt-in gross Social Security ledger for supplied, identified worker records. All amounts are monthly dollars. A ledger row is a benefit entitlement month; -its check is paid in the following month. Both annual entitlement and check +its ordinary check is paid in the following month, subject to whole-month +earnings-test withholding and later settlement. Both annual entitlement and check totals are returned, so a partial year never becomes annual benefit / 12. This module does not compute family, disability, WINDEX or minimum benefits. """ @@ -293,6 +294,18 @@ class EntitlementMonth: gross_benefit: Decimal earnings_test_reduction: Decimal payable_benefit: Decimal + deferred_earnings_test_payment: Decimal = Decimal(0) + + @property + def payment_amount(self): + return self.payable_benefit - self.deferred_earnings_test_payment + + +@dataclass(frozen=True) +class EarningsTestSettlement: + earnings_year: int + payment_month: str + amount: Decimal @dataclass(frozen=True) @@ -303,6 +316,20 @@ class AnnualBenefit: earnings_test_reduction: Decimal eligibility_pia_interval: tuple[Decimal, Decimal] | None = None inferred_aime_interval: tuple[Decimal, Decimal] | None = None + settlements: tuple[EarningsTestSettlement, ...] = () + + @property + def deferred_earnings_test_payment(self): + # The ledger's last row always belongs to the requested entitlement year. + year = self.ledger[-1].entitlement_month[:4] + return sum( + ( + row.deferred_earnings_test_payment + for row in self.ledger + if row.entitlement_month.startswith(year) + ), + Decimal(0), + ) def _source_pia(record, year, bends, baseline_events): @@ -412,6 +439,8 @@ def calculate_year( higher_exempt=None, recompute_mode="cohort", s770_survivor_bend_increase=False, + immediate_earnings_test_payment=False, + earnings_test_settlement_months=None, _include_previous_check=True, ): """Return a 13-row ledger (previous December plus January–December). @@ -421,10 +450,25 @@ def calculate_year( have been withheld. The ordinary annual test is allocated to the earliest affected months. Special monthly/service tests and adjustments for earlier withheld months require explicit no-trigger assertions in this route. + + Whole months are withheld by default; a partial month's remaining entitlement + is deferred until closed-year reporting (Handbook 1806.2, RS 02501.110). + Supply earnings-year -> actual later payment month in + earnings_test_settlement_months to post that settlement. Without a supplied + date it remains pending. immediate_earnings_test_payment represents an + explicit request to pay the partial month immediately instead. """ # The inverse, its reproduction check, and the prior-year earnings-test # ledger all need the same immutable history, including for iterator input. cola_events = tuple(cola_events) + settlement_months = earnings_test_settlement_months or {} + settlement_years = set() + for earnings_year, payment_month in settlement_months.items(): + payment_year = month_number(payment_month) // 12 + if payment_year <= earnings_year: + raise ValueError("Earnings-test settlement must follow the earnings year") + if payment_year == year: + settlement_years.add(earnings_year) benchmark = record.benchmark() baseline_pia, aime, pia_interval = _source_pia( record, benchmark, bend_points, cola_events @@ -576,7 +620,13 @@ def calculate_year( # Evaluate full entitlement years, even when only their last month's check # falls in the requested payment year. This makes request order irrelevant. by_month = {row.entitlement_month: row for row in rows} - for earnings_year in (year - 1, year) if _include_previous_check else (year,): + settlements = [] + earnings_years = ( + sorted({year - 1, year} | settlement_years) + if _include_previous_check + else (year,) + ) + for earnings_year in earnings_years: if ( earnings_year < 2000 and not record.earnings_test_no_trigger @@ -634,7 +684,7 @@ def calculate_year( # RS 02501.080: truncate the annual deduction to whole dollars. remaining = Decimal(int(remaining)) # Fill missing earlier months using the same pure ledger calculation. - if earnings_year == year - 1 and remaining: + if earnings_year < year and remaining: earlier = calculate_year( record, earnings_year, @@ -648,10 +698,23 @@ def calculate_year( higher_exempt=higher_exempt, recompute_mode=recompute_mode, s770_survivor_bend_increase=s770_survivor_bend_increase, + immediate_earnings_test_payment=immediate_earnings_test_payment, _include_previous_check=False, ) old = earlier.ledger[-1] - by_month[old.entitlement_month] = old + if old.entitlement_month in by_month: + by_month[old.entitlement_month] = old + if ( + earnings_year in settlement_years + and earlier.deferred_earnings_test_payment + ): + settlements.append( + EarningsTestSettlement( + earnings_year, + settlement_months[earnings_year], + earlier.deferred_earnings_test_payment, + ) + ) continue for n in relevant: key = month_string(n) @@ -664,6 +727,14 @@ def calculate_year( row, earnings_test_reduction=reduction, payable_benefit=row.gross_benefit - reduction, + # Handbook 1806.2 / RS 02501.110: retain the whole check until + # closed-year reporting unless partial payment was requested. + deferred_earnings_test_payment=( + row.gross_benefit - reduction + if 0 < reduction < row.gross_benefit + and not immediate_earnings_test_payment + else Decimal(0) + ), ) rows = tuple(by_month[row.entitlement_month] for row in rows) return AnnualBenefit( @@ -677,9 +748,10 @@ def calculate_year( Decimal(0), ), sum( - (r.payable_benefit for r in rows if r.payment_month.startswith(str(year))), + (r.payment_amount for r in rows if r.payment_month.startswith(str(year))), Decimal(0), - ), + ) + + sum((settlement.amount for settlement in settlements), Decimal(0)), sum( ( r.earnings_test_reduction @@ -690,4 +762,5 @@ def calculate_year( ), pia_interval, inferred_interval, + tuple(settlements), ) diff --git a/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py b/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py index b408e1093db..1e3fb334a7f 100644 --- a/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py +++ b/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py @@ -136,6 +136,22 @@ class ss_calculator_earnings_test_no_trigger(Variable): documentation = "Assert earnings do not trigger the annual earnings test in the requested years." +class ss_calculator_immediate_earnings_test_payment(Variable): + value_type = bool + entity = Person + definition_period = ETERNITY + default_value = False + label = "Social Security calculator immediate earnings test payment" + documentation = ( + "Explicitly request immediate partial earnings-test payments. By default, " + "whole months are withheld and the remainder awaits closed-year earnings reporting." + ) + reference = ( + "https://www.ssa.gov/OP_Home/handbook/handbook.18/handbook-1806.html", + "https://secure.ssa.gov/poms.nsf/lnx/0302501110", + ) + + class ss_calculator_worker_birth_year(Variable): value_type = int entity = Person @@ -319,6 +335,23 @@ class ss_calculator_annual_earnings(Variable): unit = USD +class ss_calculator_earnings_test_settlement_month(Variable): + value_type = str + entity = Person + definition_period = YEAR + default_value = "" + label = "Social Security calculator earnings test settlement month" + documentation = ( + "Actual partial-benefit settlement check month, YYYY-MM, supplied for the " + "earnings year being settled. The payment year must follow that earnings " + "year. Empty leaves the remainder pending; no settlement date is assumed." + ) + reference = ( + "https://www.ssa.gov/OP_Home/handbook/handbook.18/handbook-1806.html", + "https://secure.ssa.gov/poms.nsf/lnx/0302501110", + ) + + class ss_calculator_pre_fra_earnings(Variable): value_type = float entity = Person diff --git a/policyengine_us/variables/gov/ssa/social_security/calculator/results.py b/policyengine_us/variables/gov/ssa/social_security/calculator/results.py index 9c7aa92b71b..c87878af211 100644 --- a/policyengine_us/variables/gov/ssa/social_security/calculator/results.py +++ b/policyengine_us/variables/gov/ssa/social_security/calculator/results.py @@ -40,7 +40,10 @@ class ss_calculated_annual_entitlement(Variable): definition_period = YEAR unit = USD label = "Calculated Social Security annual entitlement" - documentation = "Sum of payable entitlement months in the calendar year, before Medicare deductions." + documentation = ( + "Sum of payable entitlement months in the calendar year, before Medicare " + "deductions, including partial earnings-test benefits awaiting settlement." + ) reference = "https://www.ssa.gov/oact/cola/colaapplic.html" def formula(person, period, parameters): @@ -53,8 +56,16 @@ class ss_calculated_annual_payment(Variable): definition_period = YEAR unit = USD label = "Calculated Social Security annual payment" - documentation = "Sum of gross checks paid in the calendar year; each check follows entitlement by one month." - reference = "https://www.ssa.gov/oact/cola/colaapplic.html" + documentation = ( + "Sum of gross checks paid in the calendar year, including explicitly " + "dated settlements. Ordinary checks follow entitlement by one month; " + "whole-month earnings-test withholding defers partial benefits until " + "closed-year reporting unless immediate payment is explicitly requested." + ) + reference = ( + "https://www.ssa.gov/OP_Home/handbook/handbook.18/handbook-1806.html", + "https://secure.ssa.gov/poms.nsf/lnx/0302501110", + ) def formula(person, period, parameters): return calculator_output(person, period, parameters, "annual_payment") @@ -75,13 +86,37 @@ def formula(person, period, parameters): return calculator_output(person, period, parameters, "earnings_test_reduction") +class ss_calculated_deferred_earnings_test_payment(Variable): + value_type = float + entity = Person + definition_period = YEAR + unit = USD + label = "Calculated Social Security deferred earnings test payment" + documentation = ( + "Partial benefit withheld from this earnings year's ordinary checks, " + "payable after closed-year earnings reporting. No settlement date is assumed." + ) + reference = ( + "https://www.ssa.gov/OP_Home/handbook/handbook.18/handbook-1806.html", + "https://secure.ssa.gov/poms.nsf/lnx/0302501110", + ) + + def formula(person, period, parameters): + return calculator_output( + person, period, parameters, "deferred_earnings_test_payment" + ) + + class ss_calculated_benefit(Variable): value_type = float entity = Person definition_period = MONTH unit = USD label = "Calculated Social Security benefit" - documentation = "Payable gross benefit for this entitlement month; the check follows next month." + documentation = ( + "Payable gross benefit for this entitlement month, including any partial " + "earnings-test benefit whose payment is deferred until settlement." + ) reference = "https://www.ssa.gov/oact/cola/colaapplic.html" def formula(person, period, parameters): @@ -95,9 +130,14 @@ class ss_calculated_payment(Variable): unit = USD label = "Calculated Social Security payment" documentation = ( - "Gross benefit check in this month for the preceding entitlement month." + "Gross benefit checks in this month, including explicitly dated settlements. " + "The preceding entitlement month's partial earnings-test benefit is " + "withheld pending closed-year reporting unless immediate payment is requested." + ) + reference = ( + "https://www.ssa.gov/OP_Home/handbook/handbook.18/handbook-1806.html", + "https://secure.ssa.gov/poms.nsf/lnx/0302501110", ) - reference = "https://www.ssa.gov/oact/cola/colaapplic.html" def formula(person, period, parameters): return calculator_output(person, period, parameters, "payment") From cdab786f9e24a595676848086ca019664c73ca5b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 26 Oct 2026 15:15:20 -0700 Subject: [PATCH 13/16] Require explicit prior disability eligibility on survivor records --- .../ss-household-calculator-4a1.added.md | 1 + docs/usage/social-security-calculator.md | 14 +- docs/usage/social-security/RULINGS.md | 10 ++ .../ss_calculated_benefit.yaml | 53 +++++++ .../tests/unit/test_ss_calculator_engine.py | 50 ++++++- .../unit/test_ss_household_calculator.py | 131 +++++++++++++++++- .../tools/social_security/engine.py | 8 +- .../tools/social_security/household.py | 11 +- .../ssa/social_security/calculator/inputs.py | 15 +- 9 files changed, 273 insertions(+), 20 deletions(-) diff --git a/changelog.d/ss-household-calculator-4a1.added.md b/changelog.d/ss-household-calculator-4a1.added.md index 173fbed2677..9583628166e 100644 --- a/changelog.d/ss-household-calculator-4a1.added.md +++ b/changelog.d/ss-household-calculator-4a1.added.md @@ -1,2 +1,3 @@ Add an opt-in supplied-AIME/PIA Social Security household calculator and shared eligibility-year PIA service. Preserve S.770 bend increases after prior disability eligibility and use whole-month earnings-test withholding with explicitly dated later settlements by default. +Require an explicit prior-disability eligibility answer for every supplied survivor record. diff --git a/docs/usage/social-security-calculator.md b/docs/usage/social-security-calculator.md index 49103d47285..adca67d9941 100644 --- a/docs/usage/social-security-calculator.md +++ b/docs/usage/social-security-calculator.md @@ -138,8 +138,15 @@ withholding in the source valuation, and ordinary non-WINDEX scope. The `ss_calculator_worker_birth_year`, `death_year`, optional exact worker birth and death dates, optional `authoritative_year`, and `basis_provenance` identify -the computation benchmark. Without an authoritative basis, assert no prior -worker disability. Derive E as the earlier of death and age-62 attainment. +the computation benchmark. Every survivor record must explicitly supply +`ss_calculator_prior_disability_eligibility`: 1 means the worker initially +became eligible through disability before death; 0 means no prior eligibility. +The default -1 means unspecified and raises `ValueError`, as does any other +value. The pure `SurvivorBasis` input is `prior_disability_eligibility`, with +`True`/`False` for the same answers and `None` meaning unspecified. +Prior eligibility requires an authoritative computation basis. With no prior +eligibility, derive E as the earlier of death and age-62 attainment unless an +authoritative basis is supplied. January 1 attainment uses the preceding year. A year-only fallback requires `year_only_not_january_1`; death and age-62 attainment in the same year require exact dates or `same_year_death_before_62` (1/0; -1 means unspecified). @@ -157,7 +164,8 @@ The default-false parameter `gov.contrib.congress.s770.section_2.recompute_pre2026_death_before_eligibility` controls only the 18% first-bend-point increase for pre-2026 deaths before any initial eligibility. This requires both death before age 62 and the -`no_prior_disability` assertion. The 95% first factor still applies when false. +explicit answer `ss_calculator_prior_disability_eligibility=0`. The 95% first +factor still applies when false. An accepted authoritative prior-disability benchmark receives both changes regardless of the switch, as do deaths in 2026 or later. S.770 section 2(c)(2)(B) includes initial disability eligibility before 2026. See [the recorded modeling diff --git a/docs/usage/social-security/RULINGS.md b/docs/usage/social-security/RULINGS.md index 318e358b4a8..95986924cb5 100644 --- a/docs/usage/social-security/RULINGS.md +++ b/docs/usage/social-security/RULINGS.md @@ -8,6 +8,16 @@ to that benchmark's first bend point. False therefore retains the 95% factor; true applies both changes. Deaths after 2025 and workers with accepted authoritative prior-disability eligibility are outside this switch. +Every survivor record requires an explicit prior-eligibility answer: +`ss_calculator_prior_disability_eligibility=1` asserts that the worker initially +became eligible through disability before death; 0 asserts no prior eligibility. +The default -1 is unspecified and raises `ValueError`; other values also fail. +The pure `SurvivorBasis.prior_disability_eligibility` field accepts the same +answers as `True`/`False`, with `None` unspecified. Prior eligibility requires +an authoritative computation basis; no prior eligibility permits a benchmark +derived from death and age-62 attainment. An authoritative year alone never +establishes prior eligibility. + Section 2(c)(2)(B) covers workers who “initially became eligible for old-age or disability insurance benefits before January 1, 2026”. Prior disability is initial eligibility, so the 18% increase applies at that earlier benchmark diff --git a/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml b/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml index cbd0e0cc19a..0f165c7510d 100644 --- a/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml +++ b/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml @@ -129,3 +129,56 @@ ss_calculated_payment: 2027-03: 800 2028-03: 1140 + +- name: Explicit prior disability eligibility controls the pre-2026 survivor bend exception + # S.770 section 2(c)(2)(B): prior eligibility retains the bend increase. + # https://www.congress.gov/bill/119th-congress/senate-bill/770/text + period: 2026 + input: &survivor_eligibility_records + gov.contrib.congress.s770.section_2.in_effect: true + gov.contrib.congress.s770.section_2.recompute_pre2026_death_before_eligibility: false + people: + no_prior: &survivor_eligibility_record + ss_calculator_source: survivor + ss_calculator_worker_id: deceased-no-prior + ss_calculator_birth_date: '1950-01-02' + ss_calculator_entitlement_month: '2020-11' + ss_calculator_insured: true + ss_calculator_no_special_monthly_test: true + ss_calculator_no_prior_withholding_adjustment: true + ss_calculator_earnings_test_no_trigger: true + ss_calculator_worker_birth_year: 1970 + ss_calculator_worker_birth_date: '1970-06-15' + ss_calculator_death_year: 2020 + ss_calculator_death_date: '2020-08-12' + ss_calculator_authoritative_year: 2020 + ss_calculator_basis_provenance: Supplied authoritative 2020 benchmark + ss_calculator_prior_disability_eligibility: 0 + ss_calculator_ordinary_non_windex: true + ss_calculator_monthly_amount: 2000 + ss_calculator_valuation_month: '2020-11' + ss_calculator_composite_ratio: '1' + ss_calculator_ratio_description: Full-rate survivor with no reductions + ss_calculator_nonbinding_rib_lim: true + ss_calculator_nonbinding_family_maximum: true + ss_calculator_no_dual_entitlement: true + ss_calculator_no_earnings_test_at_valuation: true + prior: + <<: *survivor_eligibility_record + ss_calculator_worker_id: deceased-prior + ss_calculator_prior_disability_eligibility: 1 + households: + household: + members: [no_prior, prior] + output: + ss_calculated_benefit: + 2026-01: [2596, 2734] + +- name: Requested pre-2026 survivor recomputation gives both eligibility paths the bend increase + period: 2026 + input: + <<: *survivor_eligibility_records + gov.contrib.congress.s770.section_2.recompute_pre2026_death_before_eligibility: true + output: + ss_calculated_benefit: + 2026-01: [2734, 2734] diff --git a/policyengine_us/tests/unit/test_ss_calculator_engine.py b/policyengine_us/tests/unit/test_ss_calculator_engine.py index 59c236c7392..5a82b8afb4e 100644 --- a/policyengine_us/tests/unit/test_ss_calculator_engine.py +++ b/policyengine_us/tests/unit/test_ss_calculator_engine.py @@ -452,8 +452,8 @@ def test_absolute_alternative_cola_replaces_1999_original_and_corrected_rate(): assert simulation.calculate("ss_calculated_payment", "2001-08")[0] == 1066 -def _survivor(): - return _record( +def _survivor(**overrides): + record = _record( "deceased-worker", ss_calculator_source="survivor", ss_calculator_birth_date="1950-01-02", @@ -465,7 +465,7 @@ def _survivor(): ss_calculator_death_year=2025, ss_calculator_death_date="2025-08-12", ss_calculator_basis_provenance="Supplied exact worker birth and death dates", - ss_calculator_no_prior_disability=True, + ss_calculator_prior_disability_eligibility=0, ss_calculator_ordinary_non_windex=True, ss_calculator_monthly_amount=2375, ss_calculator_valuation_month="2026-01", @@ -476,6 +476,8 @@ def _survivor(): ss_calculator_no_dual_entitlement=True, ss_calculator_no_earnings_test_at_valuation=True, ) + record.update(overrides) + return record def test_survivor_engine_derives_death_benchmark_and_first_cola(): @@ -516,3 +518,45 @@ def test_survivor_engine_s770_flag_changes_bend_increase_only(increase, expected 0 ] == pytest.approx(expected) assert simulation.calculate("ss_calculated_payment", "2026-01")[0] == 2375 + + +@pytest.mark.parametrize("increase,no_prior", [(False, 2596), (True, 2734)]) +def test_survivor_prior_eligibility_requires_explicit_api_input(increase, no_prior): + people = {} + for name in ("no_prior", "prior"): + record = _survivor( + ss_calculator_worker_id=name, + ss_calculator_entitlement_month="2020-11", + ss_calculator_death_year=2020, + ss_calculator_death_date="2020-08-12", + ss_calculator_authoritative_year=2020, + ss_calculator_monthly_amount=2000, + ss_calculator_valuation_month="2020-11", + ss_calculator_basis_provenance="Supplied authoritative 2020 benchmark", + ) + record.pop("ss_calculator_prior_disability_eligibility") + people[name] = record + simulation = _simulation( + situation=_situation(people), + reform={ + "gov.contrib.congress.s770.section_2.in_effect": {"2026-01-01": True}, + "gov.contrib.congress.s770.section_2.recompute_pre2026_death_before_eligibility": { + "2026-01-01": increase + }, + }, + ) + variable = "ss_calculator_prior_disability_eligibility" + # An authoritative year cannot supply the missing eligibility assertion. + with pytest.raises(ValueError, match=variable): + simulation.calculate("ss_calculated_benefit", "2026-01") + # Reuse the same model: failures produce no cached result, and each input + # update changes only the assertion, never the shared parameter tree. + for invalid in (-2, 2): + simulation.set_input(variable, "eternity", [invalid, 1]) + with pytest.raises(ValueError, match=variable): + simulation.calculate("ss_calculated_benefit", "2026-01") + simulation.set_input(variable, "eternity", [0, 1]) + np.testing.assert_array_equal( + simulation.calculate("ss_calculated_benefit", "2026-01"), + [no_prior, 2734], + ) diff --git a/policyengine_us/tests/unit/test_ss_household_calculator.py b/policyengine_us/tests/unit/test_ss_household_calculator.py index f8a6c04b9de..bab54d08b51 100644 --- a/policyengine_us/tests/unit/test_ss_household_calculator.py +++ b/policyengine_us/tests/unit/test_ss_household_calculator.py @@ -52,7 +52,7 @@ def survivor_basis(**overrides): worker_birth_date=date(1970, 6, 15), death_date=date(2020, 8, 12), provenance="Supplied worker birth and death dates", - no_prior_disability=True, + prior_disability_eligibility=False, ordinary_non_windex=True, ) values.update(overrides) @@ -580,7 +580,7 @@ def test_survivor_authoritative_and_derived_benchmarks(): assert replace( basis, authoritative_year=2018, - no_prior_disability=False, + prior_disability_eligibility=True, provenance="Authoritative computation year", ).benchmark() == (2018, True) after62 = survivor_basis( @@ -621,7 +621,7 @@ def test_survivor_year_only_fallback_requires_stated_assumption_and_same_year_as @pytest.mark.parametrize( "changes,match", [ - ({"no_prior_disability": False}, "authoritative"), + ({"prior_disability_eligibility": True}, "authoritative"), ({"ordinary_non_windex": False}, "WINDEX"), ({"provenance": ""}, "provenance"), ({"death_year": 1969, "death_date": None}, "precede birth"), @@ -956,7 +956,7 @@ def test_authoritative_survivor_year_does_not_require_fallback_birth_assumption( death_date=None, authoritative_year=2018, provenance="Authoritative computation year", - no_prior_disability=False, + prior_disability_eligibility=True, year_only_not_january_1=False, ) assert basis.benchmark() == (2018, True) @@ -1079,7 +1079,7 @@ def test_s770_prior_disability_survivor_retains_bend_increase(flag): record = survivor( survivor=survivor_basis( authoritative_year=2018, - no_prior_disability=False, + prior_disability_eligibility=True, provenance="Continuous DIB eligibility from 2018 until August 2020 death", ), entitlement_month="2020-08", @@ -1102,3 +1102,124 @@ def test_s770_prior_disability_survivor_retains_bend_increase(flag): ) assert record.benchmark() == 2018 assert row_for(result, "2026-01").payable_benefit == 2841 + + +@pytest.mark.parametrize("flag", [False, True]) +@pytest.mark.parametrize("prior_eligibility", [None, False, True]) +def test_s770_authoritative_survivor_requires_explicit_prior_eligibility( + flag, prior_eligibility +): + # A $2,000 November 2020 check recovers PIA [2000, 2001), selecting + # AIME 4510 from the 2020 bends 960/5785. With 95% and no bend increase, + # PIA 2048.0 becomes 2596.8 after the six 2020-2025 COLAs. Increasing + # the first bend to 1132.8 instead gives 2156.8 -> 2734.5. + record = survivor( + survivor=survivor_basis( + authoritative_year=2020, + prior_disability_eligibility=prior_eligibility, + provenance="Authoritative 2020 computation basis", + ), + entitlement_month="2020-08", + monthly_amount=D(2000), + valuation_month="2020-11", + ) + rates = (".013", ".059", ".087", ".032", ".025", ".028") + events = [ + ColaEvent(f"{year}-12", f"{year + 1}-01", D(rate)) + for year, rate in zip(range(2020, 2026), rates) + ] + kwargs = dict( + cola_events=events, + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + s770_survivor_bend_increase=flag, + ) + if prior_eligibility is None: + with pytest.raises(ValueError, match="prior_disability_eligibility"): + compute(record, **kwargs) + return + result = compute(record, **kwargs) + assert result.eligibility_pia_interval == (D(2000), D(2001)) + assert result.inferred_aime_interval[0] == D(4510) + row = row_for(result, "2026-01") + increased = prior_eligibility or flag + assert row.eligibility_pia == D("2156.8" if increased else "2048.0") + assert row.cola_pia == D("2734.5" if increased else "2596.8") + assert row.payable_benefit == (2734 if increased else 2596) + + +@st.composite +def authoritative_survivor_bases(draw): + death_year = draw(st.integers(min_value=2000, max_value=2028)) + birth_year = death_year - draw(st.integers(min_value=45, max_value=75)) + death_day = draw(st.sampled_from([13, 14, 15])) + return SurvivorBasis( + worker_birth_year=birth_year, + worker_birth_date=date(birth_year, 6, 15), + death_year=death_year, + death_date=date(death_year, 6, death_day), + authoritative_year=draw( + st.integers(min_value=1983, max_value=min(death_year, birth_year + 62)) + ), + provenance="Generated authoritative initial computation year", + ordinary_non_windex=True, + ) + + +@settings(max_examples=80, deadline=None) +@given( + basis=authoritative_survivor_bases(), + monthly=st.integers(min_value=0, max_value=10000), + flag=st.booleans(), +) +def test_property_survivor_prior_eligibility_only_changes_restricted_first_bend( + basis, monthly, flag +): + record = survivor( + birth_date=date(1900, 1, 2), + survivor=basis, + entitlement_month=f"{basis.death_year}-06", + valuation_month=f"{basis.death_year}-11", + monthly_amount=D(monthly), + ) + scoring_year = max(2026, basis.death_year + 1) + kwargs = dict( + formula_path=FormulaPath(s770=True), + recompute_mode="retroactive", + s770_survivor_bend_increase=flag, + ) + # Even authoritative records cannot use the omitted answer as evidence. + with pytest.raises(ValueError, match="prior_disability_eligibility"): + compute(record, scoring_year, **kwargs) + explicit = [ + compute( + replace( + record, survivor=replace(basis, prior_disability_eligibility=prior) + ), + scoring_year, + **kwargs, + ) + for prior in (False, True) + ] + no_prior, prior = [row_for(result, f"{scoring_year}-01") for result in explicit] + restricted = ( + basis.death_date < date(basis.worker_birth_year + 62, 6, 14) + and basis.death_year < 2026 + and not flag + ) + if not restricted: + assert explicit[0] == explicit[1] + assert prior.payable_benefit >= no_prior.payable_benefit + # Independent three-segment arithmetic checks the 95% first factor for + # both answers; only the first bend changes in the restricted case. + aime = Fraction(explicit[0].inferred_aime_interval[0]) if monthly else Fraction(0) + for row, first_bend in ( + (no_prior, Fraction(960) if restricted else Fraction("1132.8")), + (prior, Fraction("1132.8")), + ): + raw = ( + min(aime, first_bend) * Fraction(95, 100) + + max(0, min(aime, 5785) - first_bend) * Fraction(32, 100) + + max(0, aime - 5785) * Fraction(15, 100) + ) + assert row.eligibility_pia == D(int(raw * 10)) / 10 diff --git a/policyengine_us/tools/social_security/engine.py b/policyengine_us/tools/social_security/engine.py index 7d1c35734cd..8c779c480b9 100644 --- a/policyengine_us/tools/social_security/engine.py +++ b/policyengine_us/tools/social_security/engine.py @@ -52,6 +52,12 @@ def money(name, when=period): kwargs = {} if source == "survivor": + prior_eligibility = value("prior_disability_eligibility") + if prior_eligibility not in (0, 1): + raise ValueError( + "ss_calculator_prior_disability_eligibility must explicitly " + "be 0 (no prior eligibility) or 1 (prior disability eligibility)" + ) same_year = int(value("same_year_death_before_62")) if same_year not in (-1, 0, 1): raise ValueError("Same-year death assertion must be -1, 0 or 1") @@ -62,7 +68,7 @@ def money(name, when=period): worker_birth_date=optional_date("worker_birth_date"), death_date=optional_date("death_date"), authoritative_year=int(value("authoritative_year")) or None, - no_prior_disability=bool(value("no_prior_disability")), + prior_disability_eligibility=bool(prior_eligibility), ordinary_non_windex=bool(value("ordinary_non_windex")), year_only_not_january_1=bool(value("year_only_not_january_1")), same_year_death_before_62=None if same_year == -1 else bool(same_year), diff --git a/policyengine_us/tools/social_security/household.py b/policyengine_us/tools/social_security/household.py index a2ccaf19ecf..d4865fb6a54 100644 --- a/policyengine_us/tools/social_security/household.py +++ b/policyengine_us/tools/social_security/household.py @@ -126,19 +126,24 @@ class SurvivorBasis: worker_birth_date: date | None = None death_date: date | None = None authoritative_year: int | None = None - no_prior_disability: bool = False + prior_disability_eligibility: bool | None = None ordinary_non_windex: bool = False year_only_not_january_1: bool = False same_year_death_before_62: bool | None = None def benchmark(self): + if not isinstance(self.prior_disability_eligibility, bool): + raise ValueError( + "prior_disability_eligibility must explicitly state whether the " + "worker was initially eligible through disability before death" + ) if not self.provenance.strip(): raise ValueError("Survivor computation-basis provenance is required") if not self.ordinary_non_windex: raise ValueError( "Only ordinary non-WINDEX survivor computations are supported" ) - if not self.no_prior_disability and self.authoritative_year is None: + if self.prior_disability_eligibility and self.authoritative_year is None: raise ValueError( "Prior disability requires an authoritative computation basis" ) @@ -485,7 +490,7 @@ def calculate_year( restricted_survivor = ( before62 and record.survivor.death_year < 2026 - and record.survivor.no_prior_disability + and not record.survivor.prior_disability_eligibility ) death_month = ( record.survivor.death_date.strftime("%Y-%m") diff --git a/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py b/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py index 1e3fb334a7f..85c11d308f5 100644 --- a/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py +++ b/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py @@ -210,13 +210,18 @@ class ss_calculator_basis_provenance(Variable): ) -class ss_calculator_no_prior_disability(Variable): - value_type = bool +class ss_calculator_prior_disability_eligibility(Variable): + value_type = int entity = Person definition_period = ETERNITY - default_value = False - label = "Social Security calculator no prior disability" - documentation = "Assert the deceased had no prior disability benefit computation." + default_value = -1 + label = "Social Security calculator prior disability eligibility" + documentation = ( + "Required survivor assertion: 1 means the worker was initially eligible " + "through disability before death, 0 means no prior eligibility, and -1 " + "means unspecified. Prior eligibility also requires an authoritative " + "computation year." + ) class ss_calculator_ordinary_non_windex(Variable): From d3f57f00dae34e479a1f2d011491badef6a55a1a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 26 Oct 2026 17:13:00 -0700 Subject: [PATCH 14/16] Run calculator API files in isolated Rest groups --- .github/workflows/baseline-tests.yaml | 3 - .github/workflows/contrib-tests.yaml | 3 - .github/workflows/pr.yaml | 3 +- .github/workflows/push.yaml | 153 +-- .github/workflows/python-tests.yaml | 142 +-- Makefile | 61 +- .../code_health/test_make_test_matches_ci.py | 10 +- .../code_health/test_pr_runner_budget.py | 92 +- .../code_health/test_rest_python_groups.py | 1042 +++++++++++------ policyengine_us/tests/rest_python_shards.py | 505 ++++++++ 10 files changed, 1463 insertions(+), 551 deletions(-) create mode 100644 policyengine_us/tests/rest_python_shards.py diff --git a/.github/workflows/baseline-tests.yaml b/.github/workflows/baseline-tests.yaml index 81c66cdf9dc..34ae24b6a14 100644 --- a/.github/workflows/baseline-tests.yaml +++ b/.github/workflows/baseline-tests.yaml @@ -16,9 +16,6 @@ jobs: POLICYENGINE_BATCH_WORKERS: 2 strategy: fail-fast: false - # At most 6 Baseline groups run at once; GitHub starts the next group on a - # fresh runner as each finishes, so the lanes balance from real durations. - max-parallel: 6 matrix: include: # One state per batch subprocess, over four runners. The job's diff --git a/.github/workflows/contrib-tests.yaml b/.github/workflows/contrib-tests.yaml index ed0dc5ebe78..5554d547ffc 100644 --- a/.github/workflows/contrib-tests.yaml +++ b/.github/workflows/contrib-tests.yaml @@ -16,9 +16,6 @@ jobs: POLICYENGINE_BATCH_WORKERS: 2 strategy: fail-fast: false - # Contrib starts after Baseline finishes, so its 6 lanes take the place of - # Baseline's 6. - max-parallel: 6 matrix: include: - group: states-shard-1 diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 7b05ce1c6d4..617d18bc6b5 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -285,8 +285,7 @@ jobs: run: bash ./update_itemization.sh - name: Run Household API Partners YAML tests run: uv run --no-sync make test-yaml-no-structural-other-partners - # Contrib starts once Baseline passes, on the same 6 lanes, so most PRs see - # their Baseline result first. A Baseline failure skips Contrib, and + # Contrib starts once Baseline passes. A Baseline failure skips Contrib, and # re-running the failed Baseline group then runs Contrib for the first time: # no finished Contrib work is repeated. Contrib: diff --git a/.github/workflows/push.yaml b/.github/workflows/push.yaml index 059bb83c364..abcff5545f5 100644 --- a/.github/workflows/push.yaml +++ b/.github/workflows/push.yaml @@ -182,9 +182,6 @@ jobs: POLICYENGINE_BATCH_WORKERS: 2 strategy: fail-fast: false - # At most 6 Baseline groups run at once; GitHub starts the next group on a - # fresh runner as each finishes, so the lanes balance from real durations. - max-parallel: 6 matrix: include: # One state per batch subprocess, over four runners. The job's @@ -287,9 +284,6 @@ jobs: POLICYENGINE_BATCH_WORKERS: 2 strategy: fail-fast: false - # Contrib starts after Baseline finishes, so its 6 lanes take the place of - # Baseline's 6. - max-parallel: 6 matrix: include: - group: states-shard-1 @@ -336,23 +330,19 @@ jobs: - name: Run Contrib Python tests if: ${{ matrix.group == 'other-shard-1' }} run: uv run --no-sync make test-policy-contrib-python - RestPython: + RestPlan: needs: ReleaseLock - name: Full Suite - Rest (Python, shard-1 + variables) + name: Plan Rest Python shards runs-on: ubuntu-latest - # Historical group times, including variables: 33-46 minutes plus setup. - timeout-minutes: 90 + timeout-minutes: 10 if: | (github.repository == 'PolicyEngine/policyengine-us') && (github.event.head_commit.message == 'Update PolicyEngine US') - env: - PYTHONUNBUFFERED: 1 - OMP_NUM_THREADS: 4 - OPENBLAS_NUM_THREADS: 4 - MKL_NUM_THREADS: 4 - VECLIB_MAXIMUM_THREADS: 4 - NUMEXPR_NUM_THREADS: 4 - OMP_WAIT_POLICY: PASSIVE + permissions: + actions: read + contents: read + outputs: + matrix: ${{ steps.plan.outputs.matrix }} steps: - name: Checkout repo uses: actions/checkout@v6 @@ -367,56 +357,51 @@ jobs: uses: astral-sh/setup-uv@v8.1.0 with: version: "0.13.4" - - name: Resolve latest compatible PolicyEngine Core - run: uv lock --upgrade-package policyengine-core - name: Install dependencies run: uv sync --locked --extra dev - - name: Turn off default branching + # A successful release run on main has every shard's JUnit and GNU time + # reports; a failed one can lack a lost runner's, which would skew the + # estimates. Without any, the plan counts each file the same. + - name: Download recent Rest Python timings + id: timings shell: bash - run: bash ./update_itemization.sh - # Each group remains a separate, sequential process on its runner. - # SPM simulation/API contracts stay in the Microsimulation job. - - name: Run remaining Python tests - if: ${{ !cancelled() && steps.system-ca.outcome == 'success' }} env: - PYTEST_ADDOPTS: "--durations=0 -v -p no:unraisableexception -p no:threadexception" - run: uv run --no-sync make test-other-python-rest REST_PYTHON_SHARD=1 REST_REPORT_DIR=. - - name: Upload Rest Python timing and memory reports - if: always() - uses: actions/upload-artifact@v4 - with: - name: rest-python-test-timings-shard-1 - path: | - rest-python-*.xml - rest-python-*-resources.txt - - name: Run tests/variables YAML tests - if: ${{ !cancelled() && steps.system-ca.outcome == 'success' }} + GH_TOKEN: ${{ github.token }} + run: | + set -uo pipefail + runs=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow push.yaml \ + --branch main --status success --limit 40 \ + --json databaseId,displayTitle \ + --jq '.[] | select(.displayTitle == "Update PolicyEngine US") | .databaseId') || runs="" + for run in $(echo "$runs" | head -n 3); do + if gh run download "$run" --repo "$GITHUB_REPOSITORY" \ + --dir "rest-timings/$run" \ + --pattern 'rest-python-test-timings-*' \ + --pattern rest-variables-test-timings; then + echo "source=release run $run" >> "$GITHUB_OUTPUT" + exit 0 + fi + rm -rf "rest-timings/$run" + done + echo "::warning::No Rest Python timing reports found; the plan counts every file the same." + - name: Plan shards + id: plan env: - PYTEST_ADDOPTS: "--durations=0 --junitxml=rest-variables.xml -p no:unraisableexception -p no:threadexception" - run: /usr/bin/time -v -o rest-variables-resources.txt uv run --no-sync make test-yaml-variables - - name: Upload Rest variables timing and memory reports - if: always() - uses: actions/upload-artifact@v4 - with: - name: rest-variables-test-timings - path: | - rest-variables.xml - rest-variables-resources.txt - Rest: - needs: [RestPython] - name: Full Suite - Rest (Python + variables) + TIMINGS_SOURCE: ${{ steps.timings.outputs.source }} + run: uv run --no-sync python policyengine_us/tests/rest_python_shards.py plan --timings rest-timings --source "$TIMINGS_SOURCE" --github-output "$GITHUB_OUTPUT" --summary "$GITHUB_STEP_SUMMARY" + RestPython: + needs: [RestPlan] + name: Full Suite - Rest (Python shard ${{ matrix.shard }}) runs-on: ubuntu-latest - # Historical group times: 32-46 minutes plus setup. - # This runner also retains the legacy summary check, keeping PRs at 27 runners. + # Plans aim at 25 minutes a shard (26-30 from the October 2026 reports); + # one made without reports can run longer. timeout-minutes: 90 - # Runs after a shard-1 failure, but not when shard 1 was skipped (a failed - # release lock) or the run is cancelled. always() kept this runner alive - # after cancellation. if: | - !cancelled() - && (needs.RestPython.result != 'skipped') - && (github.repository == 'PolicyEngine/policyengine-us') + (github.repository == 'PolicyEngine/policyengine-us') && (github.event.head_commit.message == 'Update PolicyEngine US') + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.RestPlan.outputs.matrix) }} env: PYTHONUNBUFFERED: 1 OMP_NUM_THREADS: 4 @@ -446,31 +431,57 @@ jobs: - name: Turn off default branching shell: bash run: bash ./update_itemization.sh - # Each group remains a separate, sequential process on its runner. + # Each planned process runs files of one group, one process at a time. # SPM simulation/API contracts stay in the Microsimulation job. - name: Run remaining Python tests - id: python_tests if: ${{ !cancelled() && steps.system-ca.outcome == 'success' }} env: PYTEST_ADDOPTS: "--durations=0 -v -p no:unraisableexception -p no:threadexception" - run: uv run --no-sync make test-other-python-rest REST_PYTHON_SHARD=2 REST_REPORT_DIR=. + REST_PYTHON_PROCESSES: ${{ matrix.processes }} + run: uv run --no-sync python policyengine_us/tests/rest_python_shards.py run --report-dir . - name: Upload Rest Python timing and memory reports if: always() uses: actions/upload-artifact@v4 with: - name: rest-python-test-timings-shard-2 + name: rest-python-test-timings-shard-${{ matrix.shard }} path: | rest-python-*.xml rest-python-*-resources.txt + - name: Run tests/variables YAML tests + if: ${{ !cancelled() && steps.system-ca.outcome == 'success' && matrix.variables }} + env: + PYTEST_ADDOPTS: "--durations=0 --junitxml=rest-variables.xml -p no:unraisableexception -p no:threadexception" + run: /usr/bin/time -v -o rest-variables-resources.txt uv run --no-sync make test-yaml-variables + - name: Upload Rest variables timing and memory reports + if: ${{ always() && matrix.variables }} + uses: actions/upload-artifact@v4 + with: + name: rest-variables-test-timings + path: | + rest-variables.xml + rest-variables-resources.txt + Rest: + needs: [RestPlan, RestPython] + # Runs after a failed plan or shard, but not when the plan was skipped (a + # failed release lock) or the run is cancelled. always() kept this runner + # alive after cancellation. + if: | + !cancelled() + && (needs.RestPlan.result != 'skipped') + && (github.repository == 'PolicyEngine/policyengine-us') + && (github.event.head_commit.message == 'Update PolicyEngine US') + name: Check Rest Python shards + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: - name: Check all Rest jobs succeeded - if: always() shell: bash env: + PLAN_RESULT: ${{ needs.RestPlan.result }} PYTHON_RESULT: ${{ needs.RestPython.result }} - SHARD_RESULT: ${{ steps.python_tests.outcome }} run: | - if [[ "$PYTHON_RESULT" != "success" || "$SHARD_RESULT" != "success" ]]; then - echo "::error::Rest shards did not all succeed: shard-1=$PYTHON_RESULT, shard-2=$SHARD_RESULT" + if [[ "$PLAN_RESULT" != "success" || "$PYTHON_RESULT" != "success" ]]; then + echo "::error::Rest jobs did not all succeed: plan=$PLAN_RESULT, shards=$PYTHON_RESULT" exit 1 fi Microsimulation: @@ -484,12 +495,6 @@ jobs: env: PYTHONUNBUFFERED: 1 PYTEST_ADDOPTS: "--durations=25 -p no:unraisableexception -p no:threadexception" - OMP_NUM_THREADS: 4 - OPENBLAS_NUM_THREADS: 4 - MKL_NUM_THREADS: 4 - VECLIB_MAXIMUM_THREADS: 4 - NUMEXPR_NUM_THREADS: 4 - OMP_WAIT_POLICY: PASSIVE steps: - name: Checkout repo uses: actions/checkout@v6 @@ -539,7 +544,7 @@ jobs: if: | (github.repository == 'PolicyEngine/policyengine-us') && (github.event.head_commit.message == 'Update PolicyEngine US') - needs: [ReleaseLock, ReleaseLockTests, Baseline, HouseholdAPIPartners, Contrib, RestPython, Rest, Microsimulation] + needs: [ReleaseLock, ReleaseLockTests, Baseline, HouseholdAPIPartners, Contrib, RestPlan, RestPython, Rest, Microsimulation] # PyPI trusted publishing: PyPI accepts uploads only from this workflow in # the pypi environment, which is limited to main. No stored PyPI token. environment: pypi diff --git a/.github/workflows/python-tests.yaml b/.github/workflows/python-tests.yaml index 51fc0ad7569..ad6a88a0b01 100644 --- a/.github/workflows/python-tests.yaml +++ b/.github/workflows/python-tests.yaml @@ -1,23 +1,21 @@ name: Python tests on: workflow_call: -# Two sequential Rest runners keep each shard below its timeout. -# Shard 1 includes variables; shard 2 also supplies the legacy summary check. +# RestPlan spreads the Rest Python groups over parallel shards by the latest +# release run's times (policyengine_us/tests/rest_python_shards.py); each +# process still runs files of one Makefile group. Rest runs no tests: it +# fails unless the plan and every shard succeeded. # Only the guarded PR workflow calls this file; it has no automatic triggers. jobs: - RestPython: - name: Full Suite - Rest (Python, shard-1 + variables) + RestPlan: + name: Plan Rest Python shards runs-on: ubuntu-latest - # Historical group times, including variables: 33-46 minutes plus setup. - timeout-minutes: 90 - env: - PYTHONUNBUFFERED: 1 - OMP_NUM_THREADS: 4 - OPENBLAS_NUM_THREADS: 4 - MKL_NUM_THREADS: 4 - VECLIB_MAXIMUM_THREADS: 4 - NUMEXPR_NUM_THREADS: 4 - OMP_WAIT_POLICY: PASSIVE + timeout-minutes: 10 + permissions: + actions: read + contents: read + outputs: + matrix: ${{ steps.plan.outputs.matrix }} steps: - name: Checkout repo uses: actions/checkout@v6 @@ -32,51 +30,48 @@ jobs: uses: astral-sh/setup-uv@v8.1.0 with: version: "0.13.4" - - name: Resolve latest compatible PolicyEngine Core - run: uv lock --upgrade-package policyengine-core - name: Install dependencies run: uv sync --locked --extra dev - - name: Turn off default branching + # A successful release run on main has every shard's JUnit and GNU time + # reports; a failed one can lack a lost runner's, which would skew the + # estimates. Without any, the plan counts each file the same. + - name: Download recent Rest Python timings + id: timings shell: bash - run: bash ./update_itemization.sh - # Each group remains a separate, sequential process on its runner. - # SPM simulation/API contracts stay in the Microsimulation job. - - name: Run remaining Python tests - if: ${{ !cancelled() && steps.system-ca.outcome == 'success' }} env: - PYTEST_ADDOPTS: "--durations=0 -v -p no:unraisableexception -p no:threadexception" - run: uv run --no-sync make test-other-python-rest REST_PYTHON_SHARD=1 REST_REPORT_DIR=. - - name: Upload Rest Python timing and memory reports - if: always() - uses: actions/upload-artifact@v4 - with: - name: rest-python-test-timings-shard-1 - path: | - rest-python-*.xml - rest-python-*-resources.txt - - name: Run tests/variables YAML tests - if: ${{ !cancelled() && steps.system-ca.outcome == 'success' }} + GH_TOKEN: ${{ github.token }} + run: | + set -uo pipefail + runs=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow push.yaml \ + --branch main --status success --limit 40 \ + --json databaseId,displayTitle \ + --jq '.[] | select(.displayTitle == "Update PolicyEngine US") | .databaseId') || runs="" + for run in $(echo "$runs" | head -n 3); do + if gh run download "$run" --repo "$GITHUB_REPOSITORY" \ + --dir "rest-timings/$run" \ + --pattern 'rest-python-test-timings-*' \ + --pattern rest-variables-test-timings; then + echo "source=release run $run" >> "$GITHUB_OUTPUT" + exit 0 + fi + rm -rf "rest-timings/$run" + done + echo "::warning::No Rest Python timing reports found; the plan counts every file the same." + - name: Plan shards + id: plan env: - PYTEST_ADDOPTS: "--durations=0 --junitxml=rest-variables.xml -p no:unraisableexception -p no:threadexception" - run: /usr/bin/time -v -o rest-variables-resources.txt uv run --no-sync make test-yaml-variables - - name: Upload Rest variables timing and memory reports - if: always() - uses: actions/upload-artifact@v4 - with: - name: rest-variables-test-timings - path: | - rest-variables.xml - rest-variables-resources.txt - Rest: - needs: [RestPython] - # Runs after a shard-1 failure but stops when the run is cancelled. - # always() kept this runner alive after cancellation. - if: ${{ !cancelled() }} - name: Full Suite - Rest (Python + variables) + TIMINGS_SOURCE: ${{ steps.timings.outputs.source }} + run: uv run --no-sync python policyengine_us/tests/rest_python_shards.py plan --timings rest-timings --source "$TIMINGS_SOURCE" --github-output "$GITHUB_OUTPUT" --summary "$GITHUB_STEP_SUMMARY" + RestPython: + needs: [RestPlan] + name: Full Suite - Rest (Python shard ${{ matrix.shard }}) runs-on: ubuntu-latest - # Historical group times: 32-46 minutes plus setup. - # This runner also retains the legacy summary check, keeping PRs at 27 runners. + # Plans aim at 25 minutes a shard (26-30 from the October 2026 reports); + # one made without reports can run longer. timeout-minutes: 90 + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.RestPlan.outputs.matrix) }} env: PYTHONUNBUFFERED: 1 OMP_NUM_THREADS: 4 @@ -106,31 +101,52 @@ jobs: - name: Turn off default branching shell: bash run: bash ./update_itemization.sh - # Each group remains a separate, sequential process on its runner. + # Each planned process runs files of one group, one process at a time. # SPM simulation/API contracts stay in the Microsimulation job. - name: Run remaining Python tests - id: python_tests if: ${{ !cancelled() && steps.system-ca.outcome == 'success' }} env: PYTEST_ADDOPTS: "--durations=0 -v -p no:unraisableexception -p no:threadexception" - run: uv run --no-sync make test-other-python-rest REST_PYTHON_SHARD=2 REST_REPORT_DIR=. + REST_PYTHON_PROCESSES: ${{ matrix.processes }} + run: uv run --no-sync python policyengine_us/tests/rest_python_shards.py run --report-dir . - name: Upload Rest Python timing and memory reports if: always() uses: actions/upload-artifact@v4 with: - name: rest-python-test-timings-shard-2 + name: rest-python-test-timings-shard-${{ matrix.shard }} path: | rest-python-*.xml rest-python-*-resources.txt + - name: Run tests/variables YAML tests + if: ${{ !cancelled() && steps.system-ca.outcome == 'success' && matrix.variables }} + env: + PYTEST_ADDOPTS: "--durations=0 --junitxml=rest-variables.xml -p no:unraisableexception -p no:threadexception" + run: /usr/bin/time -v -o rest-variables-resources.txt uv run --no-sync make test-yaml-variables + - name: Upload Rest variables timing and memory reports + if: ${{ always() && matrix.variables }} + uses: actions/upload-artifact@v4 + with: + name: rest-variables-test-timings + path: | + rest-variables.xml + rest-variables-resources.txt + Rest: + needs: [RestPlan, RestPython] + # Runs after a failed plan or shard but stops when the run is cancelled. + # always() kept this runner alive after cancellation. + if: ${{ !cancelled() }} + name: Check Rest Python shards + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: - name: Check all Rest jobs succeeded - if: always() shell: bash env: + PLAN_RESULT: ${{ needs.RestPlan.result }} PYTHON_RESULT: ${{ needs.RestPython.result }} - SHARD_RESULT: ${{ steps.python_tests.outcome }} run: | - if [[ "$PYTHON_RESULT" != "success" || "$SHARD_RESULT" != "success" ]]; then - echo "::error::Rest shards did not all succeed: shard-1=$PYTHON_RESULT, shard-2=$SHARD_RESULT" + if [[ "$PLAN_RESULT" != "success" || "$PYTHON_RESULT" != "success" ]]; then + echo "::error::Rest jobs did not all succeed: plan=$PLAN_RESULT, shards=$PYTHON_RESULT" exit 1 fi Microsimulation: @@ -140,12 +156,6 @@ jobs: env: PYTHONUNBUFFERED: 1 PYTEST_ADDOPTS: "--durations=25 -p no:unraisableexception -p no:threadexception" - OMP_NUM_THREADS: 4 - OPENBLAS_NUM_THREADS: 4 - MKL_NUM_THREADS: 4 - VECLIB_MAXIMUM_THREADS: 4 - NUMEXPR_NUM_THREADS: 4 - OMP_WAIT_POLICY: PASSIVE steps: - name: Checkout repo uses: actions/checkout@v6 diff --git a/Makefile b/Makefile index 8e23dd21a4c..b9dec81386e 100644 --- a/Makefile +++ b/Makefile @@ -23,10 +23,6 @@ TESTS := policyengine_us/tests REST_SPM_TESTS := $(TESTS)/core/test_spm_policy_family.py \ $(TESTS)/core/test_spm_simulation_isolation.py \ $(TESTS)/core/test_spm_system.py -# Calculator Simulation/API contracts use that same runner, with each file -# in its own process so its reform trees are released before the next suite. -REST_SIMULATION_API_TESTS := $(TESTS)/unit/test_ss_calculator_engine.py \ - $(TESTS)/unit/test_ss_calculator_differential.py # The remaining Python tests run as one pytest process per group, one after # another, so each exit releases its heap before the next group starts. As a # single process they peaked at 15.7 GB RSS on the 16 GB runner, with 1.5M @@ -49,26 +45,12 @@ REST_SIMULATION_API_TESTS := $(TESTS)/unit/test_ss_calculator_engine.py \ # SSI resource deeming retains a reformed system at import and builds another # in its grid fixture. Core reached 13.3 GB in CI run 38141803955 after this # and three smaller modules arrived; isolate SSI rather than filling heavy-a -# (8.1 GB including the pending capital-gains MTR change). These groups remain -# sequential subprocesses within each Rest Python shard. -REST_PYTHON_GROUPS := cached-arrays heavy-a heavy-b core-heavy core policy-parameters policy remaining-heavy remaining -# CI runs two shards of these existing isolated processes. Across seven -# recent runs (including 38326922385 and 38289790999), their summed group -# times were 32-45 and 32-46 minutes; variables adds about a minute to shard 1. -# Both stay near 45 minutes, while the old serial job hit its 90-minute limit. -# No shard runs more than one Python group at a time. Locally, leaving -# REST_PYTHON_SHARD unset still runs every group in the original order. -REST_PYTHON_SHARD_1_GROUPS := cached-arrays core-heavy policy-parameters remaining-heavy remaining -REST_PYTHON_SHARD_2_GROUPS := heavy-a heavy-b core policy -REST_PYTHON_SHARD ?= -ifeq ($(REST_PYTHON_SHARD),) -REST_PYTHON_SELECTED_GROUPS := $(REST_PYTHON_GROUPS) -else -REST_PYTHON_SELECTED_GROUPS := $(REST_PYTHON_SHARD_$(REST_PYTHON_SHARD)_GROUPS) -ifeq ($(strip $(REST_PYTHON_SELECTED_GROUPS)),) -$(error REST_PYTHON_SHARD must be 1 or 2) -endif -endif +# (8.1 GB including the pending capital-gains MTR change). +# CI does not run this target. tests/rest_python_shards.py reads these groups +# from its dry run and spreads their files over parallel runners by recent +# CI times, splitting a long group into chunks. A process still runs files +# of one group only, in this order, so none holds more than its group here. +REST_PYTHON_GROUPS := cached-arrays heavy-a heavy-b core-heavy ss-calculator-engine ss-calculator-differential core policy-parameters policy remaining-heavy remaining REST_CACHED_ARRAY_TESTS := $(TESTS)/test_formulas_do_not_write_into_cached_arrays.py REST_HEAVY_A_TESTS := $(TESTS)/test_md_poverty_line_credit_invariants.py \ $(TESTS)/core/test_ald_determinism.py \ @@ -84,6 +66,15 @@ REST_HEAVY_B_TESTS := $(TESTS)/core/test_marginal_tax_rate_coverage.py \ REST_CORE_HEAVY_TESTS := $(TESTS)/core/test_ssi_resource_deeming_invariants.py \ $(TESTS)/test_federal_credit_limit_order.py \ $(TESTS)/test_pinned_branch_credit_dependents.py +# Supplied-record calculator API checks load no national dataset. Keep each +# file in a separate process so retained reform trees are released on exit. +# Local macOS/Python 3.13.9, four numeric threads: peak RSS 2.98 GiB +# through 13 cases before the 1,800-second cap; the previous complete +# 18-case run recorded 3.06 GiB. CI reports the complete 20-case process. +REST_SS_CALCULATOR_ENGINE_TESTS := $(TESTS)/unit/test_ss_calculator_engine.py +# Local macOS/Python 3.13.9, four numeric threads: all eight cases passed +# with 2.45 GiB peak RSS, below the ~10 GB per-process target above. +REST_SS_CALCULATOR_DIFFERENTIAL_TESTS := $(TESTS)/unit/test_ss_calculator_differential.py # These three parameter modules construct full reform trees; one also loads # a default Microsimulation only to read parameters. Release their heap before # the remaining policy tests, rather than stacking both in the 13.9 GB group. @@ -98,13 +89,15 @@ REST_REMAINING_HEAVY_TESTS := $(TESTS)/test_niit_section_911_magi.py \ $(TESTS)/test_capital_gain_distributions_loss_limit.py \ $(TESTS)/test_schedule_d_filer_net_capital_gain.py REST_LISTED_TESTS := $(REST_CACHED_ARRAY_TESTS) $(REST_HEAVY_A_TESTS) $(REST_HEAVY_B_TESTS) \ - $(REST_CORE_HEAVY_TESTS) $(REST_POLICY_PARAMETER_TESTS) $(REST_REMAINING_HEAVY_TESTS) -REST_IGNORES := $(addprefix --ignore=,$(TESTS)/policy/contrib $(TESTS)/microsimulation $(REST_SPM_TESTS) $(REST_SIMULATION_API_TESTS)) + $(REST_CORE_HEAVY_TESTS) $(REST_SS_CALCULATOR_ENGINE_TESTS) $(REST_SS_CALCULATOR_DIFFERENTIAL_TESTS) \ + $(REST_POLICY_PARAMETER_TESTS) $(REST_REMAINING_HEAVY_TESTS) +REST_IGNORES := $(addprefix --ignore=,$(TESTS)/policy/contrib $(TESTS)/microsimulation $(REST_SPM_TESTS)) # $(call rest_pytest,,,) is the pytest -# command for one group. CI sets REST_REPORT_DIR, and each group then writes -# its own JUnit XML and GNU time report there: rest-python-.xml and -# rest-python--resources.txt. Unset, it is plain pytest, since macOS -# /usr/bin/time has no -v. +# command for one group. With REST_REPORT_DIR set, each group writes its own +# JUnit XML and GNU time report there: rest-python-.xml and +# rest-python--resources.txt; rest_python_shards.py names the groups +# from these files. Unset, it is plain pytest, since macOS /usr/bin/time has +# no -v. rest_pytest = $(strip $(if $(REST_REPORT_DIR),/usr/bin/time -v -o $(REST_REPORT_DIR)/rest-python-$(1)-resources.txt) \ pytest $(2) --maxfail=0 $(REST_IGNORES) $(addprefix --ignore=,$(3)) \ $(if $(REST_REPORT_DIR),--junitxml=$(REST_REPORT_DIR)/rest-python-$(1).xml)) @@ -306,11 +299,9 @@ test-other-python: pytest policyengine_us/tests/ --maxfail=0 --ignore=$(TESTS)/policy/contrib --ignore=$(TESTS)/microsimulation test-other-python-spm: pytest $(REST_SPM_TESTS) --maxfail=0 - pytest $(TESTS)/unit/test_ss_calculator_engine.py --maxfail=0 $(if $(findstring --junitxml=,$(PYTEST_ADDOPTS)),--junitxml=simulation-ss-calculator-engine.xml) - pytest $(TESTS)/unit/test_ss_calculator_differential.py --maxfail=0 $(if $(findstring --junitxml=,$(PYTEST_ADDOPTS)),--junitxml=simulation-ss-calculator-differential.xml) # Every group runs even after one fails; the target fails if any group did. test-other-python-rest: - @failed=""; for group in $(REST_PYTHON_SELECTED_GROUPS); do \ + @failed=""; for group in $(REST_PYTHON_GROUPS); do \ echo "=== Rest Python group: $$group ==="; \ $(MAKE) --no-print-directory test-other-python-rest-$$group || failed="$$failed $$group"; \ done; \ @@ -323,6 +314,10 @@ test-other-python-rest-heavy-b: $(call rest_pytest,heavy-b,$(REST_HEAVY_B_TESTS)) test-other-python-rest-core-heavy: $(call rest_pytest,core-heavy,$(REST_CORE_HEAVY_TESTS)) +test-other-python-rest-ss-calculator-engine: + $(call rest_pytest,ss-calculator-engine,$(REST_SS_CALCULATOR_ENGINE_TESTS)) +test-other-python-rest-ss-calculator-differential: + $(call rest_pytest,ss-calculator-differential,$(REST_SS_CALCULATOR_DIFFERENTIAL_TESTS)) test-other-python-rest-core: $(call rest_pytest,core,$(TESTS)/core,$(REST_LISTED_TESTS)) test-other-python-rest-policy-parameters: diff --git a/policyengine_us/tests/code_health/test_make_test_matches_ci.py b/policyengine_us/tests/code_health/test_make_test_matches_ci.py index 532945e5cf9..24bb5fef2ac 100644 --- a/policyengine_us/tests/code_health/test_make_test_matches_ci.py +++ b/policyengine_us/tests/code_health/test_make_test_matches_ci.py @@ -20,6 +20,9 @@ WORKFLOW = REPO_ROOT / ".github" / "workflows" / "pr.yaml" SHARD = re.compile(r"\s+--shard\s+\d+/\d+") MAKE_TARGET = re.compile(r"\bmake\s+([\w-]+)") +# CI's planned Rest Python shards run this target's groups; the planner reads +# them from its dry run (code_health/test_rest_python_groups.py). +PLANNED_TARGETS = {"rest_python_shards.py run": "test-other-python-rest"} pytestmark = pytest.mark.skipif( shutil.which("make") is None or not WORKFLOW.exists(), @@ -59,7 +62,9 @@ def ci_suites(): targets, commands = set(), set() for job in workflow_jobs(WORKFLOW): matrix = (job.get("strategy") or {}).get("matrix") or {} - for entry in matrix.get("include") or []: + # A planned matrix is an expression; its steps name the target. + entries = [] if isinstance(matrix, str) else matrix.get("include") or [] + for entry in entries: if "target" in entry: targets.add(entry["target"]) if "cmd" in entry: @@ -71,6 +76,9 @@ def ci_suites(): for target in MAKE_TARGET.findall(step.get("run") or ""): if not target.startswith("$"): targets.add(target) + for command, target in PLANNED_TARGETS.items(): + if command in (step.get("run") or ""): + targets.add(target) return {t for t in targets if t.startswith("test")}, commands diff --git a/policyengine_us/tests/code_health/test_pr_runner_budget.py b/policyengine_us/tests/code_health/test_pr_runner_budget.py index 0c07783435c..6ac523b5ece 100644 --- a/policyengine_us/tests/code_health/test_pr_runner_budget.py +++ b/policyengine_us/tests/code_health/test_pr_runner_budget.py @@ -1,11 +1,17 @@ """Consolidating short checks must preserve coverage and failure isolation.""" +import importlib.util import math from pathlib import Path import yaml ROOT = Path(__file__).resolve().parents[3] +SPEC = importlib.util.spec_from_file_location( + "rest_python_shards", ROOT / "policyengine_us/tests/rest_python_shards.py" +) +shards = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(shards) JOBS = yaml.safe_load((ROOT / ".github/workflows/pr.yaml").read_text())["jobs"] GROUP_WORKFLOWS = { name: yaml.safe_load((ROOT / job["uses"]).read_text()) @@ -18,6 +24,7 @@ KEEP_RUNNING_WITH_SYSTEM_CA = ( "${{ !cancelled() && steps.system-ca.outcome == 'success' }}" ) +PLANNED_MATRIX = "${{ fromJSON(needs.RestPlan.outputs.matrix) }}" def action(name): @@ -34,7 +41,14 @@ def calls(job, name): ] +def planned(job): + return job.get("strategy", {}).get("matrix") == PLANNED_MATRIX + + def runners(job): + """A job's runners; a planned matrix counts its largest possible plan.""" + if planned(job): + return shards.MAX_SHARDS matrix = job.get("strategy", {}).get("matrix", {}) if "include" in matrix: return len(matrix["include"]) @@ -48,22 +62,27 @@ def test_pr_runner_budget_keeps_the_heavy_suites_separate(): for name, job in workflow["jobs"].items(): assert name not in runner_jobs runner_jobs[name] = job + assert {name for name, job in runner_jobs.items() if planned(job)} == {"RestPython"} for name, job in runner_jobs.items(): - counts[name] = runners(job) + if not planned(job): + counts[name] = runners(job) # Rest hit the 90-minute timeout on #10024, #9913, #10139 and #10029 - # in October 2026. One extra runner buys about 45 minutes of headroom: - # two tested shards share variables and the legacy summary check. + # in October 2026, and by run 40014592006 its two chained runners took + # 130 minutes. RestPlan now spreads the groups over parallel shards (five + # from the October reports, at most MAX_SHARDS), and Rest checks their + # results on a runner of its own. assert sum(counts.values()) == 27 assert { name: counts[name] - for name in ("Baseline", "Contrib", "RestPython", "Rest", "Microsimulation") + for name in ("Baseline", "Contrib", "RestPlan", "Rest", "Microsimulation") } == { "Baseline": 11, "Contrib": 9, - "RestPython": 1, + "RestPlan": 1, "Rest": 1, "Microsimulation": 1, } + assert (shards.MIN_SHARDS, shards.MAX_SHARDS) == (4, 12) def needs(job): @@ -75,19 +94,15 @@ def concurrent(job): return min(job.get("strategy", {}).get("max-parallel", math.inf), runners(job)) -def test_lanes_cap_a_pr_at_11_runners_at_once(): +def test_uncapped_matrices_keep_a_pr_at_27_runners_at_once(): # Within pr.yaml, validation runs alone; everything that needs only it starts - # together, Rest waits for RestPython, and Contrib waits for Baseline. - # Baseline and Contrib each keep one job per group but run at most - # max-parallel of them at once: GitHub starts the next group as one - # finishes, so the lanes rebalance from real durations on every run, with - # nothing to re-pair as groups grow. - assert ( - GROUP_WORKFLOWS["Baseline"]["jobs"]["Baseline"]["strategy"]["max-parallel"] == 6 - ) - assert ( - GROUP_WORKFLOWS["Contrib"]["jobs"]["Contrib"]["strategy"]["max-parallel"] == 6 - ) + # together, the planned Python shards follow RestPlan, Rest waits for them, + # and Contrib waits for Baseline. The Enterprise runner capacity allows + # every group in each matrix to start together. The dependencies and the + # planner's MAX_SHARDS still bound the peak. + for name in ("Baseline", "Contrib"): + for job in (GROUP_WORKFLOWS[name]["jobs"][name], PUSH_JOBS[name]): + assert "max-parallel" not in job["strategy"] first_wave = {} for name, job in JOBS.items(): if needs(job) != ["ReleaseLock"]: @@ -98,13 +113,21 @@ def test_lanes_cap_a_pr_at_11_runners_at_once(): for inner_name, inner in GROUP_WORKFLOWS[name]["jobs"].items(): if not needs(inner): first_wave[inner_name] = concurrent(inner) - assert "Rest" not in first_wave and "Contrib" not in first_wave - assert sum(first_wave.values()) == 11 - # Contrib starts only after Baseline has finished, so at most Contrib's - # lanes plus every other first-wave job can be running then. - single = {name: n for name, n in first_wave.items() if name != "Baseline"} + assert not {"Rest", "RestPython", "Contrib"} & set(first_wave) + assert sum(first_wave.values()) == 16 + # The shards start once RestPlan has finished. Contrib starts only after + # Baseline has finished, so at most Contrib's groups, the shards and every + # other first-wave job can be running then. + python = concurrent(PYTHON_JOBS["RestPython"]) + assert python == shards.MAX_SHARDS + assert sum(first_wave.values()) - first_wave["RestPlan"] + python <= 27 + single = { + name: n + for name, n in first_wave.items() + if name not in ("Baseline", "RestPlan") + } contrib = concurrent(GROUP_WORKFLOWS["Contrib"]["jobs"]["Contrib"]) - assert contrib + sum(single.values()) <= 11 + assert contrib + python + sum(single.values()) <= 27 def test_contrib_waits_for_baseline_and_skips_when_it_fails(): @@ -125,7 +148,7 @@ def test_yaml_suites_run_two_memory_aware_workers_per_runner(): assert job["env"]["POLICYENGINE_BATCH_WORKERS"] == 2 -def test_release_ci_runs_the_same_baseline_and_contrib_lanes(): +def test_release_ci_runs_the_same_baseline_and_contrib_matrices(): for name in ("Baseline", "Contrib"): pr_job = GROUP_WORKFLOWS[name]["jobs"][name] assert PUSH_JOBS[name]["strategy"] == pr_job["strategy"] @@ -165,22 +188,29 @@ def test_suite_groups_have_no_extra_runners_or_triggers(): # PyYAML parses the bare `on` key as True. No push/PR trigger here: # the draft guard must control the only route to these runners. assert GROUP_WORKFLOWS[name][True] == {"workflow_call": None} - assert set(PYTHON_JOBS) == {"RestPython", "Rest", "Microsimulation"} + assert set(PYTHON_JOBS) == {"RestPlan", "RestPython", "Rest", "Microsimulation"} assert {name: job["timeout-minutes"] for name, job in PYTHON_JOBS.items()} == { + "RestPlan": 10, "RestPython": 90, - "Rest": 90, + "Rest": 5, "Microsimulation": 60, } + expected_needs = { + "RestPlan": [], + "RestPython": ["RestPlan"], + "Rest": ["RestPlan", "RestPython"], + "Microsimulation": [], + } for name, job in PYTHON_JOBS.items(): assert job["runs-on"] == "ubuntu-latest" - assert job.get("needs", []) == (["RestPython"] if name == "Rest" else []) - assert not job.get("strategy") + assert job.get("needs", []) == expected_needs[name] + assert bool(job.get("strategy")) == (name == "RestPython") assert not job.get("continue-on-error") - # The second tested runner also checks the first runner's result. There - # is no third runner just for the summary, or a variables-only runner. + # Only the planned shards form a matrix. The summary runner checks the + # plan's and every shard's result; there is no variables-only runner. # !cancelled(), not always(): always() kept it running after cancellation. assert PYTHON_JOBS["Rest"]["if"] == KEEP_RUNNING - assert PYTHON_JOBS["Rest"]["name"] == "Full Suite - Rest (Python + variables)" + assert PYTHON_JOBS["Rest"]["name"] == "Check Rest Python shards" def test_sequential_variants_preserve_failures_and_allow_later_results(): diff --git a/policyengine_us/tests/code_health/test_rest_python_groups.py b/policyengine_us/tests/code_health/test_rest_python_groups.py index 8324c99de34..f4318cd3342 100644 --- a/policyengine_us/tests/code_health/test_rest_python_groups.py +++ b/policyengine_us/tests/code_health/test_rest_python_groups.py @@ -4,29 +4,32 @@ and the SPM files in one pytest process. That process peaked at 15.7 GB RSS on the 16 GB runner (CI run 37198184683), and later runs lost the runner partway through the step. `make test-other-python-rest` now runs the same files as one -pytest process per group in REST_PYTHON_GROUPS. CI assigns those groups to -two Python shards on separate runners, with the variables YAML in the first -shard. The second shard retains the original Rest check and waits for the -first shard so it can fail if either shard fails. +pytest process per group in REST_PYTHON_GROUPS. In CI, rest_python_shards.py +plans those groups' files over parallel shards from a recent run's times, +splitting a long group into chunks. A process runs files of one group only, +and Rest, which runs no tests, fails unless every shard succeeded. Paths and --ignore flags can drop a file, or run it twice, while every test -still passes. So this guard expands the workflows' shard commands through -`make -n`, asks pytest which files each group collects, and checks that each -file of the old single command runs exactly once. A new test file lands in -core or policy when it sits under those folders and in remaining otherwise; -the check fails if a change to the groups or shards leaves one out. Running -the target with a stub pytest checks that every group runs and that any -failure fails the target. The original Rest check aggregates all shard -results, and must fail on failed, cancelled or skipped jobs. +still passes. So this guard expands the groups through `make -n`, asks pytest +which files each group collects, and checks that each file of the old single +command runs exactly once. A new test file lands in core or policy when it +sits under those folders and in remaining otherwise; the check fails if a +change to the groups leaves one out. Plans made with no, measured, skewed and +tiny times must then run each group's files once, in the group's order, and +the workflows must run and upload each shard of the plan. Running the target +and a shard with a stub pytest checks that every process runs and that any +failure fails them. The Rest check aggregates the plan and shards, and must +fail on failed, cancelled or skipped jobs. pytest lists the files here through its own discovery (paths, --ignore, -python_files), but nothing is imported: running this file as a script swaps -each test module for a placeholder. It also skips conftest.py files, because -importing policyengine_us/conftest.py imports the whole model. +python_files), but nothing is imported: rest_python_shards.py's list-files +mode swaps each test module for a placeholder. It also skips conftest.py +files, because importing policyengine_us/conftest.py imports the whole model. test_conftest_files_cannot_change_which_files_are_collected keeps that safe. """ import ast +import importlib.util import json import os import re @@ -34,7 +37,7 @@ import shutil import subprocess import sys -import tempfile +import zlib from collections import defaultdict from fnmatch import fnmatch from pathlib import Path @@ -44,23 +47,26 @@ REPO = Path(__file__).resolve().parents[3] TESTS = REPO / "policyengine_us" / "tests" +PLANNER = TESTS / "rest_python_shards.py" +SPEC = importlib.util.spec_from_file_location("rest_python_shards", PLANNER) +shards = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(shards) WORKFLOWS = [ REPO / ".github" / "workflows" / name for name in ("python-tests.yaml", "push.yaml") ] KEEP_RUNNING_WITH_SYSTEM_CA = ( "${{ !cancelled() && steps.system-ca.outcome == 'success' }}" ) -# CI runs this file under a shard of `make test-other-python-rest`, and that -# make exports these. Passed on, they would restrict the guard's reference to -# one shard, or carry its report directory into the stub run and overwrite -# the CI groups' GNU time reports. -PARENT_MAKE_VARIABLES = ( - "MAKEFLAGS", - "MFLAGS", - "MAKELEVEL", - "REST_REPORT_DIR", - "REST_PYTHON_SHARD", +RELEASE_ONLY = ( + "(github.repository == 'PolicyEngine/policyengine-us') " + "&& (github.event.head_commit.message == 'Update PolicyEngine US')" ) +# CI runs this file in a Rest shard, and a local `make test` exports these. +# Passed on, they would add report options to the guard's reference commands, +# or carry a report directory into the stub run and overwrite real reports. +PARENT_MAKE_VARIABLES = ("MAKEFLAGS", "MFLAGS", "MAKELEVEL", "REST_REPORT_DIR") +REPORT_DIR = "reports" +PLANNER_COMMAND = "python policyengine_us/tests/rest_python_shards.py" def dry_run(target, *overrides, prefixes=("pytest ", "/usr/bin/time ")): @@ -89,18 +95,7 @@ def collected_files(args, cwd=REPO): A command that collects nothing (pytest's exit 5) lists no files, which partition_problems reports by group. """ - env = {k: v for k, v in os.environ.items() if k != "PYTEST_ADDOPTS"} - with tempfile.TemporaryDirectory() as tmp: - listing = Path(tmp) / "files.json" - result = subprocess.run( - [sys.executable, __file__, str(listing), *args], - cwd=cwd, - env=env, - capture_output=True, - text=True, - ) - assert result.returncode in (0, 5), (args, result.stdout + result.stderr) - return json.loads(listing.read_text()) + return shards.collected_files(args, cwd) def partition_problems(reference, groups): @@ -131,17 +126,16 @@ def workflow_jobs(workflow): return yaml.safe_load(workflow.read_text())["jobs"] -def rest_steps(workflow, job="RestPython"): - return workflow_jobs(workflow)[job]["steps"] +def single(steps, predicate): + (step,) = [step for step in steps if predicate(step)] + return step def assert_system_ca_precedes(steps, runtime_step): """Continuations require a successful, unconditional CA setup first.""" - (setup,) = [ - step - for step in steps - if step.get("uses") == "./.github/actions/setup-system-ca" - ] + setup = single( + steps, lambda step: step.get("uses") == "./.github/actions/setup-system-ca" + ) assert setup["id"] == "system-ca" assert "if" not in setup assert not setup.get("continue-on-error", False) @@ -150,63 +144,6 @@ def assert_system_ca_precedes(steps, runtime_step): assert steps.index(setup) < steps.index(runtime_step) -def ci_python_shards(workflow): - """The real Make overrides and artifact configuration of every shard.""" - jobs = workflow_jobs(workflow) - calls = [ - name - for name, config in jobs.items() - for step in config.get("steps", []) - if "make test-other-python-rest" in step.get("run", "") - ] - assert sorted(calls) == ["Rest", "RestPython"], (workflow.name, calls) - shards = {} - for job_name, selector in (("RestPython", "1"), ("Rest", "2")): - job = jobs[job_name] - assert "strategy" not in job, f"{workflow.name}: extra {job_name} runners" - (run,) = [ - step - for step in job["steps"] - if "make test-other-python-rest" in step.get("run", "") - ] - (upload,) = [ - step - for step in job["steps"] - if step.get("uses", "").startswith("actions/upload-artifact") - and "rest-python-*.xml" in step["with"]["path"].split() - ] - argv = shlex.split(run["run"]) - assert argv[:5] == ["uv", "run", "--no-sync", "make", "test-other-python-rest"] - selectors = [ - arg.removeprefix("REST_PYTHON_SHARD=") - for arg in argv[5:] - if arg.startswith("REST_PYTHON_SHARD=") - ] - assert selectors == [selector], (workflow.name, job_name, argv) - assert all(arg.startswith("REST_") and "=" in arg for arg in argv[5:]), argv - shards[f"shard-{selector}"] = { - "overrides": argv[5:], - "artifact": upload["with"]["name"], - "patterns": upload["with"]["path"].split(), - } - return shards - - -def ci_report_dir(workflow): - """The REST_REPORT_DIR each workflow shard passes to the groups.""" - dirs = [] - for shard in ci_python_shards(workflow).values(): - values = [ - arg.removeprefix("REST_REPORT_DIR=") - for arg in shard["overrides"] - if arg.startswith("REST_REPORT_DIR=") - ] - assert len(values) == 1, f"{workflow.name} runs without one REST_REPORT_DIR" - dirs.extend(values) - assert len(set(dirs)) == 1, dirs - return dirs[0] - - def reported_groups(report_dir, *overrides): """Each group's pytest arguments and report files, in run order. @@ -225,6 +162,7 @@ def reported_groups(report_dir, *overrides): assert match, xml group = match.group(1) assert group not in groups, f"{group} runs twice" + assert argv[3] == f"{report_dir}/rest-python-{group}-resources.txt", argv groups[group] = { "args": [arg for arg in argv[5:] if arg != junit[0]], "reports": [xml, argv[3]], @@ -233,15 +171,8 @@ def reported_groups(report_dir, *overrides): @pytest.fixture(scope="module") -def report_dir(): - dirs = {ci_report_dir(workflow) for workflow in WORKFLOWS} - assert len(dirs) == 1, f"The workflows disagree on REST_REPORT_DIR: {dirs}" - return dirs.pop() - - -@pytest.fixture(scope="module") -def groups(report_dir): - return reported_groups(report_dir) +def groups(): + return reported_groups(REPORT_DIR) @pytest.fixture(scope="module") @@ -249,20 +180,12 @@ def old_command(): """The pytest arguments of the single process the groups replace. It was test-other-python, the Python tests outside contrib and - microsimulation, with the SPM and Simulation/API files left to their - own sequential processes on the Microsimulation runner. + microsimulation, with the SPM files left to their own step. """ (other,) = dry_run("test-other-python") - simulation_commands = dry_run("test-other-python-spm") - assert other[0] == "pytest" - assert simulation_commands - assert all(command[0] == "pytest" for command in simulation_commands) - spm_files = [ - arg - for command in simulation_commands - for arg in command[1:] - if not arg.startswith("-") - ] + (spm,) = dry_run("test-other-python-spm") + assert other[0] == spm[0] == "pytest", (other, spm) + spm_files = [arg for arg in spm[1:] if not arg.startswith("-")] return other[1:] + [f"--ignore={file}" for file in spm_files] @@ -285,72 +208,517 @@ def test_groups_collect_each_file_of_the_old_single_process_once( assert not problems, "\n".join(problems) -@pytest.mark.parametrize("workflow", WORKFLOWS, ids=lambda path: path.name) -def test_ci_shards_run_each_group_and_each_python_file_once( - workflow, groups, group_files, reference, report_dir +def test_planner_reads_the_groups_the_makefile_runs(groups): + assert shards.make_groups() == { + group: spec["args"] for group, spec in groups.items() + } + + +def stable_seconds(file, low, high): + """A per-file time in [low, high) that depends only on the file name.""" + return low + (zlib.crc32(file.encode()) % 1000) / 1000 * (high - low) + + +def timing_scenarios(group_files): + files = [f for group in group_files.values() for f in group] + copies = "policyengine_us/tests/core/test_behavioral_response_measurement_copies.py" + measured = {f: stable_seconds(f, 0.5, 60) for f in files} + skewed = dict(measured) + skewed[files[0]] = 40 * 60 + if copies in skewed: + skewed[copies] = 27 * 60 + return { + "no reports": {}, + "measured": measured, + "partly measured": { + f: s for f, s in measured.items() if zlib.crc32(f.encode()) % 3 + }, + "one file past the target": skewed, + "tiny": {f: 0.1 for f in files}, + "huge": {f: 600 for f in files}, + } + + +@pytest.mark.parametrize( + "scenario", + [ + "no reports", + "measured", + "partly measured", + "one file past the target", + "tiny", + "huge", + ], +) +def test_every_plan_runs_each_group_file_once_in_group_order( + group_files, reference, scenario ): + seconds = timing_scenarios(group_files)[scenario] + plan = shards.make_plan(group_files, seconds) + assert shards.MIN_SHARDS <= len(plan) <= shards.MAX_SHARDS + assert [shard["shard"] for shard in plan] == list(range(1, len(plan) + 1)) + assert sum(shard["variables"] for shard in plan) == 1 selected = {} - for shard, config in ci_python_shards(workflow).items(): - shard_groups = reported_groups(report_dir, *config["overrides"]) - assert shard_groups, f"{workflow.name}: {shard} runs no groups" - for group, spec in shard_groups.items(): - assert group in groups, f"{workflow.name}: unknown group {group}" - assert spec == groups[group], (workflow.name, shard, group, spec) - selected[f"{shard}/{group}"] = group_files[group] + names = [] + for shard in plan: + assert shard["processes"], f"shard {shard['shard']} runs nothing" + for process in shard["processes"]: + names.append(process["name"]) + group = group_files[process["group"]] + assert process["name"] == process["group"] or re.fullmatch( + rf"{re.escape(process['group'])}-\d+", process["name"] + ) + # One group per process, in the order its group's process ran. + positions = [group.index(file) for file in process["files"]] + assert positions == sorted(positions), process["name"] + selected[f"shard {shard['shard']}/{process['name']}"] = process["files"] + # Process names become report names, which must not collide. + assert len(names) == len(set(names)), names problems = partition_problems(reference, selected) - assert not problems, f"{workflow.name}:\n" + "\n".join(problems) + assert not problems, f"{scenario}:\n" + "\n".join(problems) + + +def test_a_long_group_splits_and_its_longest_file_runs_alone(): + groups = { + "core": [f"core/test_{i:03d}.py" for i in range(115)], + "remaining": [f"test_{i:03d}.py" for i in range(87)], + "heavy": ["test_heavy.py"], + } + seconds = {f: 12 for f in groups["core"]} | {f: 15 for f in groups["remaining"]} + seconds["core/test_050.py"] = 27 * 60 + seconds["test_heavy.py"] = 6 * 60 + plan = shards.make_plan(groups, seconds, overhead=60, variables=70) + processes = {p["name"]: p for shard in plan for p in shard["processes"]} + # 50 core minutes split at 25; the 27-minute file fills a chunk alone. + assert sorted(processes) == ["core-1", "core-2", "heavy", "remaining"] + assert ["core/test_050.py"] in [p["files"] for p in processes.values()] + # Groups shorter than the target keep one process. + assert processes["remaining"]["files"] == groups["remaining"] + + +def rest_shaped_groups(): + """Groups and times shaped like the October 2026 Rest reports.""" + sizes = { + "cached-arrays": (1, 390), + "heavy-a": (4, 85), + "heavy-b": (4, 150), + "core-heavy": (3, 140), + "core": (115, 12), + "policy-parameters": (3, 70), + "policy": (25, 33), + "remaining-heavy": (6, 80), + "remaining": (87, 15), + } + groups = { + group: [f"{group}/test_{i:03d}.py" for i in range(count)] + for group, (count, _) in sizes.items() + } + seconds = { + file: sizes[group][1] for group, files in groups.items() for file in files + } + seconds["core/test_050.py"] = 27 * 60 + return groups, seconds + + +def test_the_plan_uses_the_fewest_shards_that_keep_the_longest_near_the_bound(): + groups, seconds = rest_shaped_groups() + plan = shards.make_plan(groups, seconds, overhead=60, variables=70) + cost = shards.estimates(groups, seconds) + weights = { + p["name"]: 60 + sum(cost[f] for f in p["files"]) + for shard in plan + for p in shard["processes"] + } + bound = shards.MAKESPAN_TOLERANCE * max( + shards.TARGET_MINUTES * 60, max(weights.values()) + ) + loads = [sum(weights[p["name"]] for p in shard["processes"]) for shard in plan] + assert max(loads) <= bound + # One shard fewer cannot meet the bound, so the plan uses no extra runner. + _, fewer = shards.longest_first(list(weights), len(plan) - 1, weights.get) + assert max(fewer) > bound + assert len(plan) == 6 + # The variables YAML goes to the least-loaded shard. + (marked,) = [i for i, shard in enumerate(plan) if shard["variables"]] + assert loads[marked] == min(loads) + assert plan[marked]["minutes"] == round((loads[marked] + 70) / 60, 1) + + +def test_plans_without_times_count_files_evenly_and_stay_complete(): + groups = {"a": [f"a/test_{i:03d}.py" for i in range(300)], "b": ["b/test_0.py"]} + plan = shards.make_plan(groups) + processes = [p for shard in plan for p in shard["processes"]] + files = sorted(f for p in processes for f in p["files"]) + assert files == sorted(groups["a"] + groups["b"]) + # 300 files at DEFAULT_FILE_SECONDS make 150 minutes: six equal chunks, + # 26 minutes each with process start. b cannot join one of them within + # the tolerance, so it gets a seventh shard, which also runs variables. + chunks = [len(p["files"]) for p in processes if p["group"] == "a"] + assert chunks == [50] * 6 + assert len(plan) == 7 + assert max(shard["minutes"] for shard in plan) == 26.0 + (marked,) = [shard for shard in plan if shard["variables"]] + assert [p["group"] for p in marked["processes"]] == ["b"] + + +def test_the_planner_refuses_group_options_a_shard_cannot_pass_on(tmp_path): + command = ( + "\t/usr/bin/time -v -o $(REST_REPORT_DIR)/rest-python-a-resources.txt " + "pytest a --maxfail=0 --ignore=a/b{extra} " + "--junitxml=$(REST_REPORT_DIR)/rest-python-a.xml\n" + ) + makefile = tmp_path / "Makefile" + makefile.write_text("test-other-python-rest:\n" + command.format(extra="")) + assert shards.make_groups(tmp_path) == {"a": ["a", "--maxfail=0", "--ignore=a/b"]} + makefile.write_text( + "test-other-python-rest:\n" + command.format(extra=" -p no:randomly") + ) + with pytest.raises(RuntimeError, match=r"cannot pass on \['-p'\]"): + shards.make_groups(tmp_path) + + +def test_the_plan_command_writes_a_complete_matrix_and_summary(tmp_path, group_files): + files = [f for group in group_files.values() for f in group] + write_report( + tmp_path / "timings" / "rest-python-test-timings-shard-1", + "rest-python-core", + [(file.removesuffix(".py").replace("/", "."), 30) for file in files[:20]], + wall="12:00", + ) + output = tmp_path / "github-output" + summary = tmp_path / "summary.md" + result = subprocess.run( + [ + sys.executable, + str(PLANNER), + "plan", + "--timings", + str(tmp_path / "timings"), + "--source", + "release run 1", + "--github-output", + str(output), + "--summary", + str(summary), + ], + cwd=REPO, + env={k: v for k, v in os.environ.items() if k not in PARENT_MAKE_VARIABLES}, + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stdout + result.stderr + (line,) = output.read_text().splitlines() + assert line.startswith("matrix=") + entries = json.loads(line.removeprefix("matrix="))["include"] + planned = [ + file + for entry in entries + for process in json.loads(entry["processes"]) + for file in process["files"] + ] + assert sorted(planned) == sorted(files) + assert sum(entry["variables"] for entry in entries) == 1 + assert summary.read_text().startswith( + f"Rest Python plan: {len(entries)} shards, times from release run 1 " + f"(20 of {len(files)} files timed)." + ) + + +def test_unknown_files_count_as_their_groups_median(): + groups = {"a": ["a1.py", "a2.py", "a3.py", "new.py"], "b": ["b1.py", "b2.py"]} + seconds = {"a1.py": 10, "a2.py": 20, "a3.py": 300, "b1.py": 1, "b2.py": 3} + assert shards.estimates(groups, seconds)["new.py"] == 20 + assert shards.estimates({"c": ["c1.py"]} | groups, seconds)["c1.py"] == 10 + + +@pytest.mark.parametrize( + "change, message", + [ + (lambda plan: plan[0]["processes"][0]["files"].pop(), "missing"), + ( + lambda plan: plan[1]["processes"][0]["files"].append("a/test_0.py"), + "outside its group", + ), + ( + lambda plan: plan[0]["processes"][0]["files"].reverse(), + "outside its group", + ), + ( + lambda plan: plan[1]["processes"].append( + dict(plan[0]["processes"][0], name="a-2") + ), + "repeated", + ), + (lambda plan: plan[1]["processes"].clear(), "runs nothing"), + (lambda plan: plan[1].update(variables=True), "exactly one shard"), + ( + lambda plan: plan[1]["processes"][0].update(name="a"), + "runs twice", + ), + ], +) +def test_the_plan_check_rejects_dropped_repeated_or_mixed_files(change, message): + groups = {"a": ["a/test_0.py", "a/test_1.py"], "b": ["b/test_0.py"]} + plan = [ + { + "shard": 1, + "variables": True, + "processes": [{"name": "a", "group": "a", "files": list(groups["a"])}], + }, + { + "shard": 2, + "variables": False, + "processes": [{"name": "b", "group": "b", "files": list(groups["b"])}], + }, + ] + shards.check_plan(groups, plan) + change(plan) + with pytest.raises(AssertionError, match=message): + shards.check_plan(groups, plan) + + +def write_report(directory, name, cases, wall=None): + """A JUnit report of (classname, seconds) cases and its GNU time report.""" + directory.mkdir(parents=True, exist_ok=True) + body = "".join( + f'' + for i, (classname, time) in enumerate(cases) + ) + (directory / f"{name}.xml").write_text( + f'{body}' + ) + if wall is not None: + (directory / f"{name}-resources.txt").write_text( + "\tCommand being timed: pytest\n" + f"\tElapsed (wall clock) time (h:mm:ss or m:ss): {wall}\n" + "\tMaximum resident set size (kbytes): 1000\n" + ) + + +def test_timings_come_from_each_shards_junit_and_gnu_time_reports(tmp_path): + files = ["pkg/tests/test_a.py", "pkg/tests/core/test_b.py", "pkg/tests/test_c.py"] + write_report( + tmp_path / "rest-python-test-timings-shard-1", + "rest-python-core-1", + [ + ("pkg.tests.test_a", 10), + ("pkg.tests.test_a.TestClass", 5.5), + ("pkg.tests.core.test_b", 20), + ("pkg.tests.test_removed", 7), + ], + wall="1:02.5", + ) + write_report( + tmp_path / "rest-python-test-timings-shard-2", + "rest-python-remaining", + [("pkg.tests.core.test_b", 1)], + wall="1:00:01", + ) + write_report(tmp_path / "rest-variables-test-timings", "rest-variables", [], "1:10") + # An earlier attempt's leftover report covers files a later shard ran + # too: each file counts once, at its longer time, not twice. + write_report( + tmp_path / "rest-python-test-timings-shard-6", + "rest-python-core-3", + [("pkg.tests.test_a", 12), ("pkg.tests.core.test_b", 30)], + ) + seconds, overhead, variables = shards.read_timings(tmp_path, files) + assert seconds == {"pkg/tests/test_a.py": 15.5, "pkg/tests/core/test_b.py": 30} + # 62.5 - 42.5 and 3601 - 1 seconds outside tests: the median of the two. + assert overhead == pytest.approx((20 + 3600) / 2) + assert variables == 70 + assert shards.read_timings(tmp_path / "missing", files) == ({}, None, None) + + +def test_the_matrix_carries_each_shards_processes_as_json(): + groups = {"a": ["a/test_0.py", "a/test_1.py"], "b": ["b/test 0's.py"]} + plan = shards.make_plan(groups, min_shards=2) + entries = shards.matrix(plan)["include"] + assert [entry["shard"] for entry in entries] == [1, 2] + assert [entry["variables"] for entry in entries] == [ + shard["variables"] for shard in plan + ] + assert [json.loads(entry["processes"]) for entry in entries] == [ + shard["processes"] for shard in plan + ] + + +def ci_jobs(workflow): + jobs = workflow_jobs(workflow) + calls = [ + name + for name, config in jobs.items() + for step in config.get("steps", []) + if PLANNER_COMMAND in step.get("run", "") + or "make test-other-python-rest" in step.get("run", "") + ] + assert sorted(calls) == ["RestPlan", "RestPython"], (workflow.name, calls) + return jobs @pytest.mark.parametrize("workflow", WORKFLOWS, ids=lambda path: path.name) -def test_each_group_writes_reports_its_ci_shard_uploads(workflow, report_dir): - artifacts = [] - reports = [] - for config in ci_python_shards(workflow).values(): - artifacts.append(config["artifact"]) - shard_reports = [ - report - for spec in reported_groups(report_dir, *config["overrides"]).values() - for report in spec["reports"] - ] - reports.extend(shard_reports) - patterns = [os.path.normpath(p) for p in config["patterns"]] - missing = [ - report - for report in shard_reports - if not any(fnmatch(os.path.normpath(report), p) for p in patterns) - ] - assert not missing, f"{workflow.name} does not upload {missing}" - assert len(set(reports)) == len(reports), reports - variable_uploads = [ - step - for step in rest_steps(workflow, "RestPython") - if step.get("uses", "").startswith("actions/upload-artifact") - and "rest-variables.xml" in step["with"]["path"].split() +def test_ci_plans_from_recent_reports_then_runs_and_uploads_each_shard(workflow): + jobs = ci_jobs(workflow) + plan_job, shard_job = jobs["RestPlan"], jobs["RestPython"] + assert plan_job["permissions"] == {"actions": "read", "contents": "read"} + assert plan_job["outputs"] == {"matrix": "${{ steps.plan.outputs.matrix }}"} + download = single(plan_job["steps"], lambda step: step.get("id") == "timings") + plan = single(plan_job["steps"], lambda step: step.get("id") == "plan") + assert plan_job["steps"].index(download) < plan_job["steps"].index(plan) + assert download["env"] == {"GH_TOKEN": "${{ github.token }}"} + assert plan["env"] == {"TIMINGS_SOURCE": "${{ steps.timings.outputs.source }}"} + assert shlex.split(plan["run"]) == [ + "uv", + "run", + "--no-sync", + *PLANNER_COMMAND.split(), + "plan", + "--timings", + "rest-timings", + "--source", + "$TIMINGS_SOURCE", + "--github-output", + "$GITHUB_OUTPUT", + "--summary", + "$GITHUB_STEP_SUMMARY", ] - assert len(variable_uploads) == 1 - artifacts.append(variable_uploads[0]["with"]["name"]) - assert len(set(artifacts)) == len(artifacts), artifacts - for job in ("RestPython", "Rest"): - steps = rest_steps(workflow, job) - (run,) = [ - step - for step in steps - if "make test-other-python-rest" in step.get("run", "") - ] - assert run["if"] == KEEP_RUNNING_WITH_SYSTEM_CA - assert_system_ca_precedes(steps, run) - (upload,) = [ - step - for step in steps - if step.get("uses", "").startswith("actions/upload-artifact") + assert not any(step.get("continue-on-error") for step in plan_job["steps"]) + + assert shard_job["needs"] == ["RestPlan"] + assert shard_job["strategy"] == { + "fail-fast": False, + "matrix": "${{ fromJSON(needs.RestPlan.outputs.matrix) }}", + } + assert "${{ matrix.shard }}" in shard_job["name"] + steps = shard_job["steps"] + run = single(steps, lambda step: PLANNER_COMMAND in step.get("run", "")) + assert shlex.split(run["run"]) == [ + "uv", + "run", + "--no-sync", + *PLANNER_COMMAND.split(), + "run", + "--report-dir", + ".", + ] + assert run["env"]["REST_PYTHON_PROCESSES"] == "${{ matrix.processes }}" + assert run["if"] == KEEP_RUNNING_WITH_SYSTEM_CA + assert_system_ca_precedes(steps, run) + upload = single( + steps, + lambda step: ( + step.get("uses", "").startswith("actions/upload-artifact") and "rest-python-*.xml" in step["with"]["path"].split() - ] - assert upload["if"] == "always()" - assert not any(step.get("continue-on-error", False) for step in steps) + ), + ) + assert upload["if"] == "always()" + assert ( + upload["with"]["name"] == "rest-python-test-timings-shard-${{ matrix.shard }}" + ) + patterns = upload["with"]["path"].split() + # Every report a planned process writes is uploaded, under a name the + # next plan downloads and reads. + reports = [ + f"./rest-python-{name}{suffix}" + for name in ("core", "core-12", "remaining-heavy") + for suffix in (".xml", "-resources.txt") + ] + for report in reports: + assert any(fnmatch(os.path.normpath(report), p) for p in patterns), report + assert fnmatch("rest-python-core-12.xml", "rest-python-*.xml") + shard_artifact = upload["with"]["name"].replace("${{ matrix.shard }}", "12") + assert "--pattern 'rest-python-test-timings-*'" in download["run"] + assert fnmatch(shard_artifact, "rest-python-test-timings-*") + assert not any(step.get("continue-on-error") for step in steps) + if workflow.name == "push.yaml": + for job in (plan_job, shard_job): + assert " ".join(job["if"].split()) == RELEASE_ONLY + assert plan_job["needs"] == "ReleaseLock" + else: + assert "if" not in shard_job and "if" not in plan_job + assert "needs" not in plan_job + + +STUB_GH = """#!/bin/sh +echo "$*" >> "$STUB_CALLS" +case "$1 $2" in + "run list") + [ "$STUB_LIST" = fail ] && exit 1 + printf '%s\\n' $STUB_RUNS + ;; + "run download") + for good in $STUB_GOOD; do + if [ "$3" = "$good" ]; then + mkdir -p "rest-timings/$3/rest-python-test-timings-shard-1" + exit 0 + fi + done + mkdir -p "rest-timings/$3/partial" + exit 1 + ;; +esac +""" + + +@pytest.mark.parametrize("workflow", WORKFLOWS, ids=lambda path: path.name) +@pytest.mark.parametrize( + "runs, good, listing, source, tried", + [ + ("101 102", "101 102", "ok", "release run 101", ["101"]), + ("101 102", "102", "ok", "release run 102", ["101", "102"]), + ("101 102 103 104", "104", "ok", None, ["101", "102", "103"]), + ("", "", "ok", None, []), + ("101", "101", "fail", None, []), + ], +) +def test_the_timing_download_never_fails_the_plan( + tmp_path, workflow, runs, good, listing, source, tried +): + download = single( + workflow_jobs(workflow)["RestPlan"]["steps"], + lambda step: step.get("id") == "timings", + ) + assert download["shell"] == "bash" + stub = tmp_path / "bin" / "gh" + stub.parent.mkdir() + stub.write_text(STUB_GH) + stub.chmod(0o755) + output = tmp_path / "output.txt" + calls = tmp_path / "calls.txt" + calls.touch() + env = dict( + os.environ, + PATH=f"{stub.parent}{os.pathsep}{os.environ['PATH']}", + GITHUB_OUTPUT=str(output), + GITHUB_REPOSITORY="PolicyEngine/policyengine-us", + STUB_CALLS=str(calls), + STUB_RUNS=runs, + STUB_GOOD=good, + STUB_LIST=listing, + ) + result = subprocess.run( + ["bash", "-e", "-c", download["run"]], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stdout + result.stderr + written = output.read_text() if output.exists() else "" + assert written == (f"source={source}\n" if source else "") + downloads = [ + line.split()[2] for line in calls.read_text().splitlines() if "download" in line + ] + assert downloads == tried + # A failed download leaves nothing for the plan to read. + kept = sorted(p.name for p in (tmp_path / "rest-timings").glob("*")) + assert kept == ([source.split()[-1]] if source else []) + if not source: + assert "::warning::No Rest Python timing reports" in result.stdout @pytest.mark.parametrize("workflow", WORKFLOWS, ids=lambda path: path.name) -def test_variable_yaml_selection_runs_once_in_the_first_python_shard(workflow): +def test_variable_yaml_selection_runs_once_on_the_planned_shard(workflow): jobs = workflow_jobs(workflow) calls = [ (job, step) @@ -360,9 +728,12 @@ def test_variable_yaml_selection_runs_once_in_the_first_python_shard(workflow): ] assert len(calls) == 1, (workflow.name, calls) job, step = calls[0] + # The plan marks exactly one shard (see the plan tests above). assert job == "RestPython" - assert "strategy" not in jobs[job], "variables YAML must run exactly once" - assert step["if"] == KEEP_RUNNING_WITH_SYSTEM_CA + assert step["if"] == ( + "${{ !cancelled() && steps.system-ca.outcome == 'success' " + "&& matrix.variables }}" + ) assert_system_ca_precedes(jobs[job]["steps"], step) assert shlex.split(step["run"]) == [ "/usr/bin/time", @@ -383,17 +754,19 @@ def test_variable_yaml_selection_runs_once_in_the_first_python_shard(workflow): "--batches", "1", ] - assert not any( - "make test-yaml-variables" in candidate.get("run", "") - for candidate in rest_steps(workflow, "Rest") + upload = single( + jobs[job]["steps"], + lambda candidate: ( + candidate.get("uses", "").startswith("actions/upload-artifact") + and "rest-variables.xml" in candidate["with"]["path"].split() + ), ) - (upload,) = [ - candidate - for candidate in jobs[job]["steps"] - if candidate.get("uses", "").startswith("actions/upload-artifact") - and "rest-variables.xml" in candidate["with"]["path"].split() - ] - assert upload["if"] == "always()" + assert upload["if"] == "${{ always() && matrix.variables }}" + assert upload["with"]["name"] == "rest-variables-test-timings" + download = single( + jobs["RestPlan"]["steps"], lambda candidate: candidate.get("id") == "timings" + ) + assert "--pattern rest-variables-test-timings" in download["run"] junit = [ arg.removeprefix("--junitxml=") for arg in shlex.split(step["env"]["PYTEST_ADDOPTS"]) @@ -408,58 +781,37 @@ def test_variable_yaml_selection_runs_once_in_the_first_python_shard(workflow): @pytest.mark.parametrize("workflow", WORKFLOWS, ids=lambda path: path.name) -def test_original_rest_check_aggregates_all_shards_without_hiding_failure(workflow): +def test_the_rest_check_aggregates_the_plan_and_shards_without_hiding_failure( + workflow, +): jobs = workflow_jobs(workflow) summary = jobs["Rest"] - assert summary["name"] == "Full Suite - Rest (Python + variables)" - assert summary["needs"] == ["RestPython"] - # Shard 2 still runs after a shard-1 failure, but a cancelled run stops - # it: a job-level always() kept it running after cancellation. + assert summary["name"] == "Check Rest Python shards" + assert summary["needs"] == ["RestPlan", "RestPython"] + # It runs after a failed plan or shard, but a cancelled run stops it: a + # job-level always() kept it running after cancellation. assert "always()" not in summary["if"] assert "strategy" not in summary - assert summary["timeout-minutes"] == 90 assert not summary.get("continue-on-error", False) + assert not jobs["RestPlan"].get("continue-on-error", False) assert not jobs["RestPython"].get("continue-on-error", False) if workflow.name == "push.yaml": assert " ".join(summary["if"].split()) == ( - "!cancelled() && (needs.RestPython.result != 'skipped') " - "&& (github.repository == 'PolicyEngine/policyengine-us') " - "&& (github.event.head_commit.message == 'Update PolicyEngine US')" + "!cancelled() && (needs.RestPlan.result != 'skipped') && " + RELEASE_ONLY ) - assert {"RestPython", "Rest"} <= set(jobs["Publish"]["needs"]) + assert {"RestPlan", "RestPython", "Rest"} <= set(jobs["Publish"]["needs"]) else: assert summary["if"] == "${{ !cancelled() }}" - (step,) = [ - candidate - for candidate in summary["steps"] - if "PYTHON_RESULT" in candidate.get("env", {}) - ] - (python_step,) = [ - candidate - for candidate in summary["steps"] - if candidate.get("id") == "python_tests" - ] - assert "make test-other-python-rest" in python_step["run"] - assert "REST_PYTHON_SHARD=2" in shlex.split(python_step["run"]) - assert python_step["if"] == KEEP_RUNNING_WITH_SYSTEM_CA - assert_system_ca_precedes(summary["steps"], python_step) - # This runner executes shard 2 before checking shard 1. Its own failures - # must remain failures, and cancellation skipping its Python step must - # fail the check even if shard 1 succeeded. - assert summary["steps"][-1] == step - assert step["if"] in ("always()", "${{ always() }}") + (step,) = summary["steps"] assert step["shell"] == "bash" assert step["env"] == { + "PLAN_RESULT": "${{ needs.RestPlan.result }}", "PYTHON_RESULT": "${{ needs.RestPython.result }}", - "SHARD_RESULT": "${{ steps.python_tests.outcome }}", } - assert not any( - candidate.get("continue-on-error", False) - for candidate in summary["steps"] + jobs["RestPython"]["steps"] - ) - for python in ("success", "failure", "cancelled", "skipped"): - for shard in ("success", "failure", "cancelled", "skipped"): - env = dict(os.environ, PYTHON_RESULT=python, SHARD_RESULT=shard) + outcomes = ("success", "failure", "cancelled", "skipped") + for plan in outcomes: + for python in outcomes: + env = dict(os.environ, PLAN_RESULT=plan, PYTHON_RESULT=python) result = subprocess.run( ["bash", "-e", "-c", step["run"]], cwd=REPO, @@ -467,10 +819,10 @@ def test_original_rest_check_aggregates_all_shards_without_hiding_failure(workfl capture_output=True, text=True, ) - assert (result.returncode == 0) == (python == shard == "success"), ( + assert (result.returncode == 0) == (plan == python == "success"), ( workflow.name, + plan, python, - shard, result.stdout + result.stderr, ) @@ -521,35 +873,19 @@ def test_spm_and_dataset_suites_run_once_in_separate_steps_with_reports(workflow assert uploads[0]["with"]["name"] != "rest-test-timings" -def test_calculator_api_files_run_once_in_separate_simulation_processes(): - commands = dry_run("test-other-python-spm") - files_by_process = [ - [arg for arg in command[1:] if not arg.startswith("-")] for command in commands - ] - files = [file for process_files in files_by_process for file in process_files] - assert len(files) == len(set(files)), "Simulation files run more than once" - for name in ("engine", "differential"): - file = f"policyengine_us/tests/unit/test_ss_calculator_{name}.py" - assert [process for process in files_by_process if file in process] == [ - [file] - ], f"{file} must run once in its own process" - - # The CI step gives SPM a JUnit path through PYTEST_ADDOPTS. Later - # processes need separate reports so they do not overwrite that suite. - reported = dry_run( - "test-other-python-spm", "PYTEST_ADDOPTS=--junitxml=simulation-spm.xml" - ) - reports = [ - arg.removeprefix("--junitxml=") - for command in reported - for arg in command[1:] - if arg.startswith("--junitxml=") - ] - assert reports == [ - "simulation-ss-calculator-engine.xml", - "simulation-ss-calculator-differential.xml", +@pytest.mark.parametrize("name", ["engine", "differential"]) +def test_calculator_api_files_run_once_in_separate_rest_processes( + groups, group_files, name +): + file = f"policyengine_us/tests/unit/test_ss_calculator_{name}.py" + group = f"ss-calculator-{name}" + assert group_files[group] == [file] + assert [owner for owner, files in group_files.items() if file in files] == [group] + assert groups[group]["reports"] == [ + f"{REPORT_DIR}/rest-python-{group}.xml", + f"{REPORT_DIR}/rest-python-{group}-resources.txt", ] - assert len(set(reports + ["simulation-spm.xml"])) == 3 + assert all(file not in command for command in dry_run("test-other-python-spm")) def test_groups_run_as_plain_pytest_without_a_report_dir(groups): @@ -559,27 +895,13 @@ def test_groups_run_as_plain_pytest_without_a_report_dir(groups): assert [argv[1:] for argv in plain] == [spec["args"] for spec in groups.values()] -def test_inherited_ci_shard_does_not_restrict_the_reference(monkeypatch, groups): - monkeypatch.setenv("REST_PYTHON_SHARD", "2") +def test_an_inherited_report_dir_does_not_change_the_reference(monkeypatch, groups): monkeypatch.setenv("REST_REPORT_DIR", "inherited-reports") plain = dry_run("test-other-python-rest") assert [argv[1:] for argv in plain] == [spec["args"] for spec in groups.values()] - - -@pytest.mark.parametrize("shard", ["0", "3", "unknown"]) -def test_invalid_shard_cannot_pass_without_running_any_groups(shard): - if shutil.which("make") is None: - pytest.skip("make is not installed") - env = {k: v for k, v in os.environ.items() if k not in PARENT_MAKE_VARIABLES} - result = subprocess.run( - ["make", "-n", "test-other-python-rest", f"REST_PYTHON_SHARD={shard}"], - cwd=REPO, - env=env, - capture_output=True, - text=True, - ) - assert result.returncode != 0 - assert "REST_PYTHON_SHARD must be 1 or 2" in result.stderr + assert shards.make_groups() == { + group: spec["args"] for group, spec in groups.items() + } def import_name(file): @@ -604,11 +926,12 @@ def test_test_files_keep_distinct_import_names(reference): assert not clashes, clashes -# Stands in for pytest on PATH: records its arguments, then exits with the -# next outcome in STUB_OUTCOMES, or kills itself with SIGKILL, as the kernel's -# out-of-memory killer does, for "killed". +# Stands in for pytest on PATH: records its arguments, joined with "|" so a +# split argument shows, then exits with the next outcome in STUB_OUTCOMES, or +# kills itself with SIGKILL, as the kernel's out-of-memory killer does, for +# "killed". STUB_PYTEST = """#!/bin/sh -echo "$*" >> "$STUB_CALLS" +(IFS='|'; echo "$*") >> "$STUB_CALLS" n=$(wc -l < "$STUB_CALLS" | tr -d ' ') outcome=$(echo "$STUB_OUTCOMES" | cut -d ' ' -f "$n") if [ "$outcome" = killed ]; then kill -9 $$; fi @@ -616,15 +939,7 @@ def test_test_files_keep_distinct_import_names(reference): """ -@pytest.mark.parametrize("scenario", ["one-fails-one-killed", "all-fail", "all-pass"]) -def test_every_group_runs_and_any_failure_fails_the_target(tmp_path, groups, scenario): - outcomes = ["0"] * len(groups) - if scenario == "one-fails-one-killed": - assert len(groups) >= 4, "need groups before and after the failures" - outcomes[1] = "1" - outcomes[3] = "killed" - elif scenario == "all-fail": - outcomes = ["killed"] + ["1"] * (len(groups) - 1) +def stub_environment(tmp_path, outcomes): stub = tmp_path / "bin" / "pytest" stub.parent.mkdir() stub.write_text(STUB_PYTEST) @@ -634,6 +949,24 @@ def test_every_group_runs_and_any_failure_fails_the_target(tmp_path, groups, sce env["PATH"] = f"{stub.parent}{os.pathsep}{env['PATH']}" env["STUB_CALLS"] = str(calls) env["STUB_OUTCOMES"] = " ".join(outcomes) + return env, calls + + +def scenario_outcomes(scenario, count): + outcomes = ["0"] * count + if scenario == "one-fails-one-killed": + assert count >= 4, "need processes before and after the failures" + outcomes[1] = "1" + outcomes[3] = "killed" + elif scenario == "all-fail": + outcomes = ["killed"] + ["1"] * (count - 1) + return outcomes + + +@pytest.mark.parametrize("scenario", ["one-fails-one-killed", "all-fail", "all-pass"]) +def test_every_group_runs_and_any_failure_fails_the_target(tmp_path, groups, scenario): + outcomes = scenario_outcomes(scenario, len(groups)) + env, calls = stub_environment(tmp_path, outcomes) result = subprocess.run( ["make", "--no-print-directory", "test-other-python-rest"], cwd=REPO, @@ -642,7 +975,7 @@ def test_every_group_runs_and_any_failure_fails_the_target(tmp_path, groups, sce text=True, ) # Every group ran, with the arguments the dry runs above check. - ran = [" ".join(spec["args"]) for spec in groups.values()] + ran = ["|".join(spec["args"]) for spec in groups.values()] assert calls.read_text().splitlines() == ran failed = [group for group, outcome in zip(groups, outcomes) if outcome != "0"] assert (result.returncode != 0) == bool(failed), result.stdout + result.stderr @@ -650,6 +983,88 @@ def test_every_group_runs_and_any_failure_fails_the_target(tmp_path, groups, sce assert f"Failed Rest Python groups: {' '.join(failed)}" in result.stdout +@pytest.mark.parametrize("scenario", ["one-fails-one-killed", "all-fail", "all-pass"]) +def test_every_planned_process_runs_and_any_failure_fails_the_shard(tmp_path, scenario): + processes = [ + {"name": f"g{i}", "group": f"g{i}", "files": [f"g{i}/test_a.py", "t b.py"]} + for i in range(5) + ] + outcomes = scenario_outcomes(scenario, len(processes)) + env, calls = stub_environment(tmp_path, outcomes) + env["REST_PYTHON_PROCESSES"] = json.dumps(processes) + result = subprocess.run( + [sys.executable, str(PLANNER), "run"], + cwd=REPO, + env=env, + capture_output=True, + text=True, + ) + assert calls.read_text().splitlines() == [ + "|".join([*p["files"], "--maxfail=0"]) for p in processes + ] + failed = [p["name"] for p, outcome in zip(processes, outcomes) if outcome != "0"] + assert (result.returncode != 0) == bool(failed), result.stdout + result.stderr + if failed: + assert f"Failed Rest Python groups: {' '.join(failed)}" in result.stdout + + +def test_a_shard_without_processes_fails(tmp_path): + env, calls = stub_environment(tmp_path, []) + for value in (None, "", "[]"): + if value is None: + env.pop("REST_PYTHON_PROCESSES", None) + else: + env["REST_PYTHON_PROCESSES"] = value + result = subprocess.run( + [sys.executable, str(PLANNER), "run"], + cwd=REPO, + env=env, + capture_output=True, + text=True, + ) + assert result.returncode == 1, (value, result.stdout + result.stderr) + assert not calls.exists() + + +def test_each_process_writes_its_own_reports_in_the_report_dir(monkeypatch): + commands = [] + monkeypatch.setattr( + shards.subprocess, + "run", + lambda command: ( + commands.append(command) or subprocess.CompletedProcess(command, 0) + ), + ) + processes = [ + {"name": "core-2", "group": "core", "files": ["core/test_a.py"]}, + {"name": "policy", "group": "policy", "files": ["p/test_b.py", "p/test_c.py"]}, + ] + assert shards.run_processes(processes, ".") == 0 + assert commands == [ + [ + "/usr/bin/time", + "-v", + "-o", + "./rest-python-core-2-resources.txt", + "pytest", + "core/test_a.py", + "--maxfail=0", + "--junitxml=./rest-python-core-2.xml", + ], + [ + "/usr/bin/time", + "-v", + "-o", + "./rest-python-policy-resources.txt", + "pytest", + "p/test_b.py", + "p/test_c.py", + "--maxfail=0", + "--junitxml=./rest-python-policy.xml", + ], + ] + + def test_conftest_files_cannot_change_which_files_are_collected(old_command): """The listing skips conftest.py; that is exact only while no conftest.py the Rest groups load defines collection hooks, collect_ignore or plugins.""" @@ -717,52 +1132,3 @@ def test_the_check_reports_a_file_in_two_groups(tmp_path): "b/test_two.py is collected by everything but was not in the old " "single process", ] - - -# --- Run as a script: list the files pytest collects, importing none --------- - - -class _Unimported(pytest.File): - """A test file pytest would import, standing in as one placeholder item.""" - - def collect(self): - yield _Placeholder.from_parent(self, name=self.path.name) - - -class _Placeholder(pytest.Item): - def runtest(self): - raise AssertionError("listed for collection only") - - -class _FileListing: - def __init__(self): - self.files = [] - - @pytest.hookimpl(tryfirst=True) - def pytest_pycollect_makemodule(self, module_path, parent): - return _Unimported.from_parent(parent, path=module_path) - - def pytest_collection_finish(self, session): - # Read the kept items, not the modules built: for a file argument - # pytest builds a module for each file beside it, then keeps one. - self.files = [ - Path(os.path.relpath(item.path)).as_posix() for item in session.items - ] - - -if __name__ == "__main__": - output, *pytest_args = sys.argv[1:] - listing = _FileListing() - status = pytest.main( - [ - *pytest_args, - "--collect-only", - "-q", - "--noconftest", - "-p", - "no:cacheprovider", - ], - plugins=[listing], - ) - Path(output).write_text(json.dumps(listing.files)) - sys.exit(status) diff --git a/policyengine_us/tests/rest_python_shards.py b/policyengine_us/tests/rest_python_shards.py new file mode 100644 index 00000000000..ac41129c5b8 --- /dev/null +++ b/policyengine_us/tests/rest_python_shards.py @@ -0,0 +1,505 @@ +#!/usr/bin/env python +"""Plan the Rest Python tests over parallel CI shards, and run one shard. + +`make test-other-python-rest` runs one pytest process per group in +REST_PYTHON_GROUPS (Makefile): modules that retain full systems sit in their +own groups, so no process outgrows the 16 GB runner. CI used to run those +groups on two runners, the second waiting for the first. By October 2026 one +file, test_behavioral_response_measurement_copies.py (27 minutes), had taken +the core group to 50 minutes and the two runners to 130 (CI run 40014592006), +the longest path of every PR. + +`plan` reads the groups from the Makefile and pytest's own collection, and +each file's time from the JUnit reports of a recent CI run. A group longer +than the target splits into chunks of about the target, longest files first, +each chunk keeping the group's file order. Chunks and whole groups then go to +the least-loaded shard, longest first, over as few shards as keep the longest +near the target or the longest single chunk. A process still runs files of +one group only, so none holds more than its group did. A file without a +recorded time counts as its group's median. Without any reports every file +counts the same, and the plan still runs each file once, only less evenly. + +`run` runs one shard's processes in turn, each with its own JUnit and GNU +time report when given a report directory, and fails if any of them fails. +code_health/test_rest_python_groups.py checks that every plan runs each file +of the groups exactly once. +""" + +import argparse +import json +import math +import os +import re +import shlex +import statistics +import subprocess +import sys +import tempfile +from collections import defaultdict +from pathlib import Path +from xml.etree import ElementTree + +REPO = Path(__file__).resolve().parents[2] + +# Each shard aims at about this many minutes. The Baseline and Contrib chain +# takes about 70, so the Python shards finish well inside it. +TARGET_MINUTES = 25 +# Bounds on the shard count whatever the reports say: missing or tiny times +# cannot pile every group onto one runner. +MIN_SHARDS = 4 +MAX_SHARDS = 12 +# A plan whose longest shard is within this of the bound is good enough; +# another runner would only shave a minute or two. +MAKESPAN_TOLERANCE = 1.05 +# Interpreter start, model import and collection, per process, when no +# report measures it (CI run 40014592006: 50-105 s per group). +DEFAULT_PROCESS_SECONDS = 60 +# Per file when no report covers any file of the group: the Rest groups +# averaged 27 s per file in CI run 40014592006. +DEFAULT_FILE_SECONDS = 30 +DEFAULT_VARIABLES_SECONDS = 90 + +# A make run passes these on to the make the planner starts, where they +# would add or remove report options from the groups' commands. +PARENT_MAKE_VARIABLES = ("MAKEFLAGS", "MFLAGS", "MAKELEVEL", "REST_REPORT_DIR") +REPORT_MARKER = "@rest-report-dir@" + + +def make_groups(cwd=REPO): + """Each Rest group's pytest arguments, in run order, from make's dry run. + + The group name comes from its JUnit file, rest-python-.xml. + """ + env = {k: v for k, v in os.environ.items() if k not in PARENT_MAKE_VARIABLES} + result = subprocess.run( + [ + "make", + "-n", + "--no-print-directory", + "test-other-python-rest", + f"REST_REPORT_DIR={REPORT_MARKER}", + ], + cwd=cwd, + env=env, + capture_output=True, + text=True, + ) + if result.returncode != 0: + raise RuntimeError(result.stdout + result.stderr) + groups = {} + junit = re.compile(rf"--junitxml={re.escape(REPORT_MARKER)}/rest-python-(.+)\.xml") + for line in result.stdout.splitlines(): + if not line.startswith("/usr/bin/time "): + continue + argv = shlex.split(line) + if argv[:3] != ["/usr/bin/time", "-v", "-o"] or argv[4] != "pytest": + raise RuntimeError(f"unexpected group command: {line}") + names = [m.group(1) for arg in argv[5:] if (m := junit.fullmatch(arg))] + if len(names) != 1 or names[0] in groups: + raise RuntimeError(f"cannot name the group of: {line}") + args = [arg for arg in argv[5:] if not junit.fullmatch(arg)] + # A shard passes pytest only the collected files and --maxfail=0, so + # any other option (-p, -m, --deselect...) would be lost in CI. + unsupported = [ + arg + for arg in args + if arg.startswith("-") + and arg != "--maxfail=0" + and not arg.startswith("--ignore=") + ] + if unsupported: + raise RuntimeError(f"shards cannot pass on {unsupported}: {line}") + groups[names[0]] = args + if not groups: + raise RuntimeError("make test-other-python-rest runs no groups") + return groups + + +def collected_files(args, cwd=REPO): + """The test files pytest collects for these arguments, relative to cwd. + + Nothing is imported: the `list-files` mode below swaps each test module + for a placeholder and skips conftest.py files. A command that collects + nothing (pytest's exit 5) lists no files. + """ + env = {k: v for k, v in os.environ.items() if k != "PYTEST_ADDOPTS"} + with tempfile.TemporaryDirectory() as tmp: + listing = Path(tmp) / "files.json" + result = subprocess.run( + [sys.executable, __file__, "list-files", str(listing), *args], + cwd=cwd, + env=env, + capture_output=True, + text=True, + ) + if result.returncode not in (0, 5): + raise RuntimeError(f"{args}:\n{result.stdout}{result.stderr}") + return json.loads(listing.read_text()) + + +def group_files(cwd=REPO): + """Each group's test files, in the order its pytest process runs them.""" + return { + group: collected_files(args, cwd) for group, args in make_groups(cwd).items() + } + + +# --- Times from CI reports ----------------------------------------------------- + + +def file_of(classname, files): + """The test file of a JUnit classname, which is its node ID's path with + dots for slashes, followed by any class names.""" + parts = classname.split(".") + for end in range(len(parts), 0, -1): + candidate = "/".join(parts[:end]) + ".py" + if candidate in files: + return candidate + return None + + +def wall_seconds(resources): + """The elapsed time in a GNU time -v report, or None without one.""" + if not resources.exists(): + return None + for line in resources.read_text().splitlines(): + if "Elapsed (wall clock) time" in line: + fields = [float(x) for x in line.rsplit(" ", 1)[1].split(":")] + return sum(x * 60**i for i, x in enumerate(reversed(fields))) + return None + + +def read_timings(directory, files): + """Seconds per test file, per process outside its tests, and for the + variables YAML, from the reports under a directory. + + Files no report covers are absent; the other two are None when no report + measures them. A re-run release run also keeps its earlier attempts' + reports under names the later plan did not reuse, so a file two reports + cover counts once, at the longer time. + """ + known = set(files) + seconds = {} + overheads = [] + variables = None + if directory is not None and Path(directory).is_dir(): + for xml in sorted(Path(directory).rglob("rest-python-*.xml")): + try: + root = ElementTree.parse(xml).getroot() + except ElementTree.ParseError: + continue + total = 0.0 + report = defaultdict(float) + for case in root.iter("testcase"): + time = float(case.get("time") or 0) + total = total + time + file = file_of(case.get("classname", ""), known) + if file is not None: + report[file] = report[file] + time + for file, time in report.items(): + seconds[file] = max(time, seconds.get(file, 0.0)) + wall = wall_seconds(xml.with_name(f"{xml.stem}-resources.txt")) + if wall is not None: + overheads.append(max(0.0, wall - total)) + for resources in Path(directory).rglob("rest-variables-resources.txt"): + variables = wall_seconds(resources) + overhead = statistics.median(overheads) if overheads else None + return seconds, overhead, variables + + +# --- Planning ------------------------------------------------------------------ + + +def estimates(groups, seconds): + """Seconds per file: its recorded time, else its group's median, else the + median over all groups, else DEFAULT_FILE_SECONDS.""" + recorded = [seconds[f] for files in groups.values() for f in files if f in seconds] + fallback = statistics.median(recorded) if recorded else DEFAULT_FILE_SECONDS + result = {} + for files in groups.values(): + known = [seconds[f] for f in files if f in seconds] + group_fallback = statistics.median(known) if known else fallback + for file in files: + result[file] = seconds.get(file, group_fallback) + return result + + +def longest_first(items, bins, weight): + """Deal items, longest first, each to the least-loaded of `bins` bins. + + Ties go to the lowest bin, so the result depends only on the inputs. + """ + loads = [0.0] * bins + contents = [[] for _ in range(bins)] + for item in sorted(items, key=lambda item: -weight(item)): + target = min(range(bins), key=lambda i: (loads[i], i)) + loads[target] = loads[target] + weight(item) + contents[target].append(item) + return contents, loads + + +def chunk_group(group, files, cost, target_seconds): + """Split a group longer than the target into chunks of about the target. + + Each chunk keeps the group's file order, so a chunk's process meets its + files in the order the whole group's process did. + """ + total = sum(cost[f] for f in files) + count = max(1, min(len(files), math.ceil(total / target_seconds))) + if count == 1: + return [(group, list(files))] + order = {f: i for i, f in enumerate(files)} + contents, _ = longest_first(files, count, cost.__getitem__) + chunks = [sorted(chunk, key=order.__getitem__) for chunk in contents if chunk] + chunks.sort(key=lambda chunk: order[chunk[0]]) + return [(f"{group}-{i}", chunk) for i, chunk in enumerate(chunks, start=1)] + + +def make_plan( + groups, + seconds=None, + overhead=None, + variables=None, + target_minutes=TARGET_MINUTES, + min_shards=MIN_SHARDS, + max_shards=MAX_SHARDS, +): + """Shards of processes that run every group's files once. + + Each process runs files of one group, in that group's order. The shard + count is the smallest in [min_shards, max_shards] whose longest shard is + within MAKESPAN_TOLERANCE of the target, or of the longest process when + that is longer. The variables YAML runs on the least-loaded shard. + """ + seconds = seconds or {} + overhead = DEFAULT_PROCESS_SECONDS if overhead is None else overhead + variables = DEFAULT_VARIABLES_SECONDS if variables is None else variables + target = target_minutes * 60 + cost = estimates(groups, seconds) + processes = [] + for group, files in groups.items(): + for name, chunk in chunk_group(group, files, cost, target): + estimate = overhead + sum(cost[f] for f in chunk) + processes.append( + {"name": name, "group": group, "files": chunk, "seconds": estimate} + ) + if not processes: + raise ValueError("no test files to plan") + weight = lambda process: process["seconds"] # noqa: E731 + bound = MAKESPAN_TOLERANCE * max(target, max(map(weight, processes))) + upper = max(1, min(max_shards, len(processes))) + count = min(min_shards, upper) + while True: + contents, loads = longest_first(processes, count, weight) + if max(loads) <= bound or count == upper: + break + count = count + 1 + lightest = min(range(count), key=lambda i: (loads[i], i)) + loads[lightest] = loads[lightest] + variables + order = {p["name"]: i for i, p in enumerate(processes)} + shards = [ + { + "shard": i + 1, + "minutes": round(loads[i] / 60, 1), + "variables": i == lightest, + "processes": [ + {"name": p["name"], "group": p["group"], "files": p["files"]} + for p in sorted(contents[i], key=lambda p: order[p["name"]]) + ], + } + for i in range(count) + ] + check_plan(groups, shards) + return shards + + +def check_plan(groups, shards): + """Raise unless the shards run each group's files once, in group order, + with no process mixing groups and no shard idle.""" + seen = defaultdict(list) + names = set() + for shard in shards: + if not shard["processes"]: + raise AssertionError(f"shard {shard['shard']} runs nothing") + for process in shard["processes"]: + if process["name"] in names: + raise AssertionError(f"process {process['name']} runs twice") + names.add(process["name"]) + group = groups.get(process["group"]) + if group is None or not process["files"]: + raise AssertionError(f"process {process['name']} has no group files") + order = [group.index(f) if f in group else -1 for f in process["files"]] + if -1 in order or order != sorted(order): + raise AssertionError( + f"process {process['name']} runs files outside its group's order" + ) + for file in process["files"]: + seen[file].append(process["name"]) + expected = [f for files in groups.values() for f in files] + missing = sorted(set(expected) - set(seen)) + repeated = sorted(f for f, owners in seen.items() if len(owners) > 1) + if missing or repeated or len(expected) != len(set(expected)): + raise AssertionError(f"missing: {missing}; repeated: {repeated}") + if sum(shard["variables"] for shard in shards) != 1: + raise AssertionError("the variables YAML must run on exactly one shard") + + +def matrix(shards): + """The GitHub Actions matrix: each shard's processes as a JSON string.""" + return { + "include": [ + { + "shard": shard["shard"], + "variables": shard["variables"], + "processes": json.dumps(shard["processes"], separators=(",", ":")), + } + for shard in shards + ] + } + + +def summary(shards, source): + lines = [ + f"Rest Python plan: {len(shards)} shards, times from {source}.", + "", + "| Shard | Estimated minutes | Processes (files) |", + "|---:|---:|---|", + ] + for shard in shards: + processes = ", ".join( + f"{p['name']} ({len(p['files'])})" for p in shard["processes"] + ) + if shard["variables"]: + processes = processes + ", variables YAML" + lines.append(f"| {shard['shard']} | {shard['minutes']} | {processes} |") + return "\n".join(lines) + "\n" + + +# --- Running a shard ----------------------------------------------------------- + + +def run_processes(processes, report_dir=None): + """Run each process in turn; 1 if any failed, was killed or is missing.""" + if not processes: + print("This shard has no Rest Python processes to run.") + return 1 + failed = [] + for process in processes: + name = process["name"] + print(f"=== Rest Python group: {name} ({len(process['files'])} files) ===") + sys.stdout.flush() + command = ["pytest", *process["files"], "--maxfail=0"] + if report_dir is not None: + command = [ + "/usr/bin/time", + "-v", + "-o", + f"{report_dir}/rest-python-{name}-resources.txt", + *command, + f"--junitxml={report_dir}/rest-python-{name}.xml", + ] + if subprocess.run(command).returncode != 0: + failed.append(name) + if failed: + print(f"Failed Rest Python groups: {' '.join(failed)}") + return 1 + return 0 + + +# --- Listing collected files without importing them ---------------------------- + + +def list_files(output, pytest_args): + import pytest + + class Unimported(pytest.File): + """A test file pytest would import, standing in as one item.""" + + def collect(self): + yield Placeholder.from_parent(self, name=self.path.name) + + class Placeholder(pytest.Item): + def runtest(self): + raise AssertionError("listed for collection only") + + class FileListing: + def __init__(self): + self.files = [] + + @pytest.hookimpl(tryfirst=True) + def pytest_pycollect_makemodule(self, module_path, parent): + return Unimported.from_parent(parent, path=module_path) + + def pytest_collection_finish(self, session): + # Read the kept items, not the modules built: for a file argument + # pytest builds a module for each file beside it, then keeps one. + self.files = [ + Path(os.path.relpath(item.path)).as_posix() for item in session.items + ] + + listing = FileListing() + status = pytest.main( + [ + *pytest_args, + "--collect-only", + "-q", + "--noconftest", + "-p", + "no:cacheprovider", + ], + plugins=[listing], + ) + Path(output).write_text(json.dumps(listing.files)) + return int(status) + + +def main(argv=None): + argv = sys.argv[1:] if argv is None else argv + if argv[:1] == ["list-files"]: + return list_files(argv[1], argv[2:]) + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + commands = parser.add_subparsers(dest="command", required=True) + plan = commands.add_parser("plan", help="plan the shards") + plan.add_argument("--timings", help="directory of CI timing reports") + plan.add_argument("--source", default="no reports", help="where they came from") + plan.add_argument("--github-output", help="file to append matrix= to") + plan.add_argument("--summary", help="file to append a Markdown summary to") + plan.add_argument("--target-minutes", type=float, default=TARGET_MINUTES) + run = commands.add_parser("run", help="run one shard's processes") + run.add_argument( + "--processes-env", + default="REST_PYTHON_PROCESSES", + help="environment variable holding the shard's processes as JSON", + ) + run.add_argument("--report-dir", help="write JUnit and GNU time reports here") + args = parser.parse_args(argv) + + if args.command == "run": + processes = json.loads(os.environ.get(args.processes_env) or "[]") + return run_processes(processes, args.report_dir) + + groups = group_files() + files = [f for group in groups.values() for f in group] + seconds, overhead, variables = read_timings(args.timings, files) + source = args.source + if not seconds: + print("::warning::No Rest Python timing reports; every file counts the same.") + source = "no reports (every file counts the same)" + else: + covered = sum(f in seconds for f in files) + source = f"{source} ({covered} of {len(files)} files timed)" + shards = make_plan(groups, seconds, overhead, variables, args.target_minutes) + text = summary(shards, source) + print(text) + print(json.dumps(shards, indent=1)) + if args.github_output: + with open(args.github_output, "a") as output: + output.write(f"matrix={json.dumps(matrix(shards))}\n") + if args.summary: + with open(args.summary, "a") as output: + output.write(text) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 3f03861babc5560bbb8771323bc48ca3a8ab853f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 26 Oct 2026 17:45:18 -0700 Subject: [PATCH 15/16] Use August commencement before the supplied survivor check --- .../baseline/gov/ssa/social_security/ss_calculated_benefit.yaml | 2 +- policyengine_us/tests/unit/test_ss_calculator_engine.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml b/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml index 0f165c7510d..65c75edc7ac 100644 --- a/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml +++ b/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml @@ -142,7 +142,7 @@ ss_calculator_source: survivor ss_calculator_worker_id: deceased-no-prior ss_calculator_birth_date: '1950-01-02' - ss_calculator_entitlement_month: '2020-11' + ss_calculator_entitlement_month: '2020-08' ss_calculator_insured: true ss_calculator_no_special_monthly_test: true ss_calculator_no_prior_withholding_adjustment: true diff --git a/policyengine_us/tests/unit/test_ss_calculator_engine.py b/policyengine_us/tests/unit/test_ss_calculator_engine.py index 5a82b8afb4e..af1c8b90d71 100644 --- a/policyengine_us/tests/unit/test_ss_calculator_engine.py +++ b/policyengine_us/tests/unit/test_ss_calculator_engine.py @@ -526,7 +526,7 @@ def test_survivor_prior_eligibility_requires_explicit_api_input(increase, no_pri for name in ("no_prior", "prior"): record = _survivor( ss_calculator_worker_id=name, - ss_calculator_entitlement_month="2020-11", + ss_calculator_entitlement_month="2020-08", ss_calculator_death_year=2020, ss_calculator_death_date="2020-08-12", ss_calculator_authoritative_year=2020, From 04c2b04848e93abff41c113b11433358924cd86c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 26 Oct 2026 18:11:33 -0700 Subject: [PATCH 16/16] Align joint COLA test with the current forecast --- policyengine_us/tests/unit/test_ss_calculator_engine.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/policyengine_us/tests/unit/test_ss_calculator_engine.py b/policyengine_us/tests/unit/test_ss_calculator_engine.py index af1c8b90d71..69e7cd1259d 100644 --- a/policyengine_us/tests/unit/test_ss_calculator_engine.py +++ b/policyengine_us/tests/unit/test_ss_calculator_engine.py @@ -383,11 +383,11 @@ def test_joint_cola_withholding_pp_change_and_payment_factors_apply_once(): np.testing.assert_array_equal( simulation.calculate("ss_calculated_payment", "2027-01"), [913, 880] ) - # Only the supplied 2027 decision withholds a COLA. January2028's 1.1% - # baseline plus .15 percentage points applies to both records; after the - # continuing .88 payment factor, the checks are924 and891 dollars. + # Only the supplied 2027 decision withholds a COLA. January2028's 2.5% + # baseline plus .15 percentage points applies to both records. Dime-rounded + # PIAs are 1064.9/1026.5; the continuing .88 factor gives 937/903 dollars. np.testing.assert_array_equal( - simulation.calculate("ss_calculated_payment", "2028-01"), [924, 891] + simulation.calculate("ss_calculated_payment", "2028-01"), [937, 903] )