From fdf8b8d309ea6133d3dafa8c09d2d7a3e08ffedd Mon Sep 17 00:00:00 2001 From: David Trimmer Date: Sat, 7 Nov 2026 19:01:08 -0500 Subject: [PATCH 1/4] Model 2027 coverage and the extension scenarios in the calculator API - Requests take a year, 2026 or 2027 (2026 if absent, so the live page's answers don't change), and every period, the household and both cache keys follow it. Responses report the year, the guideline's year and the policyengine-us version. - The FPL the API reports is now the prior year's guideline, the one the credit uses, and the household's state is set for that year too, so Alaska and Hawaii households get their own guideline for it. - One scenario table drives both calculator endpoints. New: the enhanced schedule capped at 700% FPL, and the enhanced schedule with a $5 minimum premium, which returns a 400 until policyengine-us models it (#10681). H.R. 1834's reform ends in 2028, as the bill does. - Responses include the benchmark premium at each income. - The AI explanation prompt takes the year and names the new scenarios. - Pin policyengine-us 2.105.0 (policyengine-core 3.34.9, spm-calculator 1.1.0), give the Modal function 4 GB, and smoke-test a 2027 answer after each deploy. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/modal-api.yml | 4 +- aca_calc/calculations/__init__.py | 6 + aca_calc/calculations/household.py | 9 +- aca_calc/calculations/reforms.py | 91 +++++- changelog.d/aca-2027-backend.added.md | 1 + changelog.d/aca-2027-backend.fixed.md | 1 + modal-requirements.txt | 16 +- modal_app.py | 4 +- scripts/smoke_test_api.py | 21 +- src/aca_api/api.py | 389 ++++++++++++-------------- src/aca_api/models.py | 82 +++++- tests/test_api_scenarios.py | 156 +++++++++++ 12 files changed, 543 insertions(+), 237 deletions(-) create mode 100644 changelog.d/aca-2027-backend.added.md create mode 100644 changelog.d/aca-2027-backend.fixed.md create mode 100644 tests/test_api_scenarios.py 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/__init__.py b/aca_calc/calculations/__init__.py index cb5a6aa..59908af 100644 --- a/aca_calc/calculations/__init__.py +++ b/aca_calc/calculations/__init__.py @@ -6,6 +6,9 @@ create_700fpl_reform, create_additional_bracket_reform, create_simplified_bracket_reform, + create_700fpl_cap_reform, + create_minimum_premium_reform, + minimum_premium_available, ) __all__ = [ @@ -14,4 +17,7 @@ "create_700fpl_reform", "create_additional_bracket_reform", "create_simplified_bracket_reform", + "create_700fpl_cap_reform", + "create_minimum_premium_reform", + "minimum_premium_available", ] 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..91dc393 100644 --- a/aca_calc/calculations/reforms.py +++ b/aca_calc/calculations/reforms.py @@ -14,29 +14,97 @@ 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; the January +# 2026 draft variants below use the same years. +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. + income for the benchmark plan. H.R. 1834 passed the House on January 8, + 2026; it has not been enacted. - 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. + Returns: + Reform: PolicyEngine reform object + """ + return Reform.from_dict({**_enhanced_schedule(), **NO_INCOME_CAP}, country_id="us") + + +def create_700fpl_cap_reform(): + """The enhanced schedule with eligibility ending at 700% FPL. + + A January 2026 draft of the CARE Act, which was never introduced, paired + the enhanced schedule with a 700% FPL income cap. Between 400% and 700% + FPL households pay 8.5% of income; above 700% there is no credit. 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}, + **_enhanced_schedule(), + # Move the ineligible bracket's start from 400% to 700% FPL. + "gov.aca.ptc_income_eligibility[2].threshold": {ENHANCED_PERIOD: 7}, + }, + country_id="us", + ) + + +MINIMUM_PREMIUM_MODULE = "aca_ptc_minimum_premium" + + +def minimum_premium_available() -> bool: + """Whether the installed policyengine-us has the minimum premium reform + (gov.contrib.aca.minimum_premium, policyengine-us #10681).""" + try: + _contrib_reform(MINIMUM_PREMIUM_MODULE, MINIMUM_PREMIUM_MODULE) + except ImportError: + return False + return True + + +def create_minimum_premium_reform(): + """The enhanced schedule with a $5 monthly minimum premium. + + The January 2026 CARE Act draft required every tax unit to pay at least $5 + a month toward its premiums: the credit can't cover the last $5 a month. + policyengine-us models it as the contributed reform + gov.contrib.aca.minimum_premium, $5 by default. + + Returns: + Reform: PolicyEngine reform object + + Raises: + ImportError: if the installed policyengine-us has no such reform. + """ + _contrib_reform(MINIMUM_PREMIUM_MODULE, MINIMUM_PREMIUM_MODULE) + return Reform.from_dict( + { + **_enhanced_schedule(), + **NO_INCOME_CAP, + "gov.contrib.aca.minimum_premium.in_effect": {ENHANCED_PERIOD: True}, }, country_id="us", ) @@ -57,6 +125,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..6496067 --- /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 two January 2026 draft variants of it: a 700% FPL cap, and a $5 minimum premium that stays off until policyengine-us models it. Report the benchmark premium at each income. Pin policyengine-us 2.105.0 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..c1a63e0 100644 --- a/modal-requirements.txt +++ b/modal-requirements.txt @@ -2,8 +2,11 @@ # # 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. On 2026-11-07 policyengine-us moved from 1.691.3 to 2.105.0, the +# latest release, which has the 2027 applicable percentages and the bracket +# variants' eligibility fix (policyengine-us #10680), 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 +61,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.105.0 prompt_toolkit==3.0.52 psutil==6.1.1 ptyprocess==0.7.0 @@ -81,7 +81,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..afc67cc 100644 --- a/modal_app.py +++ b/modal_app.py @@ -33,7 +33,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..365946b 100644 --- a/scripts/smoke_test_api.py +++ b/scripts/smoke_test_api.py @@ -3,10 +3,10 @@ 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. 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 +170,17 @@ 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. + # The credit measures income against the prior year's poverty guideline. + result = call(f"{base}/api/calculate", {**FRESH, "year": 2027}) + 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')}" + ) + 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 +245,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..4611425 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 @@ -28,8 +29,26 @@ create_700fpl_reform, create_additional_bracket_reform, create_simplified_bracket_reform, + create_700fpl_cap_reform, + create_minimum_premium_reform, + minimum_premium_available, ) +# 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), + ("show_700fpl_cap", "ptc_700fpl_cap", create_700fpl_cap_reform), + ("show_min_premium", "ptc_min_premium", create_minimum_premium_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 +194,83 @@ 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_700fpl_cap": data.show_700fpl_cap, + "show_min_premium": data.show_min_premium, + "year": data.year, + "model_version": MODEL_VERSION, } key_str = json.dumps(key_data, sort_keys=True) return hashlib.md5(key_str.encode()).hexdigest() +def check_scenarios(data: CalculateRequest): + """Refuse a scenario the installed model can't run, saying why.""" + if data.show_min_premium and not minimum_premium_available(): + raise ValueError( + "The $5 minimum premium scenario needs a policyengine-us release with " + f"gov.contrib.aca.minimum_premium; this API runs policyengine-us {MODEL_VERSION}." + ) + + +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_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) -> 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, + ) + + @app.post("/api/calculate", response_model=CalculateResponse) async def calculate_ptc(data: CalculateRequest): """Calculate premium tax credits across income range. @@ -194,100 +285,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), - ) + check_scenarios(data) + situation = household_situation(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) # Cache the result (persistent + local) if not data.skip_cache: @@ -323,107 +332,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, - ) + check_scenarios(data) + situation = household_situation(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) - - slcsp = float(np.max(slcsp_array)) - fpl = float(fpl_array[len(fpl_array) // 2]) + baseline = run_baseline(data, situation) - # 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 + zeros = np.zeros_like(baseline["ptc_baseline"]) 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 + 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) # Cache the result (persistent + local) if not data.skip_cache: @@ -496,17 +435,23 @@ 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_700fpl_cap: + reform_data_lines.append(f"- Enhanced credits capped at 700% FPL PTC: ${data.ptc_700fpl_cap_at_sample:,.0f}/year (${data.ptc_700fpl_cap_at_sample/12:,.0f}/month)") + if data.show_min_premium: + reform_data_lines.append(f"- Enhanced credits with a $5 minimum premium PTC: ${data.ptc_min_premium_at_sample:,.0f}/year (${data.ptc_min_premium_at_sample/12:,.0f}/month)") reform_data_text = "\n".join(reform_data_lines) @@ -514,17 +459,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 +479,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 +488,22 @@ 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""") + + if data.show_700fpl_cap: + reform_descriptions.append(""" +ENHANCED CREDITS CAPPED AT 700% FPL (show_700fpl_cap=True): +- The enhanced (ARPA/IRA) contribution schedule, with eligibility ending at 700% FPL +- A January 2026 draft of the CARE Act, which was never introduced, paired the enhanced schedule with this cap +- Between 400% and 700% FPL, households pay at most 8.5% of income for the benchmark plan; above 700% FPL there is no credit""") + + if data.show_min_premium: + reform_descriptions.append(""" +ENHANCED CREDITS WITH A $5 MINIMUM PREMIUM (show_min_premium=True): +- The enhanced (ARPA/IRA) contribution schedule with no income limit, except that the credit cannot cover the last $5 a month of a household's premium +- From the same January 2026 CARE Act draft, which was never introduced +- A household whose credit would otherwise cover the whole benchmark premium pays $5 a month ($60 a year)""") reform_descriptions_text = "\n".join(reform_descriptions) if reform_descriptions else "No reforms selected." @@ -568,49 +527,65 @@ 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 + if data.show_700fpl_cap: + diff = data.ptc_700fpl_cap_at_sample - data.ptc_baseline_at_sample + sections_spec.append(f'{section_num}. id: "cap700", chartState: "cap700_focus" - Explain the enhanced credits capped at 700% FPL, from a January 2026 draft of the CARE Act that was never introduced. At ${data.sample_income:,.0f} income, it provides ${data.ptc_700fpl_cap_at_sample:,.0f}/year vs current law ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). Explain that it follows the enhanced schedule up to 700% FPL (${data.fpl_700_income:,.0f}) and ends there.') + sections_json.append('{{"id": "cap700", "title": "...", "content": "...", "chartState": "cap700_focus"}}') + section_num += 1 + + if data.show_min_premium: + diff = data.ptc_min_premium_at_sample - data.ptc_baseline_at_sample + sections_spec.append(f'{section_num}. id: "minprem", chartState: "minprem_focus" - Explain the enhanced credits with a $5 minimum premium, from a January 2026 draft of the CARE Act that was never introduced. At ${data.sample_income:,.0f} income, it provides ${data.ptc_min_premium_at_sample:,.0f}/year vs current law ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). Explain that the credit cannot cover the last $5 a month of the premium.') + sections_json.append('{{"id": "minprem", "title": "...", "content": "...", "chartState": "minprem_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: selected_reforms.append("Additional Bracket") if data.show_simplified_bracket: selected_reforms.append("Simplified Bracket") + if data.show_700fpl_cap: + selected_reforms.append("enhanced credits capped at 700% FPL") + if data.show_min_premium: + selected_reforms.append("enhanced credits with a $5 minimum premium") 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"}}') sections_spec_text = "\n\n".join(sections_spec) @@ -624,6 +599,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,8 +614,9 @@ 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) @@ -653,7 +630,7 @@ def build_explain_prompt(data: ExplainRequest) -> str: - id: unique identifier - title: descriptive section title (5-10 words) - content: 2-3 short paragraphs using **bold** for key numbers. Use exact values provided above. -- chartState: MUST be one of these exact strings: "all_programs", "medicaid_focus", "chip_focus", "cliff_focus", "ira_impact", "fpl700_focus", "additional_focus", "simplified_focus", "both_reforms" +- chartState: MUST be one of these exact strings: "all_programs", "medicaid_focus", "chip_focus", "cliff_focus", "ira_impact", "fpl700_focus", "additional_focus", "simplified_focus", "cap700_focus", "minprem_focus", "both_reforms" REQUIRED SECTIONS (use these EXACT chartState values and ids): {sections_spec_text} @@ -685,6 +662,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_700fpl_cap": data.show_700fpl_cap, + "show_min_premium": data.show_min_premium, + "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..2fada59 100644 --- a/src/aca_api/models.py +++ b/src/aca_api/models.py @@ -2,6 +2,17 @@ from pydantic import BaseModel, Field, field_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): """Request model for PTC calculation.""" @@ -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,24 @@ class CalculateRequest(BaseModel): show_simplified_bracket: bool = Field( default=False, description="Calculate simplified bracket reform scenario" ) + show_700fpl_cap: bool = Field( + default=False, + description="Calculate the enhanced credits capped at 700% FPL (January 2026 draft)", + ) + show_min_premium: bool = Field( + default=False, + description="Calculate the enhanced credits with a $5 minimum premium (January 2026 draft)", + ) 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) + @field_validator("dependent_ages") @classmethod def validate_dependent_ages(cls, v): @@ -63,9 +92,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,8 +102,31 @@ 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") + ptc_700fpl_cap: list[float] = Field( + default_factory=list, + description="PTC under the enhanced credits capped at 700% FPL", + ) + ptc_min_premium: list[float] = Field( + default_factory=list, + description="PTC under the enhanced credits with a $5 minimum premium", + ) + 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") @@ -85,7 +137,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, " + "cap700_focus, minprem_focus or both_reforms" + ) + ) class ExplainRequest(BaseModel): @@ -97,6 +155,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 +174,8 @@ 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_700fpl_cap: bool = Field(default=False, description="Whether the 700% FPL cap variant is selected") + show_min_premium: bool = Field(default=False, description="Whether the $5 minimum premium variant is selected") # Key data points for narrative sample_income: float = Field(description="Sample income to analyze") @@ -123,6 +184,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") + ptc_700fpl_cap_at_sample: float = Field(default=0, description="700% FPL cap variant PTC at sample income") + ptc_min_premium_at_sample: float = Field(default=0, description="$5 minimum premium variant PTC 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..51f7317 --- /dev/null +++ b/tests/test_api_scenarios.py @@ -0,0 +1,156 @@ +"""The calculator API for 2026 and 2027 coverage, and its 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 aca_calc.calculations.reforms import minimum_premium_available +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, + "show_700fpl_cap": 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 available scenario for 2027 coverage.""" + response = client.post("/api/calculate", json={**HOUSEHOLD, **ALL_SCENARIOS, "year": 2027}) + 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 + monkeypatch.setattr(api, "MODEL_VERSION", "another version") + assert api.get_cache_key(CalculateRequest(**request, year=2026)) != key_2026 + + +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_the_700_percent_cap_follows_hr1834_and_ends_at_700_percent(answer_2027): + below_700 = between(answer_2027, 1, 7) + np.testing.assert_allclose( + answer_2027["ptc_700fpl_cap"][below_700], answer_2027["ptc_ira"][below_700], atol=1 + ) + above_700 = answer_2027["multiple"] > 7.01 + assert (answer_2027["ptc_700fpl_cap"][above_700] == 0).all() + assert (answer_2027["ptc_ira"][above_700 & (answer_2027["multiple"] < 8)] > 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_700fpl_cap", "ptc_min_premium"): + assert len(answer[field]) == len(answer["income"]) + assert max(answer[field]) == 0 + + +@pytest.mark.skipif( + minimum_premium_available(), reason="the installed policyengine-us models the minimum premium" +) +def test_the_minimum_premium_scenario_says_what_it_needs(client): + request = {**HOUSEHOLD, "show_ira": False, "show_min_premium": True, "year": 2027} + response = client.post("/api/calculate", json=request) + assert response.status_code == 400 + assert "gov.contrib.aca.minimum_premium" in response.json()["detail"] + stream = client.post("/api/calculate-stream", json=request) + assert '"step": "error"' in stream.text + assert "gov.contrib.aca.minimum_premium" in stream.text From 5471149d64d51ad67d12f9b6439a1bfc5ef48a37 Mon Sep 17 00:00:00 2001 From: David Trimmer Date: Mon, 9 Nov 2026 11:45:25 -0500 Subject: [PATCH 2/4] Pin policyengine-us 2.115.0, with the 2027 premiums and the minimum premium 2.115.0 is the first release with the published 2027 premiums (policyengine-us #10682) and the minimum premium reform (#10681), so the $5 minimum premium scenario now runs. The tests check that it leaves $60 a year where H.R. 1834's credit covers the whole benchmark and matches H.R. 1834 where the household pays more, and that a model without it still gets a 400 that says so. Its requirements are those of 2.105.0. Co-Authored-By: Claude Opus 5.5 (1M context) --- changelog.d/aca-2027-backend.added.md | 2 +- modal-requirements.txt | 8 ++++---- tests/test_api_scenarios.py | 29 +++++++++++++++++++++++---- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/changelog.d/aca-2027-backend.added.md b/changelog.d/aca-2027-backend.added.md index 6496067..639aefd 100644 --- a/changelog.d/aca-2027-backend.added.md +++ b/changelog.d/aca-2027-backend.added.md @@ -1 +1 @@ -Model 2027 coverage in the calculator API (requests without a year still get 2026), with H.R. 1834 and two January 2026 draft variants of it: a 700% FPL cap, and a $5 minimum premium that stays off until policyengine-us models it. Report the benchmark premium at each income. Pin policyengine-us 2.105.0 and give the Modal function 4 GB. +Model 2027 coverage in the calculator API (requests without a year still get 2026), with H.R. 1834 and two January 2026 draft variants of it: a 700% FPL cap and a $5 minimum premium. 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/modal-requirements.txt b/modal-requirements.txt index c1a63e0..0b68dfc 100644 --- a/modal-requirements.txt +++ b/modal-requirements.txt @@ -2,9 +2,9 @@ # # 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. On 2026-11-07 policyengine-us moved from 1.691.3 to 2.105.0, the -# latest release, which has the 2027 applicable percentages and the bracket -# variants' eligibility fix (policyengine-us #10680), with the +# 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) and the minimum premium reform (#10681), with the # policyengine-core and spm-calculator versions it requires; every other pin # is unchanged. # @@ -62,7 +62,7 @@ pexpect==4.9.0 plotly==5.24.1 pluggy==1.6.0 policyengine-core==3.34.9 -policyengine-us==2.105.0 +policyengine-us==2.115.0 prompt_toolkit==3.0.52 psutil==6.1.1 ptyprocess==0.7.0 diff --git a/tests/test_api_scenarios.py b/tests/test_api_scenarios.py index 51f7317..6926720 100644 --- a/tests/test_api_scenarios.py +++ b/tests/test_api_scenarios.py @@ -27,6 +27,7 @@ "show_additional_bracket": True, "show_simplified_bracket": True, "show_700fpl_cap": True, + "show_min_premium": True, } # Single-person poverty guidelines for the 48 states and Alaska (HHS). GUIDELINE_2025 = 15_650 @@ -143,10 +144,30 @@ def test_a_scenario_that_is_off_returns_zeros(client): assert max(answer[field]) == 0 -@pytest.mark.skipif( - minimum_premium_available(), reason="the installed policyengine-us models the minimum premium" -) -def test_the_minimum_premium_scenario_says_what_it_needs(client): +def test_the_installed_model_has_the_minimum_premium(): + assert minimum_premium_available() + + +def test_the_minimum_premium_leaves_60_dollars_where_hr1834_covers_the_premium(answer_2027): + # Below 150% FPL the enhanced schedule's contribution is 0%, so H.R. 1834's + # credit is the whole benchmark premium; the minimum leaves $5 a month. + below_150 = between(answer_2027, 1, 1.5) + np.testing.assert_allclose( + answer_2027["ptc_min_premium"][below_150], answer_2027["slcsp"] - 60, atol=1 + ) + + +def test_the_minimum_premium_matches_hr1834_where_the_household_pays_more(answer_2027): + # From 200% FPL the required contribution is at least 2% of income, far + # more than $60 a year, so the minimum doesn't bind. + above_200 = between(answer_2027, 2, 7) + np.testing.assert_allclose( + answer_2027["ptc_min_premium"][above_200], answer_2027["ptc_ira"][above_200], atol=1 + ) + + +def test_a_model_without_the_minimum_premium_says_what_it_needs(client, monkeypatch): + monkeypatch.setattr(api, "minimum_premium_available", lambda: False) request = {**HOUSEHOLD, "show_ira": False, "show_min_premium": True, "year": 2027} response = client.post("/api/calculate", json=request) assert response.status_code == 400 From 51f53bb46fa4608580ead2a285a090cb6fc9df0a Mon Sep 17 00:00:00 2001 From: David Trimmer Date: Mon, 9 Nov 2026 14:15:20 -0500 Subject: [PATCH 3/4] Drop the draft scenarios and return 2026 current law alongside 2027 The calculator now compares 2027 current law with H.R. 1834 and shows 2026 current law beside them, so the January 2026 draft variants (the 700% FPL cap and the $5 minimum premium) go. A 2027 request with show_prior_year also gets 2026 current law for the same household and incomes: ptc_prior_year, slcsp_by_income_prior_year and fpl_prior_year. The smoke test asks for it, and the explanation prompt uses it. Co-Authored-By: Claude Opus 5.5 (1M context) --- aca_calc/calculations/__init__.py | 6 -- aca_calc/calculations/reforms.py | 61 +------------- changelog.d/aca-2027-backend.added.md | 2 +- modal-requirements.txt | 5 +- scripts/smoke_test_api.py | 12 ++- src/aca_api/api.py | 111 ++++++++++++-------------- src/aca_api/models.py | 51 +++++++----- tests/test_api_scenarios.py | 73 ++++++----------- 8 files changed, 118 insertions(+), 203 deletions(-) diff --git a/aca_calc/calculations/__init__.py b/aca_calc/calculations/__init__.py index 59908af..cb5a6aa 100644 --- a/aca_calc/calculations/__init__.py +++ b/aca_calc/calculations/__init__.py @@ -6,9 +6,6 @@ create_700fpl_reform, create_additional_bracket_reform, create_simplified_bracket_reform, - create_700fpl_cap_reform, - create_minimum_premium_reform, - minimum_premium_available, ) __all__ = [ @@ -17,7 +14,4 @@ "create_700fpl_reform", "create_additional_bracket_reform", "create_simplified_bracket_reform", - "create_700fpl_cap_reform", - "create_minimum_premium_reform", - "minimum_premium_available", ] diff --git a/aca_calc/calculations/reforms.py b/aca_calc/calculations/reforms.py index 91dc393..4a33932 100644 --- a/aca_calc/calculations/reforms.py +++ b/aca_calc/calculations/reforms.py @@ -14,8 +14,7 @@ ENHANCED_INITIAL = [0, 0, 0.02, 0.04, 0.06] ENHANCED_FINAL = [0, 0.02, 0.04, 0.06, 0.085] -# H.R. 1834 extends the enhanced schedule for 2026 through 2028; the January -# 2026 draft variants below use the same years. +# H.R. 1834 extends the enhanced schedule for 2026 through 2028. ENHANCED_PERIOD = "2026-01-01.2028-12-31" @@ -52,64 +51,6 @@ def create_enhanced_ptc_reform(): return Reform.from_dict({**_enhanced_schedule(), **NO_INCOME_CAP}, country_id="us") -def create_700fpl_cap_reform(): - """The enhanced schedule with eligibility ending at 700% FPL. - - A January 2026 draft of the CARE Act, which was never introduced, paired - the enhanced schedule with a 700% FPL income cap. Between 400% and 700% - FPL households pay 8.5% of income; above 700% there is no credit. - - Returns: - Reform: PolicyEngine reform object - """ - return Reform.from_dict( - { - **_enhanced_schedule(), - # Move the ineligible bracket's start from 400% to 700% FPL. - "gov.aca.ptc_income_eligibility[2].threshold": {ENHANCED_PERIOD: 7}, - }, - country_id="us", - ) - - -MINIMUM_PREMIUM_MODULE = "aca_ptc_minimum_premium" - - -def minimum_premium_available() -> bool: - """Whether the installed policyengine-us has the minimum premium reform - (gov.contrib.aca.minimum_premium, policyengine-us #10681).""" - try: - _contrib_reform(MINIMUM_PREMIUM_MODULE, MINIMUM_PREMIUM_MODULE) - except ImportError: - return False - return True - - -def create_minimum_premium_reform(): - """The enhanced schedule with a $5 monthly minimum premium. - - The January 2026 CARE Act draft required every tax unit to pay at least $5 - a month toward its premiums: the credit can't cover the last $5 a month. - policyengine-us models it as the contributed reform - gov.contrib.aca.minimum_premium, $5 by default. - - Returns: - Reform: PolicyEngine reform object - - Raises: - ImportError: if the installed policyengine-us has no such reform. - """ - _contrib_reform(MINIMUM_PREMIUM_MODULE, MINIMUM_PREMIUM_MODULE) - return Reform.from_dict( - { - **_enhanced_schedule(), - **NO_INCOME_CAP, - "gov.contrib.aca.minimum_premium.in_effect": {ENHANCED_PERIOD: True}, - }, - country_id="us", - ) - - def _contrib_reform(module: str, name: str): """A structural ACA reform from policyengine-us, or an error saying which is missing: a missing reform must not show as zero credits.""" diff --git a/changelog.d/aca-2027-backend.added.md b/changelog.d/aca-2027-backend.added.md index 639aefd..cd189f9 100644 --- a/changelog.d/aca-2027-backend.added.md +++ b/changelog.d/aca-2027-backend.added.md @@ -1 +1 @@ -Model 2027 coverage in the calculator API (requests without a year still get 2026), with H.R. 1834 and two January 2026 draft variants of it: a 700% FPL cap and a $5 minimum premium. 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. +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/modal-requirements.txt b/modal-requirements.txt index 0b68dfc..fbe1410 100644 --- a/modal-requirements.txt +++ b/modal-requirements.txt @@ -4,9 +4,8 @@ # minus the 14 packages that Modal's 2025.06 image builder installs at the same # 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) and the minimum premium reform (#10681), with the -# policyengine-core and spm-calculator versions it requires; every other pin -# is unchanged. +# (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. diff --git a/scripts/smoke_test_api.py b/scripts/smoke_test_api.py index 365946b..c5754a7 100644 --- a/scripts/smoke_test_api.py +++ b/scripts/smoke_test_api.py @@ -4,7 +4,8 @@ Checks /api/health, then both calculator endpoints: /api/calculate-stream, which the calculator page calls, and /api/calculate, its fallback, and then a -2027 calculation. The requests set skip_cache, so the deployed code computes +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 @@ -171,13 +172,16 @@ def check_calculate(base): def check_calculate_2027(base): - # Requests without a year get 2026; the calculator page asks for 2027. - # The credit measures income against the prior year's poverty guideline. - result = call(f"{base}/api/calculate", {**FRESH, "year": 2027}) + # 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) diff --git a/src/aca_api/api.py b/src/aca_api/api.py index 4611425..c6b62c0 100644 --- a/src/aca_api/api.py +++ b/src/aca_api/api.py @@ -29,9 +29,6 @@ create_700fpl_reform, create_additional_bracket_reform, create_simplified_bracket_reform, - create_700fpl_cap_reform, - create_minimum_premium_reform, - minimum_premium_available, ) # The model version is part of every cache key, so a new pin never serves @@ -45,8 +42,6 @@ ("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), - ("show_700fpl_cap", "ptc_700fpl_cap", create_700fpl_cap_reform), - ("show_min_premium", "ptc_min_premium", create_minimum_premium_reform), ] # Local cache fallback for development (in-memory, lost on restart) @@ -194,8 +189,7 @@ 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_700fpl_cap": data.show_700fpl_cap, - "show_min_premium": data.show_min_premium, + "show_prior_year": data.show_prior_year, "year": data.year, "model_version": MODEL_VERSION, } @@ -203,15 +197,6 @@ def get_cache_key(data: CalculateRequest) -> str: return hashlib.md5(key_str.encode()).hexdigest() -def check_scenarios(data: CalculateRequest): - """Refuse a scenario the installed model can't run, saying why.""" - if data.show_min_premium and not minimum_premium_available(): - raise ValueError( - "The $5 minimum premium scenario needs a policyengine-us release with " - f"gov.contrib.aca.minimum_premium; this API runs policyengine-us {MODEL_VERSION}." - ) - - def household_situation(data: CalculateRequest) -> dict: """The household, with an income axis, for the request's coverage year.""" return build_household_situation( @@ -247,6 +232,26 @@ def run_baseline(data: CalculateRequest, situation: dict) -> dict: } +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): @@ -255,7 +260,9 @@ def run_scenario(data: CalculateRequest, situation: dict, flag: str, create_refo return sim.calculate("aca_ptc", map_to="household", period=data.year) -def build_response(data: CalculateRequest, baseline: dict, scenarios: dict) -> CalculateResponse: +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"]), @@ -268,6 +275,7 @@ def build_response(data: CalculateRequest, baseline: dict, scenarios: dict) -> C medicaid=convert_to_native(baseline["medicaid"]), chip=convert_to_native(baseline["chip"]), model_version=MODEL_VERSION, + **prior_year, ) @@ -285,8 +293,8 @@ async def calculate_ptc(data: CalculateRequest): return cached try: - check_scenarios(data) situation = household_situation(data) + prior_year = simulation_executor.submit(run_prior_year, data) baseline = run_baseline(data, situation) # Run the selected scenarios in parallel @@ -296,7 +304,7 @@ async def calculate_ptc(data: CalculateRequest): for flag, field, create in SCENARIOS } scenarios = {field: future.result() for field, future in futures.items()} - response = build_response(data, baseline, scenarios) + response = build_response(data, baseline, scenarios, prior_year.result()) # Cache the result (persistent + local) if not data.skip_cache: @@ -332,8 +340,9 @@ 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 - check_scenarios(data) situation = household_situation(data) + loop = asyncio.get_event_loop() + prior_year = loop.run_in_executor(simulation_executor, run_prior_year, data) # Step 2: Run the current-law simulation message = f"Calculating current law ({data.year})..." @@ -347,7 +356,6 @@ async def generate(): await asyncio.sleep(0) zeros = np.zeros_like(baseline["ptc_baseline"]) - loop = asyncio.get_event_loop() results = await asyncio.gather( *( loop.run_in_executor( @@ -362,7 +370,7 @@ async def generate(): yield f"data: {json.dumps({'step': 'finalizing', 'progress': 90, 'message': 'Finalizing results...'})}\n\n" await asyncio.sleep(0) - response = build_response(data, baseline, scenarios) + response = build_response(data, baseline, scenarios, await prior_year) # Cache the result (persistent + local) if not data.skip_cache: @@ -448,10 +456,8 @@ def build_explain_prompt(data: ExplainRequest) -> str: 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_700fpl_cap: - reform_data_lines.append(f"- Enhanced credits capped at 700% FPL PTC: ${data.ptc_700fpl_cap_at_sample:,.0f}/year (${data.ptc_700fpl_cap_at_sample/12:,.0f}/month)") - if data.show_min_premium: - reform_data_lines.append(f"- Enhanced credits with a $5 minimum premium PTC: ${data.ptc_min_premium_at_sample:,.0f}/year (${data.ptc_min_premium_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) @@ -491,20 +497,6 @@ def build_explain_prompt(data: ExplainRequest) -> str: - Simplest structure, with the fastest phase-out of the options - CRFB estimates it would cost about $175 billion through 2035""") - if data.show_700fpl_cap: - reform_descriptions.append(""" -ENHANCED CREDITS CAPPED AT 700% FPL (show_700fpl_cap=True): -- The enhanced (ARPA/IRA) contribution schedule, with eligibility ending at 700% FPL -- A January 2026 draft of the CARE Act, which was never introduced, paired the enhanced schedule with this cap -- Between 400% and 700% FPL, households pay at most 8.5% of income for the benchmark plan; above 700% FPL there is no credit""") - - if data.show_min_premium: - reform_descriptions.append(""" -ENHANCED CREDITS WITH A $5 MINIMUM PREMIUM (show_min_premium=True): -- The enhanced (ARPA/IRA) contribution schedule with no income limit, except that the credit cannot cover the last $5 a month of a household's premium -- From the same January 2026 CARE Act draft, which was never introduced -- A household whose credit would otherwise cover the whole benchmark premium pays $5 a month ($60 a year)""") - reform_descriptions_text = "\n".join(reform_descriptions) if reform_descriptions else "No reforms selected." # Build dynamic sections based on selected reforms @@ -513,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 @@ -556,18 +555,6 @@ def build_explain_prompt(data: ExplainRequest) -> str: sections_json.append('{{"id": "simplified", "title": "...", "content": "...", "chartState": "simplified_focus"}}') section_num += 1 - if data.show_700fpl_cap: - diff = data.ptc_700fpl_cap_at_sample - data.ptc_baseline_at_sample - sections_spec.append(f'{section_num}. id: "cap700", chartState: "cap700_focus" - Explain the enhanced credits capped at 700% FPL, from a January 2026 draft of the CARE Act that was never introduced. At ${data.sample_income:,.0f} income, it provides ${data.ptc_700fpl_cap_at_sample:,.0f}/year vs current law ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). Explain that it follows the enhanced schedule up to 700% FPL (${data.fpl_700_income:,.0f}) and ends there.') - sections_json.append('{{"id": "cap700", "title": "...", "content": "...", "chartState": "cap700_focus"}}') - section_num += 1 - - if data.show_min_premium: - diff = data.ptc_min_premium_at_sample - data.ptc_baseline_at_sample - sections_spec.append(f'{section_num}. id: "minprem", chartState: "minprem_focus" - Explain the enhanced credits with a $5 minimum premium, from a January 2026 draft of the CARE Act that was never introduced. At ${data.sample_income:,.0f} income, it provides ${data.ptc_min_premium_at_sample:,.0f}/year vs current law ${data.ptc_baseline_at_sample:,.0f}/year (difference: ${diff:,.0f}/year). Explain that the credit cannot cover the last $5 a month of the premium.') - sections_json.append('{{"id": "minprem", "title": "...", "content": "...", "chartState": "minprem_focus"}}') - section_num += 1 - # Final comparison section (always included) selected_reforms = [] if data.show_ira: @@ -578,16 +565,18 @@ def build_explain_prompt(data: ExplainRequest) -> str: selected_reforms.append("Additional Bracket") if data.show_simplified_bracket: selected_reforms.append("Simplified Bracket") - if data.show_700fpl_cap: - selected_reforms.append("enhanced credits capped at 700% FPL") - if data.show_min_premium: - selected_reforms.append("enhanced credits with a $5 minimum premium") 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: 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) @@ -618,7 +607,7 @@ def build_explain_prompt(data: ExplainRequest) -> str: - 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} @@ -630,7 +619,7 @@ def build_explain_prompt(data: ExplainRequest) -> str: - id: unique identifier - title: descriptive section title (5-10 words) - content: 2-3 short paragraphs using **bold** for key numbers. Use exact values provided above. -- chartState: MUST be one of these exact strings: "all_programs", "medicaid_focus", "chip_focus", "cliff_focus", "ira_impact", "fpl700_focus", "additional_focus", "simplified_focus", "cap700_focus", "minprem_focus", "both_reforms" +- chartState: MUST be one of these exact strings: "all_programs", "medicaid_focus", "chip_focus", "cliff_focus", "ira_impact", "fpl700_focus", "additional_focus", "simplified_focus", "both_reforms" REQUIRED SECTIONS (use these EXACT chartState values and ids): {sections_spec_text} @@ -662,8 +651,8 @@ 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_700fpl_cap": data.show_700fpl_cap, - "show_min_premium": data.show_min_premium, + "show_prior_year": data.show_prior_year, + "slcsp_prior_year": round(data.slcsp_prior_year, 0), "year": data.year, "model_version": MODEL_VERSION, } diff --git a/src/aca_api/models.py b/src/aca_api/models.py index 2fada59..b835a7c 100644 --- a/src/aca_api/models.py +++ b/src/aca_api/models.py @@ -1,6 +1,6 @@ """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. @@ -44,13 +44,12 @@ class CalculateRequest(BaseModel): show_simplified_bracket: bool = Field( default=False, description="Calculate simplified bracket reform scenario" ) - show_700fpl_cap: bool = Field( + show_prior_year: bool = Field( default=False, - description="Calculate the enhanced credits capped at 700% FPL (January 2026 draft)", - ) - show_min_premium: bool = Field( - default=False, - description="Calculate the enhanced credits with a $5 minimum premium (January 2026 draft)", + 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, @@ -62,6 +61,15 @@ class CalculateRequest(BaseModel): 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): @@ -102,14 +110,6 @@ class CalculateResponse(BaseModel): ptc_simplified_bracket: list[float] = Field( default_factory=list, description="PTC under simplified bracket reform" ) - ptc_700fpl_cap: list[float] = Field( - default_factory=list, - description="PTC under the enhanced credits capped at 700% FPL", - ) - ptc_min_premium: list[float] = Field( - default_factory=list, - description="PTC under the enhanced credits with a $5 minimum premium", - ) year: int = Field(default=DEFAULT_YEAR, description="Coverage year") fpl: float = Field( description=( @@ -129,6 +129,16 @@ class CalculateResponse(BaseModel): ) 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): @@ -140,8 +150,8 @@ class ScrollySection(BaseModel): chartState: str = Field( description=( "Chart state: all_programs, medicaid_focus, chip_focus, cliff_focus, " - "ira_impact, fpl700_focus, additional_focus, simplified_focus, " - "cap700_focus, minprem_focus or both_reforms" + "ira_impact, fpl700_focus, additional_focus, simplified_focus or " + "both_reforms" ) ) @@ -174,8 +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_700fpl_cap: bool = Field(default=False, description="Whether the 700% FPL cap variant is selected") - show_min_premium: bool = Field(default=False, description="Whether the $5 minimum premium variant 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") @@ -184,8 +193,8 @@ 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") - ptc_700fpl_cap_at_sample: float = Field(default=0, description="700% FPL cap variant PTC at sample income") - ptc_min_premium_at_sample: float = Field(default=0, description="$5 minimum premium variant 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 diff --git a/tests/test_api_scenarios.py b/tests/test_api_scenarios.py index 6926720..d965c19 100644 --- a/tests/test_api_scenarios.py +++ b/tests/test_api_scenarios.py @@ -1,4 +1,5 @@ -"""The calculator API for 2026 and 2027 coverage, and its extension scenarios. +"""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% @@ -16,7 +17,6 @@ ).TestClient from aca_calc.calculations.household import build_household_situation -from aca_calc.calculations.reforms import minimum_premium_available from src.aca_api import api from src.aca_api.models import CalculateRequest @@ -26,8 +26,6 @@ "show_700fpl": True, "show_additional_bracket": True, "show_simplified_bracket": True, - "show_700fpl_cap": True, - "show_min_premium": True, } # Single-person poverty guidelines for the 48 states and Alaska (HHS). GUIDELINE_2025 = 15_650 @@ -43,8 +41,9 @@ def client(): @pytest.fixture(scope="module") def answer_2027(client): - """Current law and every available scenario for 2027 coverage.""" - response = client.post("/api/calculate", json={**HOUSEHOLD, **ALL_SCENARIOS, "year": 2027}) + """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 @@ -77,10 +76,19 @@ def test_the_cache_key_names_the_year_and_the_model_version(monkeypatch): 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. @@ -113,14 +121,16 @@ 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_the_700_percent_cap_follows_hr1834_and_ends_at_700_percent(answer_2027): - below_700 = between(answer_2027, 1, 7) - np.testing.assert_allclose( - answer_2027["ptc_700fpl_cap"][below_700], answer_2027["ptc_ira"][below_700], atol=1 - ) - above_700 = answer_2027["multiple"] > 7.01 - assert (answer_2027["ptc_700fpl_cap"][above_700] == 0).all() - assert (answer_2027["ptc_ira"][above_700 & (answer_2027["multiple"] < 8)] > 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( @@ -139,39 +149,8 @@ def test_a_scenario_that_is_off_returns_zeros(client): assert answer["year"] == 2026 assert answer["fpl"] == GUIDELINE_2025 assert max(answer["ptc_ira"]) > 0 - for field in ("ptc_700fpl", "ptc_700fpl_cap", "ptc_min_premium"): + 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 - -def test_the_installed_model_has_the_minimum_premium(): - assert minimum_premium_available() - - -def test_the_minimum_premium_leaves_60_dollars_where_hr1834_covers_the_premium(answer_2027): - # Below 150% FPL the enhanced schedule's contribution is 0%, so H.R. 1834's - # credit is the whole benchmark premium; the minimum leaves $5 a month. - below_150 = between(answer_2027, 1, 1.5) - np.testing.assert_allclose( - answer_2027["ptc_min_premium"][below_150], answer_2027["slcsp"] - 60, atol=1 - ) - - -def test_the_minimum_premium_matches_hr1834_where_the_household_pays_more(answer_2027): - # From 200% FPL the required contribution is at least 2% of income, far - # more than $60 a year, so the minimum doesn't bind. - above_200 = between(answer_2027, 2, 7) - np.testing.assert_allclose( - answer_2027["ptc_min_premium"][above_200], answer_2027["ptc_ira"][above_200], atol=1 - ) - - -def test_a_model_without_the_minimum_premium_says_what_it_needs(client, monkeypatch): - monkeypatch.setattr(api, "minimum_premium_available", lambda: False) - request = {**HOUSEHOLD, "show_ira": False, "show_min_premium": True, "year": 2027} - response = client.post("/api/calculate", json=request) - assert response.status_code == 400 - assert "gov.contrib.aca.minimum_premium" in response.json()["detail"] - stream = client.post("/api/calculate-stream", json=request) - assert '"step": "error"' in stream.text - assert "gov.contrib.aca.minimum_premium" in stream.text From fb7bbb6425e2f9c46fd05dc885a33d56ad12fc6c Mon Sep 17 00:00:00 2001 From: David Trimmer Date: Wed, 11 Nov 2026 09:47:43 -0500 Subject: [PATCH 4/4] Let a preview of the API run beside the live app ACA_API_APP_NAME names the Modal app (aca-calc-api by default). A preview deploy, such as aca-calc-api-preview, gets caches of its own, and the image carries the name so its containers open them. Co-Authored-By: Claude Opus 5.5 --- modal_app.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/modal_app.py b/modal_app.py index afc67cc..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, + } + ) )