diff --git a/.github/workflows/modal-api.yml b/.github/workflows/modal-api.yml index e0de2dc..667914f 100644 --- a/.github/workflows/modal-api.yml +++ b/.github/workflows/modal-api.yml @@ -11,6 +11,7 @@ on: - aca_calc/** - src/aca_api/** - tests/test_api_explain.py + - tests/test_api_scenarios.py - tests/test_enhanced_ptc_reform.py - tests/test_modal_requirements.py - tests/test_smoke_test_api.py @@ -24,6 +25,7 @@ on: - aca_calc/** - src/aca_api/** - tests/test_api_explain.py + - tests/test_api_scenarios.py - tests/test_enhanced_ptc_reform.py - tests/test_modal_requirements.py - tests/test_smoke_test_api.py @@ -63,7 +65,7 @@ jobs: uv venv --python 3.11 uv pip install -r modal-requirements.txt - name: Run the API tests - run: .venv/bin/python -m pytest tests/test_api_explain.py tests/test_enhanced_ptc_reform.py tests/test_modal_requirements.py tests/test_smoke_test_api.py + run: .venv/bin/python -m pytest tests/test_api_explain.py tests/test_api_scenarios.py tests/test_enhanced_ptc_reform.py tests/test_modal_requirements.py tests/test_smoke_test_api.py deploy: name: Deploy and smoke-test diff --git a/aca_calc/calculations/household.py b/aca_calc/calculations/household.py index 6abf224..16950b2 100644 --- a/aca_calc/calculations/household.py +++ b/aca_calc/calculations/household.py @@ -34,7 +34,14 @@ def build_household_situation( "spm_units": {"your household": {"members": ["you"]}}, "tax_units": {"your tax unit": {"members": ["you"]}}, "households": { - "your household": {"members": ["you"], "state_name": {year: state}} + "your household": { + "members": ["you"], + # The credit measures income against the prior year's poverty + # guideline (aca_magi_fraction), so the state is set for that + # year too. Without it, Alaska and Hawaii households get the + # 48 states' lower guideline. + "state_name": {year - 1: state, year: state}, + } }, } diff --git a/aca_calc/calculations/reforms.py b/aca_calc/calculations/reforms.py index 945ba26..4a33932 100644 --- a/aca_calc/calculations/reforms.py +++ b/aca_calc/calculations/reforms.py @@ -14,32 +14,41 @@ ENHANCED_INITIAL = [0, 0, 0.02, 0.04, 0.06] ENHANCED_FINAL = [0, 0.02, 0.04, 0.06, 0.085] -ENHANCED_PERIOD = "2026-01-01.2100-12-31" +# H.R. 1834 extends the enhanced schedule for 2026 through 2028. +ENHANCED_PERIOD = "2026-01-01.2028-12-31" + + +def _enhanced_schedule() -> dict: + """The enhanced schedule as policyengine-us parameter overrides. + + The three lists are replaced together: the threshold list has one more + entry than the rate lists, and current law's lists have a 133% FPL + threshold the enhanced schedule doesn't. + """ + return { + "gov.aca.required_contribution_percentage.threshold": {ENHANCED_PERIOD: ENHANCED_THRESHOLDS}, + "gov.aca.required_contribution_percentage.initial": {ENHANCED_PERIOD: ENHANCED_INITIAL}, + "gov.aca.required_contribution_percentage.final": {ENHANCED_PERIOD: ENHANCED_FINAL}, + } + + +# gov.aca.ptc_income_eligibility's third bracket starts at 400% FPL; from 2026 +# it makes incomes there ineligible. +NO_INCOME_CAP = {"gov.aca.ptc_income_eligibility[2].amount": {ENHANCED_PERIOD: True}} def create_enhanced_ptc_reform(): - """Create reform extending enhanced PTCs (IRA extension) from 2026 on. + """H.R. 1834: extend the enhanced premium tax credits for 2026-2028. Restores the ARPA/IRA applicable-percentage schedule and removes the 400% FPL eligibility limit, so households above 400% FPL pay at most 8.5% of - income for the benchmark plan. - - The three schedule lists are replaced together: the threshold list has one - more entry than the rate lists, and the 2026 law's lists have a 133% FPL - threshold the enhanced schedule doesn't. + income for the benchmark plan. H.R. 1834 passed the House on January 8, + 2026; it has not been enacted. Returns: Reform: PolicyEngine reform object """ - return Reform.from_dict( - { - "gov.aca.required_contribution_percentage.threshold": {ENHANCED_PERIOD: ENHANCED_THRESHOLDS}, - "gov.aca.required_contribution_percentage.initial": {ENHANCED_PERIOD: ENHANCED_INITIAL}, - "gov.aca.required_contribution_percentage.final": {ENHANCED_PERIOD: ENHANCED_FINAL}, - "gov.aca.ptc_income_eligibility[2].amount": {ENHANCED_PERIOD: True}, - }, - country_id="us", - ) + return Reform.from_dict({**_enhanced_schedule(), **NO_INCOME_CAP}, country_id="us") def _contrib_reform(module: str, name: str): @@ -57,6 +66,9 @@ def _contrib_reform(module: str, name: str): def create_700fpl_reform(): """Create 700% FPL extension reform (Bipartisan Health Insurance Affordability Act). + Introduced by Reps. Dunn (R-FL) and Schneider (D-IL) on December 9, 2025; + not enacted. + This implements the proposed bill's schedule: - 200-250% FPL: 2% to 4% - 250-300% FPL: 4% to 6% diff --git a/changelog.d/aca-2027-backend.added.md b/changelog.d/aca-2027-backend.added.md new file mode 100644 index 0000000..cd189f9 --- /dev/null +++ b/changelog.d/aca-2027-backend.added.md @@ -0,0 +1 @@ +Model 2027 coverage in the calculator API (requests without a year still get 2026), with H.R. 1834, and return 2026 current law for the same household and incomes alongside 2027 when asked (show_prior_year). Report the benchmark premium at each income. Pin policyengine-us 2.115.0, which has the published 2027 premiums, and give the Modal function 4 GB. diff --git a/changelog.d/aca-2027-backend.fixed.md b/changelog.d/aca-2027-backend.fixed.md new file mode 100644 index 0000000..d86c02c --- /dev/null +++ b/changelog.d/aca-2027-backend.fixed.md @@ -0,0 +1 @@ +Draw the FPL lines from the prior year's poverty guideline, which the credit uses, and give Alaska and Hawaii households their own guideline for the credit instead of the 48 states'. diff --git a/modal-requirements.txt b/modal-requirements.txt index 18dcc10..fbe1410 100644 --- a/modal-requirements.txt +++ b/modal-requirements.txt @@ -2,8 +2,10 @@ # # Captured with `pip freeze` from the live aca-calc-api container on 2026-11-03, # minus the 14 packages that Modal's 2025.06 image builder installs at the same -# versions. Deploying from this file reproduces the calculator that has served -# since May 2026 (policyengine-us 1.691.3), so a redeploy changes only the code. +# versions. Since then policyengine-us has moved from 1.691.3 to 2.115.0 +# (2026-11-09), the first release with the published 2027 premiums +# (policyengine-us #10682), with the policyengine-core and spm-calculator +# versions it requires; every other pin is unchanged. # # To upgrade a package, change its pin here, run the tests against the new set, # and compare /api/calculate results before deploying. @@ -58,11 +60,8 @@ parso==0.8.7 pexpect==4.9.0 plotly==5.24.1 pluggy==1.6.0 -policyengine-core==3.26.4 -# PyPI no longer serves policyengine-us 1.691.3 (of the 1.691 series it keeps -# only 1.691.1), so this builds it from its release commit. The build matches -# the live container's installed files hash for hash. -policyengine-us @ https://github.com/PolicyEngine/policyengine-us/archive/2cb12a24dad22d85a82549f6d164b9d5fbadbe5e.tar.gz +policyengine-core==3.34.9 +policyengine-us==2.115.0 prompt_toolkit==3.0.52 psutil==6.1.1 ptyprocess==0.7.0 @@ -81,7 +80,7 @@ shellingham==1.5.4 six==1.17.0 sniffio==1.3.1 sortedcontainers==2.4.0 -spm-calculator==0.3.1 +spm-calculator==1.1.0 stack-data==0.6.3 standard-imghdr==3.13.0 starlette==1.0.0 diff --git a/modal_app.py b/modal_app.py index 4a52c5f..adfe96a 100644 --- a/modal_app.py +++ b/modal_app.py @@ -5,13 +5,21 @@ import modal -app = modal.App("aca-calc-api") +# The live app is aca-calc-api. A preview deploy sets ACA_API_APP_NAME, say +# aca-calc-api-preview, to run a branch's backend beside it with caches of its +# own; the image carries the name, so its containers open the same caches. +APP_NAME = os.environ.get("ACA_API_APP_NAME", "aca-calc-api") +CACHE_SUFFIX = APP_NAME.removeprefix("aca-calc-api") + +app = modal.App(APP_NAME) # Persistent cache for calculation results (7-day TTL handled in application) -calculation_cache = modal.Dict.from_name("aca-calc-cache", create_if_missing=True) +calculation_cache = modal.Dict.from_name(f"aca-calc-cache{CACHE_SUFFIX}", create_if_missing=True) # Persistent cache for AI explanations -explanation_cache = modal.Dict.from_name("aca-explain-cache", create_if_missing=True) +explanation_cache = modal.Dict.from_name( + f"aca-explain-cache{CACHE_SUFFIX}", create_if_missing=True +) # Exact package versions from the live container, so a deploy changes only this # repo's code. Read the notes in the file before changing a pin. @@ -25,7 +33,13 @@ .add_local_dir("src/aca_api", "/root/src/aca_api", copy=True) # The commit a CI deploy came from. The API reports it, so the smoke test # can tell this deploy's containers from the previous version's. - .env({"PYTHONPATH": "/root", "ACA_API_COMMIT": os.environ.get("ACA_API_COMMIT", "")}) + .env( + { + "PYTHONPATH": "/root", + "ACA_API_COMMIT": os.environ.get("ACA_API_COMMIT", ""), + "ACA_API_APP_NAME": APP_NAME, + } + ) ) @@ -33,7 +47,9 @@ image=image, secrets=[modal.Secret.from_name("anthropic-api-key")], timeout=300, - memory=2048, + # policyengine-us 2.x needs about 0.9 GB to load and 2.4-2.9 GB once a + # request has run its scenarios' reforms. + memory=4096, ) @modal.asgi_app() def fastapi_app(): diff --git a/scripts/smoke_test_api.py b/scripts/smoke_test_api.py index cd0956e..c5754a7 100644 --- a/scripts/smoke_test_api.py +++ b/scripts/smoke_test_api.py @@ -3,10 +3,11 @@ Usage: python scripts/smoke_test_api.py API_URL [--explain] [--commit SHA [--wait SECONDS]] Checks /api/health, then both calculator endpoints: /api/calculate-stream, -which the calculator page calls, and /api/calculate, its fallback. Both -requests set skip_cache, so the deployed code computes each answer instead of -returning one from the 7-day calculation cache, and the stream check confirms -that it did. With --explain it checks /api/health and then /api/explain +which the calculator page calls, and /api/calculate, its fallback, and then a +2027 calculation with 2026 alongside, as the calculator page asks. The +requests set skip_cache, so the deployed code computes +each answer instead of returning one from the 7-day calculation cache, and the +stream check confirms that it did. With --explain it checks /api/health and then /api/explain instead of the calculator: it requests a fixed household's AI narrative, which calls the Anthropic API unless the answer is already in the 7-day explanation cache. @@ -170,6 +171,20 @@ def check_calculate(base): check_result("/api/calculate", call(f"{base}/api/calculate", FRESH)) +def check_calculate_2027(base): + # Requests without a year get 2026; the calculator page asks for 2027, with + # 2026 current law for the same household alongside. The credit measures + # income against the prior year's poverty guideline. + result = call(f"{base}/api/calculate", {**FRESH, "year": 2027, "show_prior_year": True}) + assert result.get("year") == 2027, f"asked for 2027, got {result.get('year')}" + assert result.get("fpl_year") == 2026, ( + f"2027 credits use the 2026 guideline, got {result.get('fpl_year')}" + ) + assert max(result.get("ptc_prior_year") or [0]) > 0, "no 2026 credits came back" + assert (result.get("fpl_prior_year") or 0) > 0, "no 2026 guideline came back" + check_result("/api/calculate (2027)", result) + + def check_explain(base): # A fixed household, so after the first deploy the answer usually comes # from the explanation cache rather than a new Anthropic API call. @@ -234,7 +249,7 @@ def main(): if args.explain: checks = [check_health, check_explain] else: - checks = [check_health, check_calculate_stream, check_calculate] + checks = [check_health, check_calculate_stream, check_calculate, check_calculate_2027] for check in checks: from_this_deploy(check, base) diff --git a/src/aca_api/api.py b/src/aca_api/api.py index cbaa9da..c6b62c0 100644 --- a/src/aca_api/api.py +++ b/src/aca_api/api.py @@ -10,6 +10,7 @@ import os import time from concurrent.futures import ThreadPoolExecutor +from importlib.metadata import version import anthropic import numpy as np @@ -30,6 +31,19 @@ create_simplified_bracket_reform, ) +# The model version is part of every cache key, so a new pin never serves +# answers the previous version computed. +MODEL_VERSION = version("policyengine-us") + +# Each scenario: the request flag that turns it on, the response field for its +# credits, and the reform that models it. +SCENARIOS = [ + ("show_ira", "ptc_ira", create_enhanced_ptc_reform), + ("show_700fpl", "ptc_700fpl", create_700fpl_reform), + ("show_additional_bracket", "ptc_additional_bracket", create_additional_bracket_reform), + ("show_simplified_bracket", "ptc_simplified_bracket", create_simplified_bracket_reform), +] + # Local cache fallback for development (in-memory, lost on restart) _local_calculation_cache = TTLCache(maxsize=1000, ttl=86400) _local_explanation_cache = TTLCache(maxsize=500, ttl=604800) @@ -175,11 +189,96 @@ def get_cache_key(data: CalculateRequest) -> str: "show_700fpl": data.show_700fpl, "show_additional_bracket": data.show_additional_bracket, "show_simplified_bracket": data.show_simplified_bracket, + "show_prior_year": data.show_prior_year, + "year": data.year, + "model_version": MODEL_VERSION, } key_str = json.dumps(key_data, sort_keys=True) return hashlib.md5(key_str.encode()).hexdigest() +def household_situation(data: CalculateRequest) -> dict: + """The household, with an income axis, for the request's coverage year.""" + return build_household_situation( + age_head=data.age_head, + age_spouse=data.age_spouse, + dependent_ages=list(data.dependent_ages), + state=data.state, + county=data.county, + zip_code=data.zip_code, + year=data.year, + with_axes=True, + ) + + +def run_baseline(data: CalculateRequest, situation: dict) -> dict: + """Current law for the coverage year across the income axis.""" + year = data.year + sim = Simulation(situation=situation) + fpl = sim.calculate("tax_unit_fpg", period=year - 1) + slcsp = sim.calculate("slcsp", map_to="household", period=year) + return { + "income": sim.calculate("employment_income", map_to="household", period=year), + "ptc_baseline": sim.calculate("aca_ptc", map_to="household", period=year), + "medicaid": sim.calculate("medicaid", map_to="household", period=year), + "chip": sim.calculate("chip", map_to="household", period=year), + # The benchmark covers the members eligible for the credit at each + # income, so it is zero where none is; the scalar is its maximum. + "slcsp_by_income": slcsp, + "slcsp": float(np.max(slcsp)), + # The credit measures income against the prior year's guideline + # (aca_magi_fraction), so the page's FPL lines use that one too. + "fpl": float(fpl[len(fpl) // 2]), + } + + +def run_prior_year(data: CalculateRequest) -> dict: + """Current law a year before the coverage year, for the same household and + incomes (the income axis doesn't change with the year), or nothing if the + request doesn't ask for it.""" + if not data.show_prior_year: + return {} + prior = data.model_copy(update={"year": data.year - 1}) + sim = Simulation(situation=household_situation(prior)) + fpl = sim.calculate("tax_unit_fpg", period=prior.year - 1) + return { + "ptc_prior_year": convert_to_native( + sim.calculate("aca_ptc", map_to="household", period=prior.year) + ), + "slcsp_by_income_prior_year": convert_to_native( + sim.calculate("slcsp", map_to="household", period=prior.year) + ), + "fpl_prior_year": float(fpl[len(fpl) // 2]), + } + + +def run_scenario(data: CalculateRequest, situation: dict, flag: str, create_reform, zeros): + """A scenario's credits across the income axis, or zeros if it is off.""" + if not getattr(data, flag): + return zeros + sim = Simulation(situation=situation, reform=create_reform()) + return sim.calculate("aca_ptc", map_to="household", period=data.year) + + +def build_response( + data: CalculateRequest, baseline: dict, scenarios: dict, prior_year: dict +) -> CalculateResponse: + return CalculateResponse( + income=convert_to_native(baseline["income"]), + ptc_baseline=convert_to_native(baseline["ptc_baseline"]), + **{field: convert_to_native(values) for field, values in scenarios.items()}, + year=data.year, + fpl=baseline["fpl"], + fpl_year=data.year - 1, + slcsp=baseline["slcsp"], + slcsp_by_income=convert_to_native(baseline["slcsp_by_income"]), + medicaid=convert_to_native(baseline["medicaid"]), + chip=convert_to_native(baseline["chip"]), + model_version=MODEL_VERSION, + **prior_year, + ) + + @app.post("/api/calculate", response_model=CalculateResponse) async def calculate_ptc(data: CalculateRequest): """Calculate premium tax credits across income range. @@ -194,100 +293,18 @@ async def calculate_ptc(data: CalculateRequest): return cached try: - # Build household situation with income axis - situation = build_household_situation( - age_head=data.age_head, - age_spouse=data.age_spouse, - dependent_ages=list(data.dependent_ages), - state=data.state, - county=data.county, - zip_code=data.zip_code, - year=2026, - with_axes=True, - ) - - # Run baseline simulation - sim_baseline = Simulation(situation=situation) - income = sim_baseline.calculate( - "employment_income", map_to="household", period=2026 - ) - ptc_baseline = sim_baseline.calculate( - "aca_ptc", map_to="household", period=2026 - ) - medicaid = sim_baseline.calculate( - "medicaid", map_to="household", period=2026 - ) - chip = sim_baseline.calculate( - "chip", map_to="household", period=2026 - ) - slcsp_array = sim_baseline.calculate( - "slcsp", map_to="household", period=2026 - ) - fpl_array = sim_baseline.calculate("tax_unit_fpg", period=2026) - - # Get scalar values - slcsp = float(np.max(slcsp_array)) - fpl = float(fpl_array[len(fpl_array) // 2]) - - # Run reform simulations in parallel - def run_ira_simulation(): - if not data.show_ira: - return np.zeros_like(ptc_baseline) - reform_ira = create_enhanced_ptc_reform() - sim_ira = Simulation(situation=situation, reform=reform_ira) - return sim_ira.calculate("aca_ptc", map_to="household", period=2026) - - def run_700fpl_simulation(): - if not data.show_700fpl: - return np.zeros_like(ptc_baseline) - reform_700fpl = create_700fpl_reform() - if not reform_700fpl: - return np.zeros_like(ptc_baseline) - sim_700fpl = Simulation(situation=situation, reform=reform_700fpl) - return sim_700fpl.calculate("aca_ptc", map_to="household", period=2026) - - def run_additional_bracket_simulation(): - if not data.show_additional_bracket: - return np.zeros_like(ptc_baseline) - reform = create_additional_bracket_reform() - if not reform: - return np.zeros_like(ptc_baseline) - sim = Simulation(situation=situation, reform=reform) - return sim.calculate("aca_ptc", map_to="household", period=2026) - - def run_simplified_bracket_simulation(): - if not data.show_simplified_bracket: - return np.zeros_like(ptc_baseline) - reform = create_simplified_bracket_reform() - if not reform: - return np.zeros_like(ptc_baseline) - sim = Simulation(situation=situation, reform=reform) - return sim.calculate("aca_ptc", map_to="household", period=2026) - - # Submit all simulations to run in parallel - ira_future = simulation_executor.submit(run_ira_simulation) - fpl700_future = simulation_executor.submit(run_700fpl_simulation) - additional_bracket_future = simulation_executor.submit(run_additional_bracket_simulation) - simplified_bracket_future = simulation_executor.submit(run_simplified_bracket_simulation) - - # Wait for all to complete - ptc_ira = ira_future.result() - ptc_700fpl = fpl700_future.result() - ptc_additional_bracket = additional_bracket_future.result() - ptc_simplified_bracket = simplified_bracket_future.result() - - response = CalculateResponse( - income=convert_to_native(income), - ptc_baseline=convert_to_native(ptc_baseline), - ptc_ira=convert_to_native(ptc_ira), - ptc_700fpl=convert_to_native(ptc_700fpl), - ptc_additional_bracket=convert_to_native(ptc_additional_bracket), - ptc_simplified_bracket=convert_to_native(ptc_simplified_bracket), - fpl=fpl, - slcsp=slcsp, - medicaid=convert_to_native(medicaid), - chip=convert_to_native(chip), - ) + situation = household_situation(data) + prior_year = simulation_executor.submit(run_prior_year, data) + baseline = run_baseline(data, situation) + + # Run the selected scenarios in parallel + zeros = np.zeros_like(baseline["ptc_baseline"]) + futures = { + field: simulation_executor.submit(run_scenario, data, situation, flag, create, zeros) + for flag, field, create in SCENARIOS + } + scenarios = {field: future.result() for field, future in futures.items()} + response = build_response(data, baseline, scenarios, prior_year.result()) # Cache the result (persistent + local) if not data.skip_cache: @@ -323,107 +340,37 @@ async def generate(): yield f"data: {json.dumps({'step': 'setup', 'progress': 10, 'message': 'Setting up household...'})}\n\n" await asyncio.sleep(0) # Allow event to be sent - situation = build_household_situation( - age_head=data.age_head, - age_spouse=data.age_spouse, - dependent_ages=list(data.dependent_ages), - state=data.state, - county=data.county, - zip_code=data.zip_code, - year=2026, - with_axes=True, - ) + situation = household_situation(data) + loop = asyncio.get_event_loop() + prior_year = loop.run_in_executor(simulation_executor, run_prior_year, data) - # Step 2: Run baseline simulation - yield f"data: {json.dumps({'step': 'baseline', 'progress': 25, 'message': 'Calculating baseline (2026)...'})}\n\n" + # Step 2: Run the current-law simulation + message = f"Calculating current law ({data.year})..." + yield f"data: {json.dumps({'step': 'baseline', 'progress': 25, 'message': message})}\n\n" await asyncio.sleep(0) - sim_baseline = Simulation(situation=situation) - income = sim_baseline.calculate( - "employment_income", map_to="household", period=2026 - ) - ptc_baseline = sim_baseline.calculate( - "aca_ptc", map_to="household", period=2026 - ) - medicaid = sim_baseline.calculate( - "medicaid", map_to="household", period=2026 - ) - chip = sim_baseline.calculate( - "chip", map_to="household", period=2026 - ) - slcsp_array = sim_baseline.calculate( - "slcsp", map_to="household", period=2026 - ) - fpl_array = sim_baseline.calculate("tax_unit_fpg", period=2026) + baseline = run_baseline(data, situation) - slcsp = float(np.max(slcsp_array)) - fpl = float(fpl_array[len(fpl_array) // 2]) - - # Step 3: Run reform simulations in parallel + # Step 3: Run the selected scenarios in parallel yield f"data: {json.dumps({'step': 'reforms', 'progress': 50, 'message': 'Calculating policy reforms...'})}\n\n" await asyncio.sleep(0) - def run_ira_simulation(): - if not data.show_ira: - return np.zeros_like(ptc_baseline) - reform_ira = create_enhanced_ptc_reform() - sim_ira = Simulation(situation=situation, reform=reform_ira) - return sim_ira.calculate("aca_ptc", map_to="household", period=2026) - - def run_700fpl_simulation(): - if not data.show_700fpl: - return np.zeros_like(ptc_baseline) - reform_700fpl = create_700fpl_reform() - if not reform_700fpl: - return np.zeros_like(ptc_baseline) - sim_700fpl = Simulation(situation=situation, reform=reform_700fpl) - return sim_700fpl.calculate("aca_ptc", map_to="household", period=2026) - - def run_additional_bracket_simulation(): - if not data.show_additional_bracket: - return np.zeros_like(ptc_baseline) - reform = create_additional_bracket_reform() - if not reform: - return np.zeros_like(ptc_baseline) - sim = Simulation(situation=situation, reform=reform) - return sim.calculate("aca_ptc", map_to="household", period=2026) - - def run_simplified_bracket_simulation(): - if not data.show_simplified_bracket: - return np.zeros_like(ptc_baseline) - reform = create_simplified_bracket_reform() - if not reform: - return np.zeros_like(ptc_baseline) - sim = Simulation(situation=situation, reform=reform) - return sim.calculate("aca_ptc", map_to="household", period=2026) - - # Run all reform simulations in parallel - loop = asyncio.get_event_loop() - ira_future = loop.run_in_executor(simulation_executor, run_ira_simulation) - fpl700_future = loop.run_in_executor(simulation_executor, run_700fpl_simulation) - additional_bracket_future = loop.run_in_executor(simulation_executor, run_additional_bracket_simulation) - simplified_bracket_future = loop.run_in_executor(simulation_executor, run_simplified_bracket_simulation) - - ptc_ira, ptc_700fpl, ptc_additional_bracket, ptc_simplified_bracket = await asyncio.gather( - ira_future, fpl700_future, additional_bracket_future, simplified_bracket_future + zeros = np.zeros_like(baseline["ptc_baseline"]) + results = await asyncio.gather( + *( + loop.run_in_executor( + simulation_executor, run_scenario, data, situation, flag, create, zeros + ) + for flag, _, create in SCENARIOS + ) ) + scenarios = {field: result for (_, field, _), result in zip(SCENARIOS, results)} # Step 4: Complete yield f"data: {json.dumps({'step': 'finalizing', 'progress': 90, 'message': 'Finalizing results...'})}\n\n" await asyncio.sleep(0) - response = CalculateResponse( - income=convert_to_native(income), - ptc_baseline=convert_to_native(ptc_baseline), - ptc_ira=convert_to_native(ptc_ira), - ptc_700fpl=convert_to_native(ptc_700fpl), - ptc_additional_bracket=convert_to_native(ptc_additional_bracket), - ptc_simplified_bracket=convert_to_native(ptc_simplified_bracket), - fpl=fpl, - slcsp=slcsp, - medicaid=convert_to_native(medicaid), - chip=convert_to_native(chip), - ) + response = build_response(data, baseline, scenarios, await prior_year) # Cache the result (persistent + local) if not data.skip_cache: @@ -496,17 +443,21 @@ def build_explain_prompt(data: ExplainRequest) -> str: expansion_note = "This is a non-expansion state." if not data.is_expansion_state else "This is an expansion state." chip_line = f"- CHIP for children: {data.chip_threshold_pct}% FPL (${chip_income:,.0f})" if has_children and data.chip_threshold_pct > 0 else "" + year = data.year + # Build reform data section based on which reforms are selected - reform_data_lines = [f"- Baseline PTC (2026 if IRA expires): ${data.ptc_baseline_at_sample:,.0f}/year (${data.ptc_baseline_at_sample/12:,.0f}/month)"] + reform_data_lines = [f"- Current-law PTC ({year}): ${data.ptc_baseline_at_sample:,.0f}/year (${data.ptc_baseline_at_sample/12:,.0f}/month)"] if data.show_ira: - reform_data_lines.append(f"- IRA Extension PTC: ${data.ptc_ira_at_sample:,.0f}/year (${data.ptc_ira_at_sample/12:,.0f}/month)") + reform_data_lines.append(f"- H.R. 1834 PTC: ${data.ptc_ira_at_sample:,.0f}/year (${data.ptc_ira_at_sample/12:,.0f}/month)") if data.show_700fpl: reform_data_lines.append(f"- 700% FPL Bill PTC: ${data.ptc_700fpl_at_sample:,.0f}/year (${data.ptc_700fpl_at_sample/12:,.0f}/month)") if data.show_additional_bracket: reform_data_lines.append(f"- Additional Bracket PTC: ${data.ptc_additional_bracket_at_sample:,.0f}/year (${data.ptc_additional_bracket_at_sample/12:,.0f}/month)") if data.show_simplified_bracket: reform_data_lines.append(f"- Simplified Bracket PTC: ${data.ptc_simplified_bracket_at_sample:,.0f}/year (${data.ptc_simplified_bracket_at_sample/12:,.0f}/month)") + if data.show_prior_year: + reform_data_lines.insert(0, f"- Current-law PTC ({year - 1}): ${data.ptc_prior_year_at_sample:,.0f}/year (${data.ptc_prior_year_at_sample/12:,.0f}/month)") reform_data_text = "\n".join(reform_data_lines) @@ -514,17 +465,17 @@ def build_explain_prompt(data: ExplainRequest) -> str: reform_descriptions = [] if data.show_ira: reform_descriptions.append(""" -IRA EXTENSION (show_ira=True): -- Extends the Inflation Reduction Act's enhanced premium tax credits -- Sets an 8.5% income cap on health insurance contributions for those above 400% FPL -- Removes the income eligibility cliff at 400% FPL -- Anyone above 400% FPL pays at most 8.5% of income toward benchmark plan""") +H.R. 1834 (show_ira=True): +- Would extend the enhanced premium tax credits of the American Rescue Plan Act and the Inflation Reduction Act, which expired after 2025, for 2026 through 2028 +- Required contributions run from 0% of income up to 150% FPL to 8.5% at 400% FPL and above +- Removes the income eligibility limit at 400% FPL +- Passed the House on January 8, 2026; it has not been enacted""") if data.show_700fpl: reform_descriptions.append(""" 700% FPL BILL (show_700fpl=True): -- Bipartisan Health Insurance Affordability Act proposal -- Extends subsidies up to 700% FPL (vs current 400% FPL cliff) +- Bipartisan Health Insurance Affordability Act, introduced by Reps. Dunn and Schneider on December 9, 2025; it has not been enacted +- Extends subsidies up to 700% FPL (vs the current 400% FPL limit) - Contribution rates: 2-4% at 200-250% FPL, 4-6% at 250-300%, 6-8.5% at 300-400%, 8.5% at 400-600%, 8.5-9.25% at 600-700% - Eligibility ends at 700% FPL""") @@ -534,8 +485,8 @@ def build_explain_prompt(data: ExplainRequest) -> str: - CRFB proposal: "Extend Subsidies Below 300% of Poverty, Extend Phase Up Above" - Adds a new bracket above 400% FPL with a linear phase-out - Contribution percentage increases by ~4 percentage points per 100% FPL above transition threshold -- Creates a more gradual cliff than current law while reducing costs vs full IRA extension -- Estimated cost: ~$280 billion through 2035 (vs $350B for full IRA extension)""") +- Creates a more gradual cliff than current law +- CRFB estimates it would cost about $280 billion through 2035, against $350 billion for the full IRA extension""") if data.show_simplified_bracket: reform_descriptions.append(""" @@ -543,8 +494,8 @@ def build_explain_prompt(data: ExplainRequest) -> str: - CRFB proposal: sets subsidies "about halfway between base and enhanced rate" - Single linear phase-out starting at 100% FPL - Contribution percentage increases by 4 percentage points per 100% FPL from the start -- Simplest structure but most aggressive phase-out -- Estimated cost: ~$175 billion through 2035""") +- Simplest structure, with the fastest phase-out of the options +- CRFB estimates it would cost about $175 billion through 2035""") reform_descriptions_text = "\n".join(reform_descriptions) if reform_descriptions else "No reforms selected." @@ -554,7 +505,14 @@ def build_explain_prompt(data: ExplainRequest) -> str: sections_json = [] # Section 1: Always intro - sections_spec.append(f'{section_num}. id: "intro", chartState: "all_programs" - Introduce this household and their location. State the SLCSP cost of ${data.slcsp:,.0f}/year.') + prior_year_note = ( + f" Compare it with the {year - 1} benchmark of ${data.slcsp_prior_year:,.0f}/year, and" + f" say how the household's current-law credit at ${data.sample_income:,.0f} changes" + f" between {year - 1} and {year}." + if data.show_prior_year + else "" + ) + sections_spec.append(f'{section_num}. id: "intro", chartState: "all_programs" - Introduce this household and their location. State the SLCSP cost of ${data.slcsp:,.0f}/year.{prior_year_note}') sections_json.append('{{"id": "intro", "title": "...", "content": "...", "chartState": "all_programs"}}') section_num += 1 @@ -568,39 +526,39 @@ def build_explain_prompt(data: ExplainRequest) -> str: sections_spec.append(f'{section_num}. id: "chip", chartState: "chip_focus" - Explain CHIP coverage for children up to {data.chip_threshold_pct}% FPL (${chip_income:,.0f}).') sections_json.append('{{"id": "chip", "title": "...", "content": "...", "chartState": "chip_focus"}}') else: - sections_spec.append(f'{section_num}. id: "cliff", chartState: "cliff_focus" - Explain the 400% FPL cliff at ${data.fpl_400_income:,.0f} where baseline subsidies end. Above this income, there are no premium tax credits under current law (2026).') + sections_spec.append(f'{section_num}. id: "cliff", chartState: "cliff_focus" - Explain the 400% FPL cliff at ${data.fpl_400_income:,.0f} where current-law subsidies end. Above this income, there are no premium tax credits under current law ({year}).') sections_json.append('{{"id": "cliff", "title": "...", "content": "...", "chartState": "cliff_focus"}}') section_num += 1 # Add a section for each selected reform if data.show_ira: diff = data.ptc_ira_at_sample - data.ptc_baseline_at_sample - sections_spec.append(f'{section_num}. id: "ira", chartState: "ira_impact" - Explain the IRA Extension reform. At ${data.sample_income:,.0f} income, IRA provides ${data.ptc_ira_at_sample:,.0f}/year vs baseline ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). Explain the 8.5% cap and removal of the 400% FPL cliff.') + sections_spec.append(f'{section_num}. id: "ira", chartState: "ira_impact" - Explain H.R. 1834, which would extend the enhanced credits. At ${data.sample_income:,.0f} income, it provides ${data.ptc_ira_at_sample:,.0f}/year vs current law ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). Explain the 8.5% cap and removal of the 400% FPL limit.') sections_json.append('{{"id": "ira", "title": "...", "content": "...", "chartState": "ira_impact"}}') section_num += 1 if data.show_700fpl: diff = data.ptc_700fpl_at_sample - data.ptc_baseline_at_sample - sections_spec.append(f'{section_num}. id: "fpl700", chartState: "fpl700_focus" - Explain the 700% FPL Bill (Bipartisan Health Insurance Affordability Act). At ${data.sample_income:,.0f} income, it provides ${data.ptc_700fpl_at_sample:,.0f}/year vs baseline ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). Explain the graduated brackets up to 700% FPL.') + sections_spec.append(f'{section_num}. id: "fpl700", chartState: "fpl700_focus" - Explain the 700% FPL Bill (Bipartisan Health Insurance Affordability Act). At ${data.sample_income:,.0f} income, it provides ${data.ptc_700fpl_at_sample:,.0f}/year vs current law ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). Explain the graduated brackets up to 700% FPL.') sections_json.append('{{"id": "fpl700", "title": "...", "content": "...", "chartState": "fpl700_focus"}}') section_num += 1 if data.show_additional_bracket: diff = data.ptc_additional_bracket_at_sample - data.ptc_baseline_at_sample - sections_spec.append(f'{section_num}. id: "additional", chartState: "additional_focus" - Explain the Additional Bracket reform (CRFB proposal). At ${data.sample_income:,.0f} income, it provides ${data.ptc_additional_bracket_at_sample:,.0f}/year vs baseline ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). This proposal extends subsidies below 300% FPL while adding a linear phase-up above, costing ~$280B vs $350B for full IRA extension.') + sections_spec.append(f'{section_num}. id: "additional", chartState: "additional_focus" - Explain the Additional Bracket reform (CRFB proposal). At ${data.sample_income:,.0f} income, it provides ${data.ptc_additional_bracket_at_sample:,.0f}/year vs current law ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). This proposal extends subsidies below 300% FPL while adding a linear phase-up above; CRFB estimates it would cost about $280B, against $350B for the full IRA extension.') sections_json.append('{{"id": "additional", "title": "...", "content": "...", "chartState": "additional_focus"}}') section_num += 1 if data.show_simplified_bracket: diff = data.ptc_simplified_bracket_at_sample - data.ptc_baseline_at_sample - sections_spec.append(f'{section_num}. id: "simplified", chartState: "simplified_focus" - Explain the Simplified Bracket reform (CRFB proposal). At ${data.sample_income:,.0f} income, it provides ${data.ptc_simplified_bracket_at_sample:,.0f}/year vs baseline ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). This proposal uses a single linear phase-out from 100% FPL, setting subsidies about halfway between baseline and enhanced rates, costing ~$175B.') + sections_spec.append(f'{section_num}. id: "simplified", chartState: "simplified_focus" - Explain the Simplified Bracket reform (CRFB proposal). At ${data.sample_income:,.0f} income, it provides ${data.ptc_simplified_bracket_at_sample:,.0f}/year vs current law ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). This proposal uses a single linear phase-out from 100% FPL, setting subsidies about halfway between current-law and enhanced rates; CRFB estimates it would cost about $175B.') sections_json.append('{{"id": "simplified", "title": "...", "content": "...", "chartState": "simplified_focus"}}') section_num += 1 # Final comparison section (always included) selected_reforms = [] if data.show_ira: - selected_reforms.append("IRA Extension") + selected_reforms.append("H.R. 1834") if data.show_700fpl: selected_reforms.append("700% FPL Bill") if data.show_additional_bracket: @@ -610,9 +568,15 @@ def build_explain_prompt(data: ExplainRequest) -> str: if len(selected_reforms) > 1: reforms_list = ", ".join(selected_reforms) - sections_spec.append(f'{section_num}. id: "comparison", chartState: "both_reforms" - Compare all selected reforms: baseline vs {reforms_list}. Use the exact PTC values provided for ${data.sample_income:,.0f} income. Summarize which provides the most/least subsidy for this household.') + sections_spec.append(f'{section_num}. id: "comparison", chartState: "both_reforms" - Compare all selected reforms: current law vs {reforms_list}. Use the exact PTC values provided for ${data.sample_income:,.0f} income. Summarize which provides the most/least subsidy for this household.') sections_json.append('{{"id": "comparison", "title": "...", "content": "...", "chartState": "both_reforms"}}') + prior_year_benchmark = ( + f"\n- Annual benchmark plan (SLCSP) in {year - 1}: ${data.slcsp_prior_year:,.0f}" + f" (${data.slcsp_prior_year/12:,.0f}/month)" + if data.show_prior_year + else "" + ) sections_spec_text = "\n\n".join(sections_spec) sections_json_text = ",\n ".join(sections_json) total_sections = len(sections_json) @@ -624,6 +588,7 @@ def build_explain_prompt(data: ExplainRequest) -> str: - Do NOT use value-laden words like "unfortunately", "thankfully", "crucial", "vital", "struggle", etc. - Simply describe what the policies are and how they affect this household's numbers. - Use exact dollar amounts and percentages provided - do not round or approximate. +- Every reform below is a proposal, not law. Say so, and describe {year} current law as the law in effect. {"- CRITICAL: This household has NO children. Do NOT mention CHIP at all." if not has_children else ""} HOUSEHOLD DETAILS: @@ -638,10 +603,11 @@ def build_explain_prompt(data: ExplainRequest) -> str: - Medicaid expansion state: {"Yes" if data.is_expansion_state else "No"} KEY FINANCIAL DATA: -- Federal Poverty Level (FPL) for this household: ${data.fpl:,.0f} -- 400% FPL (baseline subsidy cliff): ${data.fpl_400_income:,.0f} +- Coverage year: {year} +- Federal Poverty Level (FPL) for this household: ${data.fpl:,.0f} (the {year - 1} poverty guideline, which {year} premium tax credits use) +- 400% FPL (current-law subsidy limit): ${data.fpl_400_income:,.0f} - 700% FPL: ${data.fpl_700_income:,.0f} -- Annual benchmark plan (SLCSP): ${data.slcsp:,.0f} (${data.slcsp/12:,.0f}/month) +- Annual benchmark plan (SLCSP): ${data.slcsp:,.0f} (${data.slcsp/12:,.0f}/month){prior_year_benchmark} SELECTED REFORMS AND THEIR DETAILS: {reform_descriptions_text} @@ -685,6 +651,10 @@ def get_explain_cache_key(data: ExplainRequest) -> str: "show_700fpl": data.show_700fpl, "show_additional_bracket": data.show_additional_bracket, "show_simplified_bracket": data.show_simplified_bracket, + "show_prior_year": data.show_prior_year, + "slcsp_prior_year": round(data.slcsp_prior_year, 0), + "year": data.year, + "model_version": MODEL_VERSION, } key_str = json.dumps(key_data, sort_keys=True) return hashlib.md5(key_str.encode()).hexdigest() diff --git a/src/aca_api/models.py b/src/aca_api/models.py index 4999167..b835a7c 100644 --- a/src/aca_api/models.py +++ b/src/aca_api/models.py @@ -1,6 +1,17 @@ """Pydantic models for ACA Calculator API.""" -from pydantic import BaseModel, Field, field_validator +from pydantic import BaseModel, Field, field_validator, model_validator + +# Coverage years the calculator models. Requests without a year get 2026, so +# a page that predates the year setting keeps its answers. +YEARS = (2026, 2027) +DEFAULT_YEAR = 2026 + + +def check_year(year: int) -> int: + if year not in YEARS: + raise ValueError(f"year must be one of {', '.join(map(str, YEARS))}") + return year class CalculateRequest(BaseModel): @@ -18,9 +29,14 @@ class CalculateRequest(BaseModel): zip_code: str | None = Field( default=None, description="ZIP code (required for LA County)" ) - show_ira: bool = Field(default=True, description="Calculate IRA extension scenario") + year: int = Field(default=DEFAULT_YEAR, description="Coverage year (2026 or 2027)") + show_ira: bool = Field( + default=True, + description="Calculate H.R. 1834, the enhanced credits extended (the IRA extension)", + ) show_700fpl: bool = Field( - default=False, description="Calculate 700% FPL bill scenario" + default=False, + description="Calculate the Bipartisan Health Insurance Affordability Act (700% FPL bill)", ) show_additional_bracket: bool = Field( default=False, description="Calculate additional bracket reform scenario" @@ -28,11 +44,32 @@ class CalculateRequest(BaseModel): show_simplified_bracket: bool = Field( default=False, description="Calculate simplified bracket reform scenario" ) + show_prior_year: bool = Field( + default=False, + description=( + "Also calculate current law for the year before the coverage year, for " + "the same household and incomes (2027 requests only)" + ), + ) skip_cache: bool = Field( default=False, description="Compute a new answer without reading or writing the cache", ) + @field_validator("year") + @classmethod + def validate_year(cls, v): + return check_year(v) + + @model_validator(mode="after") + def validate_prior_year(self): + if self.show_prior_year and self.year - 1 not in YEARS: + raise ValueError( + f"show_prior_year needs a coverage year after {YEARS[0]}; " + f"the calculator doesn't model {self.year - 1}" + ) + return self + @field_validator("dependent_ages") @classmethod def validate_dependent_ages(cls, v): @@ -63,9 +100,9 @@ def validate_state(cls, v): class CalculateResponse(BaseModel): """Response model for PTC calculation.""" - income: list[float] = Field(description="Income values (10,001 points)") - ptc_baseline: list[float] = Field(description="PTC under baseline (2026 law)") - ptc_ira: list[float] = Field(description="PTC under IRA extension") + income: list[float] = Field(description="Income values (1,001 points)") + ptc_baseline: list[float] = Field(description="PTC under current law for the year") + ptc_ira: list[float] = Field(description="PTC under H.R. 1834 (the IRA extension)") ptc_700fpl: list[float] = Field(description="PTC under 700% FPL bill") ptc_additional_bracket: list[float] = Field( default_factory=list, description="PTC under additional bracket reform" @@ -73,10 +110,35 @@ class CalculateResponse(BaseModel): ptc_simplified_bracket: list[float] = Field( default_factory=list, description="PTC under simplified bracket reform" ) - fpl: float = Field(description="Federal Poverty Level for household size") + year: int = Field(default=DEFAULT_YEAR, description="Coverage year") + fpl: float = Field( + description=( + "Poverty guideline for the household's size that the credit uses: " + "the one for the year before the coverage year" + ) + ) + fpl_year: int | None = Field(default=None, description="The guideline's year") + model_version: str = Field(default="", description="policyengine-us version") slcsp: float = Field(description="Second-lowest cost silver plan (annual)") + slcsp_by_income: list[float] = Field( + default_factory=list, + description=( + "Annual benchmark premium for the members eligible for the credit at " + "each income, zero where none is" + ), + ) medicaid: list[float] = Field(description="Medicaid value by income") chip: list[float] = Field(description="CHIP value by income") + # With show_prior_year: current law a year before the coverage year. + ptc_prior_year: list[float] | None = Field( + default=None, description="PTC under current law for the year before" + ) + slcsp_by_income_prior_year: list[float] | None = Field( + default=None, description="slcsp_by_income for the year before" + ) + fpl_prior_year: float | None = Field( + default=None, description="The guideline the year before's credit uses" + ) class ScrollySection(BaseModel): @@ -85,7 +147,13 @@ class ScrollySection(BaseModel): id: str = Field(description="Unique section identifier") title: str = Field(description="Section title") content: str = Field(description="Markdown content for section") - chartState: str = Field(description="Chart state: all_programs, medicaid_focus, chip_focus, cliff_focus, ira_impact, both_reforms") + chartState: str = Field( + description=( + "Chart state: all_programs, medicaid_focus, chip_focus, cliff_focus, " + "ira_impact, fpl700_focus, additional_focus, simplified_focus or " + "both_reforms" + ) + ) class ExplainRequest(BaseModel): @@ -97,6 +165,7 @@ class ExplainRequest(BaseModel): dependent_ages: list[int] = Field(default_factory=list, description="Ages of dependents") state: str = Field(description="Two-letter state code") county: str = Field(description="County name") + year: int = Field(default=DEFAULT_YEAR, description="Coverage year (2026 or 2027)") is_expansion_state: bool = Field(description="Whether state expanded Medicaid") # Calculated values @@ -115,6 +184,7 @@ class ExplainRequest(BaseModel): show_700fpl: bool = Field(default=True, description="Whether 700% FPL bill is selected") show_additional_bracket: bool = Field(default=False, description="Whether additional bracket is selected") show_simplified_bracket: bool = Field(default=False, description="Whether simplified bracket is selected") + show_prior_year: bool = Field(default=False, description="Whether to compare with current law a year earlier") # Key data points for narrative sample_income: float = Field(description="Sample income to analyze") @@ -123,6 +193,13 @@ class ExplainRequest(BaseModel): ptc_700fpl_at_sample: float = Field(default=0, description="700% FPL PTC at sample income") ptc_additional_bracket_at_sample: float = Field(default=0, description="Additional bracket PTC at sample income") ptc_simplified_bracket_at_sample: float = Field(default=0, description="Simplified bracket PTC at sample income") + slcsp_prior_year: float = Field(default=0, description="Annual SLCSP cost a year earlier") + ptc_prior_year_at_sample: float = Field(default=0, description="Current-law PTC a year earlier at sample income") + + @field_validator("year") + @classmethod + def validate_year(cls, v): + return check_year(v) class ExplainResponse(BaseModel): diff --git a/tests/test_api_scenarios.py b/tests/test_api_scenarios.py new file mode 100644 index 0000000..d965c19 --- /dev/null +++ b/tests/test_api_scenarios.py @@ -0,0 +1,156 @@ +"""The calculator API for 2026 and 2027 coverage, 2026 alongside 2027, and the +extension scenarios. + +A single 60-year-old in Travis County, Texas: Texas didn't expand Medicaid, so +the credit starts at 100% FPL, and at 60 the benchmark premium is above 8.5% +of income well past 400% FPL, so the scenarios' differences there show. +""" + +import numpy as np +import pytest +from policyengine_us import Simulation +from pydantic import ValidationError + +TestClient = pytest.importorskip( + "fastapi.testclient", + reason="API tests require FastAPI: run uv run --with fastapi pytest", +).TestClient + +from aca_calc.calculations.household import build_household_situation +from src.aca_api import api +from src.aca_api.models import CalculateRequest + +HOUSEHOLD = {"age_head": 60, "state": "TX", "county": "Travis County", "skip_cache": True} +ALL_SCENARIOS = { + "show_ira": True, + "show_700fpl": True, + "show_additional_bracket": True, + "show_simplified_bracket": True, +} +# Single-person poverty guidelines for the 48 states and Alaska (HHS). +GUIDELINE_2025 = 15_650 +GUIDELINE_2026 = 15_960 +ALASKA_GUIDELINE_2026 = 19_950 + + +@pytest.fixture(scope="module") +def client(): + with TestClient(api.app) as client: + yield client + + +@pytest.fixture(scope="module") +def answer_2027(client): + """Current law and every scenario for 2027 coverage, with 2026 current law.""" + request = {**HOUSEHOLD, **ALL_SCENARIOS, "year": 2027, "show_prior_year": True} + response = client.post("/api/calculate", json=request) + assert response.status_code == 200, response.text + answer = { + key: np.array(value) if isinstance(value, list) else value + for key, value in response.json().items() + } + # Income as a multiple of the guideline the credit uses. Points within 1% + # of a limit are left out of the checks, since the credit's FPL fraction is + # truncated to whole percents. + answer["multiple"] = answer["income"] / answer["fpl"] + return answer + + +def between(answer, low, high): + multiple = answer["multiple"] + return (multiple > low * 1.01) & (multiple < high * 0.99) + + +def test_requests_without_a_year_get_2026(): + assert CalculateRequest(age_head=40, state="TX", county="Travis County").year == 2026 + + +@pytest.mark.parametrize("year", [2025, 2028]) +def test_other_years_are_refused(year): + with pytest.raises(ValidationError, match="year must be one of 2026, 2027"): + CalculateRequest(age_head=40, state="TX", county="Travis County", year=year) + + +def test_the_cache_key_names_the_year_and_the_model_version(monkeypatch): + request = {"age_head": 40, "state": "TX", "county": "Travis County"} + key_2026 = api.get_cache_key(CalculateRequest(**request, year=2026)) + key_2027 = api.get_cache_key(CalculateRequest(**request, year=2027)) + assert key_2026 != key_2027 + with_2026 = CalculateRequest(**request, year=2027, show_prior_year=True) + assert api.get_cache_key(with_2026) != key_2027 + monkeypatch.setattr(api, "MODEL_VERSION", "another version") + assert api.get_cache_key(CalculateRequest(**request, year=2026)) != key_2026 + + +def test_only_2027_requests_can_ask_for_the_year_before(): + with pytest.raises(ValidationError, match="show_prior_year"): + CalculateRequest( + age_head=40, state="TX", county="Travis County", year=2026, show_prior_year=True + ) + + +def test_the_answer_names_its_year_guideline_and_model(answer_2027): + assert answer_2027["year"] == 2027 + # 2027 credits measure income against the 2026 guideline. + assert answer_2027["fpl_year"] == 2026 + assert answer_2027["fpl"] == GUIDELINE_2026 + assert answer_2027["model_version"] == api.MODEL_VERSION + + +def test_alaska_households_get_alaskas_prior_year_guideline(): + situation = build_household_situation(40, None, [], "AK", county="Anchorage Municipality", year=2027) + sim = Simulation(situation=situation) + assert float(sim.calculate("tax_unit_fpg", 2026)[0]) == ALASKA_GUIDELINE_2026 + + +def test_current_law_in_2027_ends_the_credit_at_400_percent(answer_2027): + baseline = answer_2027["ptc_baseline"] + assert (baseline[between(answer_2027, 1.5, 4)] > 0).all() + assert (baseline[answer_2027["multiple"] > 4.01] == 0).all() + + +def test_hr1834_in_2027_charges_nothing_below_150_percent(answer_2027): + # The enhanced schedule's required contribution is 0% of income there, so + # the credit is the whole benchmark premium. + below_150 = between(answer_2027, 1, 1.5) + assert below_150.any() + np.testing.assert_allclose(answer_2027["ptc_ira"][below_150], answer_2027["slcsp"], atol=1) + + +def test_hr1834_in_2027_continues_above_400_percent(answer_2027): + assert (answer_2027["ptc_ira"][between(answer_2027, 4, 7)] > 0).all() + + +def test_2026_current_law_comes_back_for_the_same_incomes(answer_2027): + # 2026 credits measure income against the 2025 guideline and end at 400% + # of it. + assert answer_2027["fpl_prior_year"] == GUIDELINE_2025 + prior = answer_2027["ptc_prior_year"] + assert len(prior) == len(answer_2027["income"]) + assert len(answer_2027["slcsp_by_income_prior_year"]) == len(answer_2027["income"]) + multiple = answer_2027["income"] / GUIDELINE_2025 + assert (prior[(multiple > 1.5 * 1.01) & (multiple < 4 * 0.99)] > 0).all() + assert (prior[multiple > 4.01] == 0).all() + + +@pytest.mark.parametrize( + "field", ["ptc_700fpl", "ptc_additional_bracket", "ptc_simplified_bracket"] +) +def test_the_other_scenarios_run_for_2027(answer_2027, field): + values = answer_2027[field] + assert len(values) == len(answer_2027["income"]) + assert values[between(answer_2027, 1.5, 4)].max() > 0 + + +def test_a_scenario_that_is_off_returns_zeros(client): + response = client.post("/api/calculate", json={**HOUSEHOLD, "show_ira": True}) + assert response.status_code == 200, response.text + answer = response.json() + assert answer["year"] == 2026 + assert answer["fpl"] == GUIDELINE_2025 + assert max(answer["ptc_ira"]) > 0 + for field in ("ptc_700fpl", "ptc_additional_bracket", "ptc_simplified_bracket"): + assert len(answer[field]) == len(answer["income"]) + assert max(answer[field]) == 0 + assert answer["ptc_prior_year"] is None +