diff --git a/Makefile b/Makefile index dbc821bb65b..69c9172f058 100644 --- a/Makefile +++ b/Makefile @@ -52,7 +52,7 @@ REST_SPM_TESTS := $(TESTS)/core/test_spm_policy_family.py \ # 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 core policy-parameters policy remaining-heavy remaining +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 \ @@ -69,6 +69,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. @@ -83,7 +92,8 @@ 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_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. With REST_REPORT_DIR set, each group writes its own @@ -308,6 +318,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/changelog.d/ss-household-calculator-4a1.added.md b/changelog.d/ss-household-calculator-4a1.added.md new file mode 100644 index 00000000000..9583628166e --- /dev/null +++ b/changelog.d/ss-household-calculator-4a1.added.md @@ -0,0 +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/_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 new file mode 100644 index 00000000000..adca67d9941 --- /dev/null +++ b/docs/usage/social-security-calculator.md @@ -0,0 +1,250 @@ +# Supplied-record Social Security calculator + +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 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 +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. 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 +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. 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). + +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. +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 pre-2026 deaths before any +initial eligibility. This requires both death before age 62 and the +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 +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 + +`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, 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. + +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. 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 +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. +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 +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..95986924cb5 --- /dev/null +++ b/docs/usage/social-security/RULINGS.md @@ -0,0 +1,32 @@ +# Restricted-survivor modeling ruling + +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 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 +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/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..804c8a15178 --- /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 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: + 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/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/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/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/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/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/code_health/test_rest_python_groups.py b/policyengine_us/tests/code_health/test_rest_python_groups.py index aa1ce8ab3e7..f4318cd3342 100644 --- a/policyengine_us/tests/code_health/test_rest_python_groups.py +++ b/policyengine_us/tests/code_health/test_rest_python_groups.py @@ -873,6 +873,21 @@ def test_spm_and_dataset_suites_run_once_in_separate_steps_with_reports(workflow assert uploads[0]["with"]["name"] != "rest-test-timings" +@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 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): """Locally the same groups run without GNU time, which macOS lacks.""" plain = dry_run("test-other-python-rest") 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..65c75edc7ac --- /dev/null +++ b/policyengine_us/tests/policy/baseline/gov/ssa/social_security/ss_calculated_benefit.yaml @@ -0,0 +1,184 @@ +- 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 + +- 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 + +- 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-08' + 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_differential.py b/policyengine_us/tests/unit/test_ss_calculator_differential.py new file mode 100644 index 00000000000..2014996c4ba --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_calculator_differential.py @@ -0,0 +1,226 @@ +"""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 + ] + + +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", + [ + _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): + reference = _reference_simulation(situation) + 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) + 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) + 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..69e7cd1259d --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_calculator_engine.py @@ -0,0 +1,562 @@ +"""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 each variant once to the wrapper's isolated runtime clone. + + 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) + return Simulation( + situation=situation, + tax_benefit_system=Simulation.default_tax_benefit_system_instance, + 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 + # 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 + # 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) + # 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(): + simulation = _simulation( + situation=_situation( + { + "worker": _record( + ss_calculator_source="aime", + ss_calculator_supplied_aime=5000, + ss_calculator_birth_date="1958-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] + ) + # 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"), [937, 903] + ) + + +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(**overrides): + record = _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_prior_disability_eligibility=0, + 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, + ) + record.update(overrides) + return record + + +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 + + +@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-08", + 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_calculator_parameters.py b/policyengine_us/tests/unit/test_ss_calculator_parameters.py new file mode 100644 index 00000000000..6d9ff107cf6 --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_calculator_parameters.py @@ -0,0 +1,279 @@ +"""Runtime parameter selection for the opt-in eligibility-year PIA service.""" + +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 ( + 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(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(data={}) + 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]), data={}), + ) + destination = destination.children[part] + return root + + +@pytest.fixture +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"): + 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.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] + + +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_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) + _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, "2032-01-01") + path, _ = formula_path_at(parameters, 2032, 2032) + assert ( + progressive_threshold(2032, path, bend_points=bend_points_at(parameters, 2032)) + == 3500 + ) + + +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) + _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} + + +@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_cola_schedule.py b/policyengine_us/tests/unit/test_ss_cola_schedule.py new file mode 100644 index 00000000000..7086c8b35b4 --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_cola_schedule.py @@ -0,0 +1,228 @@ +"""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 + 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" + 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_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) + + +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/tests/unit/test_ss_household_calculator.py b/policyengine_us/tests/unit/test_ss_household_calculator.py new file mode 100644 index 00000000000..bab54d08b51 --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_household_calculator.py @@ -0,0 +1,1225 @@ +"""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", + prior_disability_eligibility=False, + 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) + + +@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), + eligibility_year=2026, + entitlement_month="2026-01", + pia=D(800), + supplied_claiming_factor=D(1), + earnings_test_no_trigger=False, + ) + 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. + 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 + + +@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, + 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}, + 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 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(): + 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, + prior_disability_eligibility=True, + 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", + [ + ({"prior_disability_eligibility": True}, "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", + prior_disability_eligibility=True, + 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 row_for(result, "2025-12").payment_amount == 0 + assert result.entitlement_total == 9600 + assert result.payment_total == 8800 + + +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)) + + +@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, + prior_disability_eligibility=True, + 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 + + +@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/tests/unit/test_ss_pia_service.py b/policyengine_us/tests/unit/test_ss_pia_service.py new file mode 100644 index 00000000000..b0fbf791010 --- /dev/null +++ b/policyengine_us/tests/unit/test_ss_pia_service.py @@ -0,0 +1,349 @@ +"""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, + has_active_reform, + 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") + + +@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. + # 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_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): + 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/general.py b/policyengine_us/tools/general.py index 2f8254e327c..891bfdd10f9 100644 --- a/policyengine_us/tools/general.py +++ b/policyengine_us/tools/general.py @@ -53,7 +53,10 @@ 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 + 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 @@ -66,6 +69,7 @@ def earliest_input_year(simulation): if ( branch_name in visible_branches and period.unit != ETERNITY + and not variable.startswith(("ss_calculator_", "ss_calculated_")) and variable in variables and not variables[variable].is_neutralized ): 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/cola.py b/policyengine_us/tools/social_security/cola.py new file mode 100644 index 00000000000..174c34734ec --- /dev/null +++ b/policyengine_us/tools/social_security/cola.py @@ -0,0 +1,321 @@ +"""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: + # Reuse the canonical statutory history supplied by the benefit-lever + # route. Its authored event dates preserve irregular historical timing. + 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( + ( + 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 observation in observations: + year = int(observation.instant_str[:4]) + if year > through_year: + continue + # 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}" + 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) == 2 + else "unsupported_historical_rounding" + ) + kwargs = {} + if year == 1999: + correction = parameters.gov.ssa.social_security.cola( + observation.instant_str + ) + kwargs = { + "as_paid_rate": _decimal(correction.december_1999_as_paid_rate), + "correction_payment_month": str( + int(correction.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_parameter = parameters.gov.ssa.uprating + q3_years = { + int(observation.instant_str[:4]) + for observation in q3_parameter.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. + 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( + f"The frozen SSA Q3 path is missing payment year {min(missing_years)}" + ) + q3 = { + year: _decimal(q3_parameter(f"{year}-01-01")) + 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 diff --git a/policyengine_us/tools/social_security/engine.py b/policyengine_us/tools/social_security/engine.py new file mode 100644 index 00000000000..8c779c480b9 --- /dev/null +++ b/policyengine_us/tools/social_security/engine.py @@ -0,0 +1,309 @@ +"""Thin Person-variable adapter for the pure supplied-record calculator.""" + +from datetime import date +from decimal import Decimal + +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, + month_number, +) +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": + 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") + 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, + 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), + ) + 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 = {}, {}, {}, {} + 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 sorted(payment_years): + 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 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 + # 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 + 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 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: + # 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 sorted(payment_years): + 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, + immediate_earnings_test_payment=bool( + value("immediate_earnings_test_payment") + ), + earnings_test_settlement_months=settlement_months, + ) + 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 == "deferred_earnings_test_payment": + result[index] = float(annual.deferred_earnings_test_payment) + 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 + ) + 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 + 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..d4865fb6a54 --- /dev/null +++ b/policyengine_us/tools/social_security/household.py @@ -0,0 +1,771 @@ +"""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 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. +""" + +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 + 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 self.prior_disability_eligibility 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 + 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) +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 + 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): + 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, + immediate_earnings_test_payment=False, + earnings_test_settlement_months=None, + _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. + + 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 + ) + 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 + and not record.survivor.prior_disability_eligibility + ) + 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} + 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 + 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 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, + immediate_earnings_test_payment=immediate_earnings_test_payment, + _include_previous_check=False, + ) + old = earlier.ledger[-1] + 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) + 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, + # 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( + rows, + sum( + ( + r.payable_benefit + for r in rows + if r.entitlement_month.startswith(str(year)) + ), + Decimal(0), + ), + sum( + (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 + for r in rows + if r.entitlement_month.startswith(str(year)) + ), + Decimal(0), + ), + pia_interval, + inferred_interval, + tuple(settlements), + ) diff --git a/policyengine_us/tools/social_security/parameters.py b/policyengine_us/tools/social_security/parameters.py new file mode 100644 index 00000000000..82c31872883 --- /dev/null +++ b/policyengine_us/tools/social_security/parameters.py @@ -0,0 +1,134 @@ +"""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(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): + """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.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]) + + +def formula_path_at(parameters, eligibility_year, payment_year): + """Return ``(FormulaPath, recompute_mode)`` for one worker and payment year. + + 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 + 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") + 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(pia_node, selection_year) + s770 = bool( + _snapshot(parameters.gov.contrib.congress.s770.section_2, payment).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 = _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: + values["progressive_price_indexing_start_year"] = int( + progressive.start_year + ) + 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 = _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" + return FormulaPath(**values), mode diff --git a/policyengine_us/tools/social_security/pia.py b/policyengine_us/tools/social_security/pia.py new file mode 100644 index 00000000000..72e9d3a5348 --- /dev/null +++ b/policyengine_us/tools/social_security/pia.py @@ -0,0 +1,390 @@ +"""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 _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( + eligibility_year: int, + formula_path: FormulaPath, + *, + bend_points: tuple[Number, Number], +) -> Fraction: + 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 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( + 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 = _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() + 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( + _number(value, "bend-point multiplier") + for value in path.bend_point_multipliers + ) + bends = tuple(bp * multiplier for bp, multiplier in zip(bends, multipliers)) + if "factors" in features: + _, rates = _scale(baseline_bends, path.factor_values) + 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]) + 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 "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 "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" + ) + 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, + ) 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..85c11d308f5 --- /dev/null +++ b/policyengine_us/variables/gov/ssa/social_security/calculator/inputs.py @@ -0,0 +1,376 @@ +"""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_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 + 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_prior_disability_eligibility(Variable): + value_type = int + entity = Person + definition_period = ETERNITY + 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): + 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_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 + 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..c87878af211 --- /dev/null +++ b/policyengine_us/variables/gov/ssa/social_security/calculator/results.py @@ -0,0 +1,210 @@ +"""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, including partial earnings-test benefits awaiting settlement." + ) + 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, 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") + + +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_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, 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): + 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 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", + ) + + 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")