From 3b734808826654b91353b13dfb6c7fe9f6805a9b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 10:13:54 -0500 Subject: [PATCH 1/3] Show the forward rate as "Saved on the next $1" /api/calculate's marginal_savings_rate was the donation sweep's central difference at the nearest grid point, which averages the rates on either side of a kink. A single filer giving $1,000 in 2026 sits on the 170(p) cap, so Texas showed 14.7% where the next dollar saves nothing, and Massachusetts 19.7% where it saves 5%. The rate now comes from a point run at the gift plus $100, in the same parallel batch as the $0 and gift runs: (net tax at the gift - net tax $100 above) / 100. Smaller steps turn float32 rounding into rate. Co-Authored-By: Claude Opus 5.5 --- api/main.py | 38 ++++-- .../src/components/__tests__/Faq.test.tsx | 2 +- frontend/src/components/faq/questions.tsx | 3 +- tests/test_household_payload.py | 8 +- tests/test_next_dollar_rate.py | 111 ++++++++++++++++++ 5 files changed, 149 insertions(+), 13 deletions(-) create mode 100644 tests/test_next_dollar_rate.py diff --git a/api/main.py b/api/main.py index 799ae3b..022f2ca 100644 --- a/api/main.py +++ b/api/main.py @@ -388,17 +388,38 @@ def sample_curve(df, donation_column: str, point_type) -> list: def marginal_rate_at(df, donation_column: str, donation: float) -> float: """The sweep's marginal savings rate at the grid point nearest ``donation``. It is a central difference over the grid, so at a kink - it averages the rates on either side.""" + it averages the rates on either side. The US rate comes from + ``next_dollar_rate`` instead.""" idx = np.abs(df[donation_column].values - donation).argmin() return float(df["marginal_savings"].iloc[idx]) +# The step of the "Saved on the next $1" rate. Taxes come back as float32, +# whose rounding grows with the tax, and a smaller step turns more of it +# into rate: at $1, a $75,000 earner's 5% read 5.08%; at $10, a $3 million +# earner's 37.7% read 38.8% (policyengine-us 2.156.4). At $100 the +# measured error was 0.02 point at $355,000 of net tax and 0.25 point at +# $3.8 million. A gift less than $100 below a kink gets a blend of the +# rates on either side. +NEXT_DOLLARS = 100 + + +def next_dollar_rate( + at_donation: PointMetrics, after_next: PointMetrics +) -> float: + """What each of the next ``NEXT_DOLLARS`` of the gift saves in tax: + the forward (right-hand) rate at the gift, so a gift on a kink gets + the rate above it.""" + return (at_donation.net_tax - after_next.net_tax) / NEXT_DOLLARS + + @app.post("/api/calculate", response_model=CalculateResponse) def calculate_donation(request: CalculateRequest): """Calculate tax impact of a charitable donation. Returns tax savings, marginal rates, and full donation curve data. - Runs three simulations: $0, the donation, and the donation sweep. + Runs four simulations: $0, the donation, the donation plus + ``NEXT_DOLLARS`` (for the next-dollar rate), and the donation sweep. """ try: gift = request.donation_amount @@ -408,8 +429,13 @@ def calculate_donation(request: CalculateRequest): curve = None if request.household is None: curve = start_curve("us", situation) - baseline, at_donation = point_metrics_many( - "us", [(situation, 0), (situation, gift)] + baseline, at_donation, after_next = point_metrics_many( + "us", + [ + (situation, 0), + (situation, gift), + (situation, gift + NEXT_DOLLARS), + ], ) if curve is None: curve = start_curve( @@ -424,9 +450,7 @@ def calculate_donation(request: CalculateRequest): baseline_net_tax=baseline.net_tax, net_tax_at_donation=at_donation.net_tax, tax_savings=baseline.net_tax - at_donation.net_tax, - marginal_savings_rate=marginal_rate_at( - df, "charitable_cash_donations", request.donation_amount - ), + marginal_savings_rate=next_dollar_rate(at_donation, after_next), baseline_net_income=baseline.household_net_income, net_income_after_donation=at_donation.household_net_income - request.donation_amount, diff --git a/frontend/src/components/__tests__/Faq.test.tsx b/frontend/src/components/__tests__/Faq.test.tsx index 3730f37..b9af099 100644 --- a/frontend/src/components/__tests__/Faq.test.tsx +++ b/frontend/src/components/__tests__/Faq.test.tsx @@ -166,7 +166,7 @@ describe("FAQ", () => { "If you itemize, the federal deduction for cash gifts to qualifying public charities is generally limited to 60% of your adjusted gross income for the year. Giving more than the limit adds no deduction for that year. From 2026, itemizers then subtract 0.5% of that income from the gifts the percentage limits allow.", ); expect(answer("Why did my gift save little or nothing?")).toContain( - "“Saved on the next $1” estimates the tax savings per dollar near your gift.", + "“Saved on the next $1” is the tax each extra dollar saves, averaged over the next $100 above your gift.", ); expect(answer("What does GiveCalc leave out?")).toContain( "For itemizers, federal law lets you carry eligible gifts above the annual deduction limit forward for up to five years;", diff --git a/frontend/src/components/faq/questions.tsx b/frontend/src/components/faq/questions.tsx index 8fdd02a..4ce278a 100644 --- a/frontend/src/components/faq/questions.tsx +++ b/frontend/src/components/faq/questions.tsx @@ -143,7 +143,8 @@ export const FAQ_ITEMS: FaqItem[] = [ then subtract{" "} {formatPercent(us.itemizer_floor_share_of_agi, 1)} of that income from the gifts the percentage limits allow. In your results, “Saved on - the next $1” estimates the tax savings per dollar near your gift. + the next $1” is the tax each extra dollar saves, averaged over the + next $100 above your gift. {/* 26 U.S.C. 170(b)(1)(G) and (H) define the cash limit and contribution base; (b)(1)(I), the floor on gifts otherwise allowable. */} diff --git a/tests/test_household_payload.py b/tests/test_household_payload.py index f16f943..db23d68 100644 --- a/tests/test_household_payload.py +++ b/tests/test_household_payload.py @@ -40,7 +40,7 @@ from policyengine_us import Simulation # noqa: E402 from policyengine_us.system import system # noqa: E402 -from api.main import _printable, app # noqa: E402 +from api.main import NEXT_DOLLARS, _printable, app # noqa: E402 from api.simulations import clear_caches # noqa: E402 from givecalc import create_situation # noqa: E402 from givecalc.calculations.tax import calculate_donation_metrics # noqa: E402 @@ -145,10 +145,10 @@ def test_both_request_shapes_agree_at_the_endpoint(fixture): assert new.json()[key] == pytest.approx( old.json()[key], abs=TOLERANCE ), key - # The curves' grids differ when benefits raise the top, so the rate is - # compared loosely: the same bracket, not the same grid point. + # The next-dollar rate is the difference of two point runs, the gift + # and NEXT_DOLLARS above it, each within TOLERANCE as above. assert new.json()["marginal_savings_rate"] == pytest.approx( - old.json()["marginal_savings_rate"], abs=0.02 + old.json()["marginal_savings_rate"], abs=2 * TOLERANCE / NEXT_DOLLARS ) diff --git a/tests/test_next_dollar_rate.py b/tests/test_next_dollar_rate.py new file mode 100644 index 0000000..f2c6b68 --- /dev/null +++ b/tests/test_next_dollar_rate.py @@ -0,0 +1,111 @@ +"""The "Saved on the next $1" rate is the forward rate at the gift. + +/api/calculate's ``marginal_savings_rate`` is what the next dollars of a +gift save: (net tax at the gift - net tax at the gift plus +``NEXT_DOLLARS``) / ``NEXT_DOLLARS``, from two point runs. It used to be +the donation sweep's central difference at the nearest grid point, which +averages the rates on either side of a kink. A gift that sits on a kink, +such as $1,000 for a single filer who takes the standard deduction (the +26 U.S.C. 170(p) cap), then showed a rate it gets on neither side. + +The households are those of GiveCalc's Giving Tuesday 2026 posts: a single +30-year-old with $75,000 in wages, built as the wizard builds it, giving +$1,000 in 2026. In Texas the next dollar saves nothing: the 170(p) +deduction is used up, and Texas has no income tax. In Massachusetts it +saves 5%, the Part B charitable deduction. The live site showed 14.7% and +19.7% (2026-12-01). + +Invariants: +- On a kink, the rate is the right-hand rate: TX 0%, MA 5% for a single + filer at $1,000 and a joint filer at $2,000. +- Off a kink, the rate is the bracket's: 22% federal for the Texan at + $500, below the cap. +- Identity: the rate equals the change in /api/savings' tax savings from + the gift to the gift plus ``NEXT_DOLLARS``, divided by ``NEXT_DOLLARS``. +""" + +import copy + +import pytest +from fastapi.testclient import TestClient + +from api.main import NEXT_DOLLARS, app +from api.simulations import clear_caches + +client = TestClient(app) + + +def wizard_body(state, gift, wages=75_000, married=False, year=2026): + """The request the wizard sends for a 30-year-old earner (and spouse).""" + y = str(year) + members = ["adult-1", "adult-2"] if married else ["adult-1"] + people = { + member: {"age": {y: 30}, "is_tax_unit_dependent": {y: False}} + for member in members + } + people["adult-1"]["employment_income"] = {y: wages} + return { + "donation_amount": gift, + "year": year, + "household": { + "people": people, + "families": {"family": {"members": members}}, + "marital_units": ( + {"marital_unit": {"members": members}} if married else {} + ), + "tax_units": {"tax_unit": {"members": members}}, + "spm_units": {"spm_unit": {"members": members}}, + "households": { + "household": {"members": members, "state_name": {y: state}} + }, + }, + } + + +def post(path, body): + response = client.post(path, json=body) + assert response.status_code == 200, response.text + return response.json() + + +def rate(body): + clear_caches() + return post("/api/calculate", body)["marginal_savings_rate"] + + +@pytest.mark.parametrize( + "state,married,gift,expected", + [ + # On the 170(p) cap ($1,000 single, $2,000 joint): federal 0%. + ("TX", False, 1_000, 0.0), + ("MA", False, 1_000, 0.05), + ("TX", True, 2_000, 0.0), + ("MA", True, 2_000, 0.05), + # Below the cap: the 22% bracket, and no Texas income tax. + ("TX", False, 500, 0.22), + ], + ids=[ + "TX single at the $1,000 cap", + "MA single at the $1,000 cap", + "TX joint at the $2,000 cap", + "MA joint at the $2,000 cap", + "TX single below the cap", + ], +) +def test_next_dollar_rate_is_the_forward_rate(state, married, gift, expected): + wages = 120_000 if married else 75_000 + body = wizard_body(state, gift, wages=wages, married=married) + assert rate(body) == pytest.approx(expected, abs=0.001) + + +@pytest.mark.parametrize("state", ["TX", "MA"]) +def test_next_dollar_rate_matches_the_savings_endpoint(state): + body = wizard_body(state, 1_000) + more = copy.deepcopy(body) + more["donation_amount"] += NEXT_DOLLARS + clear_caches() + savings = post("/api/savings", body)["tax_savings"] + savings_more = post("/api/savings", more)["tax_savings"] + assert rate(body) == pytest.approx( + (savings_more - savings) / NEXT_DOLLARS, abs=1e-6 + ) From 83f8269c38440099cb00aa076dc2d4476f0cdabd Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 10:43:11 -0500 Subject: [PATCH 2/3] Widen the next-dollar window for large tax bills policyengine-us returns taxes as float32, whose spacing grows with the tax. Over a fixed $100 window, a $100 million earner's 35% read 32% and a $25 million earner's 37.7% read 39.0%, worse than the old sweep figure. The window is now $100, or 2,000 float32 spacings of the net tax when that is wider ($125 from $524,288 of net tax, $8,000 at $40 million). A wider window costs one more point run, alongside the sweep. The FAQ states the window from faqRules.json, which a test ties to the API. Comments in App.tsx, headlineFirst.ts and CLAUDE.md now say where the card's rate comes from. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 9 +++- api/main.py | 49 +++++++++++++------ frontend/src/App.tsx | 4 +- .../src/components/__tests__/Faq.test.tsx | 2 +- frontend/src/components/faq/questions.tsx | 3 +- frontend/src/lib/faqRules.json | 3 +- frontend/src/lib/headlineFirst.ts | 3 +- tests/test_faq_numbers.py | 13 ++++- tests/test_next_dollar_rate.py | 46 +++++++++++++++-- 9 files changed, 104 insertions(+), 28 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4febf77..510a3b4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -178,12 +178,19 @@ All entities must have consistent member lists. ### Marginal tax savings -Calculated using numpy's gradient on the backend: +The curve's rate, which the marginal chart plots, uses numpy's gradient: ```python df["marginal_savings"] = -np.gradient(df.income_tax_after_donations) / \ np.gradient(df[donation_column]) ``` +The "Saved on the next $1" card shows `/api/calculate`'s +`marginal_savings_rate`, which for the US is `next_dollar_rate` in +`api/main.py`: the forward rate over a window above the gift ($100, wider +for large tax bills, where float32 rounding would show). A central +difference averages the rates on either side of a kink, such as the +$1,000 non-itemizer cap. + ## Household wizard The US form uses `policyengine-household-wizard`'s primitives and US draft, and diff --git a/api/main.py b/api/main.py index 022f2ca..5c6fe0c 100644 --- a/api/main.py +++ b/api/main.py @@ -394,23 +394,37 @@ def marginal_rate_at(df, donation_column: str, donation: float) -> float: return float(df["marginal_savings"].iloc[idx]) -# The step of the "Saved on the next $1" rate. Taxes come back as float32, -# whose rounding grows with the tax, and a smaller step turns more of it -# into rate: at $1, a $75,000 earner's 5% read 5.08%; at $10, a $3 million -# earner's 37.7% read 38.8% (policyengine-us 2.156.4). At $100 the -# measured error was 0.02 point at $355,000 of net tax and 0.25 point at -# $3.8 million. A gift less than $100 below a kink gets a blend of the -# rates on either side. +# The "Saved on the next $1" rate averages what the dollars just above the +# gift save, over a window of NEXT_DOLLARS or more. policyengine-us returns +# taxes as float32, whose spacing grows with the tax (about $0.002 at +# $16,000, $4 at $40 million), and the two runs' difference carries a +# spacing or so of rounding, which the window divides. Measured at +# policyengine-us 2.156.4: a $1 window read a $75,000 earner's 5% as 5.08%, +# and a $100 window read a $100 million earner's 35% as 32%. So the window +# is NEXT_DOLLARS, or SPACINGS_PER_WINDOW float32 spacings of the net tax +# when that is wider, which keeps each spacing of rounding to 0.05 point. +# A gift less than one window below a kink gets a blend of the rates on +# either side. NEXT_DOLLARS = 100 +SPACINGS_PER_WINDOW = 2_000 + + +def next_dollar_window(net_tax: float) -> float: + """The window above the gift that the next-dollar rate averages over: + ``NEXT_DOLLARS``, or ``SPACINGS_PER_WINDOW`` float32 spacings of + ``net_tax`` when that is wider ($125 from $524,288 of net tax, doubling + with each doubling of the tax: $8,000 at $40 million).""" + spacing = float(np.spacing(np.float32(abs(net_tax)))) + return max(float(NEXT_DOLLARS), SPACINGS_PER_WINDOW * spacing) def next_dollar_rate( - at_donation: PointMetrics, after_next: PointMetrics + at_donation: PointMetrics, after_window: PointMetrics, window: float ) -> float: - """What each of the next ``NEXT_DOLLARS`` of the gift saves in tax: - the forward (right-hand) rate at the gift, so a gift on a kink gets - the rate above it.""" - return (at_donation.net_tax - after_next.net_tax) / NEXT_DOLLARS + """What each dollar in the ``window`` above the gift saves in tax: the + forward (right-hand) rate at the gift, so a gift on a kink gets the + rate above it.""" + return (at_donation.net_tax - after_window.net_tax) / window @app.post("/api/calculate", response_model=CalculateResponse) @@ -420,6 +434,8 @@ def calculate_donation(request: CalculateRequest): Returns tax savings, marginal rates, and full donation curve data. Runs four simulations: $0, the donation, the donation plus ``NEXT_DOLLARS`` (for the next-dollar rate), and the donation sweep. + When the net tax calls for a wider window (``next_dollar_window``), a + fifth runs at the donation plus that window, alongside the sweep. """ try: gift = request.donation_amount @@ -429,7 +445,7 @@ def calculate_donation(request: CalculateRequest): curve = None if request.household is None: curve = start_curve("us", situation) - baseline, at_donation, after_next = point_metrics_many( + baseline, at_donation, after_window = point_metrics_many( "us", [ (situation, 0), @@ -441,6 +457,9 @@ def calculate_donation(request: CalculateRequest): curve = start_curve( "us", with_curve_top(request, situation, baseline, gift) ) + window = next_dollar_window(at_donation.net_tax) + if window > NEXT_DOLLARS: + after_window = point_metrics("us", situation, gift + window) df = add_net_income_columns( curve_result(curve), baseline_metrics_dict(baseline) ) @@ -450,7 +469,9 @@ def calculate_donation(request: CalculateRequest): baseline_net_tax=baseline.net_tax, net_tax_at_donation=at_donation.net_tax, tax_savings=baseline.net_tax - at_donation.net_tax, - marginal_savings_rate=next_dollar_rate(at_donation, after_next), + marginal_savings_rate=next_dollar_rate( + at_donation, after_window, window + ), baseline_net_income=baseline.household_net_income, net_income_after_donation=at_donation.household_net_income - request.donation_amount, diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 20a690f..7424d5b 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -293,8 +293,8 @@ function Calculator() { if (!cached?.headline) setPublished(null); setCurveStatus(null); - // The headline first, from two simulations; then the curve and the - // marginal rate, from the donation sweep. + // The headline first, from two simulations; then the curve, from the + // donation sweep, and the next-dollar rate, from a run above the gift. await fetchHeadlineFirst({ cachedHeadline: cached?.headline, fetchHeadline: () => savingsMutation.mutateAsync(request), diff --git a/frontend/src/components/__tests__/Faq.test.tsx b/frontend/src/components/__tests__/Faq.test.tsx index b9af099..08a56ad 100644 --- a/frontend/src/components/__tests__/Faq.test.tsx +++ b/frontend/src/components/__tests__/Faq.test.tsx @@ -166,7 +166,7 @@ describe("FAQ", () => { "If you itemize, the federal deduction for cash gifts to qualifying public charities is generally limited to 60% of your adjusted gross income for the year. Giving more than the limit adds no deduction for that year. From 2026, itemizers then subtract 0.5% of that income from the gifts the percentage limits allow.", ); expect(answer("Why did my gift save little or nothing?")).toContain( - "“Saved on the next $1” is the tax each extra dollar saves, averaged over the next $100 above your gift.", + "“Saved on the next $1” is the tax each extra dollar saves, averaged over the next $100 above your gift, or over a wider range when your tax bill tops about $500,000.", ); expect(answer("What does GiveCalc leave out?")).toContain( "For itemizers, federal law lets you carry eligible gifts above the annual deduction limit forward for up to five years;", diff --git a/frontend/src/components/faq/questions.tsx b/frontend/src/components/faq/questions.tsx index 4ce278a..ee16732 100644 --- a/frontend/src/components/faq/questions.tsx +++ b/frontend/src/components/faq/questions.tsx @@ -144,7 +144,8 @@ export const FAQ_ITEMS: FaqItem[] = [ {formatPercent(us.itemizer_floor_share_of_agi, 1)} of that income from the gifts the percentage limits allow. In your results, “Saved on the next $1” is the tax each extra dollar saves, averaged over the - next $100 above your gift. + next {usd(us.next_dollars)} above your gift, or over a wider range + when your tax bill tops about $500,000. {/* 26 U.S.C. 170(b)(1)(G) and (H) define the cash limit and contribution base; (b)(1)(I), the floor on gifts otherwise allowable. */} diff --git a/frontend/src/lib/faqRules.json b/frontend/src/lib/faqRules.json index a7d6901..26f4033 100644 --- a/frontend/src/lib/faqRules.json +++ b/frontend/src/lib/faqRules.json @@ -5,7 +5,8 @@ "itemizer_floor_share_of_agi": 0.005, "cash_gift_limit_share_of_agi": 0.6, "top_bracket_rate": 0.37, - "top_bracket_limit": { "numerator": 2, "denominator": 37 } + "top_bracket_limit": { "numerator": 2, "denominator": 37 }, + "next_dollars": 100 }, "uk": { "year": 2026, diff --git a/frontend/src/lib/headlineFirst.ts b/frontend/src/lib/headlineFirst.ts index 9417cb2..e33020b 100644 --- a/frontend/src/lib/headlineFirst.ts +++ b/frontend/src/lib/headlineFirst.ts @@ -2,7 +2,8 @@ * Fetch the headline, show it, then fetch the full result with the curve. * * The headline (/api/savings) runs two simulations; the full result - * (/api/calculate) adds the donation sweep. Showing the headline first puts + * (/api/calculate) adds the donation sweep and a run above the gift for the + * next-dollar rate. Showing the headline first puts * the answer on screen while the charts load. */ diff --git a/tests/test_faq_numbers.py b/tests/test_faq_numbers.py index 9dbe812..bd9cb8d 100644 --- a/tests/test_faq_numbers.py +++ b/tests/test_faq_numbers.py @@ -12,7 +12,8 @@ - The file records the model versions modal_app.py deploys, which are the ones installed here. - Each rule the FAQ states equals its PolicyEngine parameter in the year - the FAQ names. + the FAQ names, and the next-dollar window it states equals the API's, + widening from about $500,000 of net tax as it says. - The Florida example's reasons hold in the model: no state or local income tax, adjusted gross income equal to wages, each $10,000 step saving at the rate of the bracket its taxable income stays in, and a deduction that stops @@ -31,7 +32,7 @@ import pytest from fastapi.testclient import TestClient -from api.main import app, us_situation +from api.main import NEXT_DOLLARS, app, next_dollar_window, us_situation from api.schemas import SavingsRequest from api.simulations import clear_caches from givecalc.core.simulation import create_donation_simulation @@ -118,6 +119,14 @@ def test_us_rules_match_policyengine_us(): assert not before.deductions.itemized.limitation.obbb.applies +def test_next_dollar_window_matches_the_api(): + """The FAQ: "averaged over the next $100 above your gift, or over a + wider range when your tax bill tops about $500,000".""" + assert RULES["us"]["next_dollars"] == NEXT_DOLLARS + assert next_dollar_window(500_000) == NEXT_DOLLARS + assert next_dollar_window(550_000) > NEXT_DOLLARS + + def test_uk_rules_match_policyengine_uk(): from policyengine_uk.system import system from policyengine_uk.utils.income_tax import ( diff --git a/tests/test_next_dollar_rate.py b/tests/test_next_dollar_rate.py index f2c6b68..10ffda0 100644 --- a/tests/test_next_dollar_rate.py +++ b/tests/test_next_dollar_rate.py @@ -1,10 +1,12 @@ """The "Saved on the next $1" rate is the forward rate at the gift. /api/calculate's ``marginal_savings_rate`` is what the next dollars of a -gift save: (net tax at the gift - net tax at the gift plus -``NEXT_DOLLARS``) / ``NEXT_DOLLARS``, from two point runs. It used to be -the donation sweep's central difference at the nearest grid point, which -averages the rates on either side of a kink. A gift that sits on a kink, +gift save: (net tax at the gift - net tax a window above it) / the window, +from two point runs. The window is ``NEXT_DOLLARS``, wider for a net tax +large enough that float32 rounding would show (``next_dollar_window``). + +The rate used to be the donation sweep's central difference at the +nearest grid point, which averages the rates on either side of a kink. A gift that sits on a kink, such as $1,000 for a single filer who takes the standard deduction (the 26 U.S.C. 170(p) cap), then showed a rate it gets on neither side. @@ -22,14 +24,23 @@ $500, below the cap. - Identity: the rate equals the change in /api/savings' tax savings from the gift to the gift plus ``NEXT_DOLLARS``, divided by ``NEXT_DOLLARS``. +- Rounding: the window is at least ``SPACINGS_PER_WINDOW`` float32 spacings + of the net tax, so a $100 million earner's 35% (37% less the 2/37 + limit) reads 35%, not the 32% a $100 window gave. """ import copy +import numpy as np import pytest from fastapi.testclient import TestClient -from api.main import NEXT_DOLLARS, app +from api.main import ( + NEXT_DOLLARS, + SPACINGS_PER_WINDOW, + app, + next_dollar_window, +) from api.simulations import clear_caches client = TestClient(app) @@ -109,3 +120,28 @@ def test_next_dollar_rate_matches_the_savings_endpoint(state): assert rate(body) == pytest.approx( (savings_more - savings) / NEXT_DOLLARS, abs=1e-6 ) + + +@pytest.mark.parametrize( + "net_tax,window", + [ + (13_187.50, 100), + (-5_000, 100), + (524_287, 100), + (524_288, 125), + (3_800_000, 500), + (39_000_000, 8_000), + ], +) +def test_window_grows_with_the_float32_spacing(net_tax, window): + assert next_dollar_window(net_tax) == window + spacing = float(np.spacing(np.float32(abs(net_tax)))) + assert next_dollar_window(net_tax) >= SPACINGS_PER_WINDOW * spacing + + +def test_a_large_tax_bill_gets_a_wider_window(): + """Net tax near $39 million: float32 spacing is $4, so a $100 window + read 32%. The top bracket's 37%, less the 2/37 limit on itemized + deductions, is 35%.""" + body = wizard_body("TX", 1_000_000, wages=100_000_000) + assert rate(body) == pytest.approx(0.35, abs=0.002) From bfcda89e35d32defd494bd9ad05f99a3d6cd6f72 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 15:34:12 -0500 Subject: [PATCH 3/3] Label the card as an average over the next $100 Round 1 of the review (a Codex cloud review at 83f8269) found the card promised the next $1 while showing the average over a $100 window: a Texan giving $925 saves 22% on the next $75 and 0% after the cap, so the card read 16.5%. The card now reads "Average savings per extra dollar", "Change in net taxes if you give a little more", and the FAQ says the figure is the reduction in net taxes per dollar over the next $100, how the range widens, and what a negative rate means. Also from the review: the FAQ threshold uses the magnitude of net tax (a -550,000 check), a comment notes that intermediate rounding can still move the displayed figure, and the float32 spacing example is corrected. A test pins the $925 blend. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 10 +++--- api/main.py | 11 +++---- frontend/src/components/Results.tsx | 4 +-- .../src/components/__tests__/Faq.test.tsx | 2 +- .../__tests__/Results.headlineFirst.test.tsx | 1 + frontend/src/components/faq/questions.tsx | 10 +++--- tests/test_faq_numbers.py | 4 +-- tests/test_next_dollar_rate.py | 31 ++++++++++++------- 8 files changed, 41 insertions(+), 32 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 510a3b4..bcfcd67 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -184,12 +184,12 @@ df["marginal_savings"] = -np.gradient(df.income_tax_after_donations) / \ np.gradient(df[donation_column]) ``` -The "Saved on the next $1" card shows `/api/calculate`'s +The "Average savings per extra dollar" card shows `/api/calculate`'s `marginal_savings_rate`, which for the US is `next_dollar_rate` in -`api/main.py`: the forward rate over a window above the gift ($100, wider -for large tax bills, where float32 rounding would show). A central -difference averages the rates on either side of a kink, such as the -$1,000 non-itemizer cap. +`api/main.py`. This averages net tax savings per dollar over a window +above the gift ($100, wider for large absolute net taxes to reduce float32 +rounding). A central difference averages the rates on either side of a +kink, such as the $1,000 non-itemizer cap. ## Household wizard diff --git a/api/main.py b/api/main.py index 5c6fe0c..a31b6da 100644 --- a/api/main.py +++ b/api/main.py @@ -394,15 +394,16 @@ def marginal_rate_at(df, donation_column: str, donation: float) -> float: return float(df["marginal_savings"].iloc[idx]) -# The "Saved on the next $1" rate averages what the dollars just above the -# gift save, over a window of NEXT_DOLLARS or more. policyengine-us returns +# The US card averages net tax savings per dollar over a window of +# NEXT_DOLLARS or more above the gift. policyengine-us returns # taxes as float32, whose spacing grows with the tax (about $0.002 at -# $16,000, $4 at $40 million), and the two runs' difference carries a +# $17,000, $4 at $40 million), and the two runs' difference carries a # spacing or so of rounding, which the window divides. Measured at # policyengine-us 2.156.4: a $1 window read a $75,000 earner's 5% as 5.08%, # and a $100 window read a $100 million earner's 35% as 32%. So the window # is NEXT_DOLLARS, or SPACINGS_PER_WINDOW float32 spacings of the net tax # when that is wider, which keeps each spacing of rounding to 0.05 point. +# The model's intermediate rounding can still affect the displayed rate. # A gift less than one window below a kink gets a blend of the rates on # either side. NEXT_DOLLARS = 100 @@ -421,9 +422,7 @@ def next_dollar_window(net_tax: float) -> float: def next_dollar_rate( at_donation: PointMetrics, after_window: PointMetrics, window: float ) -> float: - """What each dollar in the ``window`` above the gift saves in tax: the - forward (right-hand) rate at the gift, so a gift on a kink gets the - rate above it.""" + """Average net tax savings per dollar over the window above the gift.""" return (at_donation.net_tax - after_window.net_tax) / window diff --git a/frontend/src/components/Results.tsx b/frontend/src/components/Results.tsx index b767cb2..9dc7526 100644 --- a/frontend/src/components/Results.tsx +++ b/frontend/src/components/Results.tsx @@ -280,9 +280,9 @@ export default function Results({ description="Federal, state and local" /> )} diff --git a/frontend/src/components/__tests__/Faq.test.tsx b/frontend/src/components/__tests__/Faq.test.tsx index 08a56ad..cd23b65 100644 --- a/frontend/src/components/__tests__/Faq.test.tsx +++ b/frontend/src/components/__tests__/Faq.test.tsx @@ -166,7 +166,7 @@ describe("FAQ", () => { "If you itemize, the federal deduction for cash gifts to qualifying public charities is generally limited to 60% of your adjusted gross income for the year. Giving more than the limit adds no deduction for that year. From 2026, itemizers then subtract 0.5% of that income from the gifts the percentage limits allow.", ); expect(answer("Why did my gift save little or nothing?")).toContain( - "“Saved on the next $1” is the tax each extra dollar saves, averaged over the next $100 above your gift, or over a wider range when your tax bill tops about $500,000.", + "“Average savings per extra dollar” is the reduction in net taxes per dollar over the next $100 above your gift. The range widens when the gap between your taxes and benefits at your gift is about $500,000 or more. A negative rate means giving more increases net taxes.", ); expect(answer("What does GiveCalc leave out?")).toContain( "For itemizers, federal law lets you carry eligible gifts above the annual deduction limit forward for up to five years;", diff --git a/frontend/src/components/__tests__/Results.headlineFirst.test.tsx b/frontend/src/components/__tests__/Results.headlineFirst.test.tsx index ca0fed7..bce7b09 100644 --- a/frontend/src/components/__tests__/Results.headlineFirst.test.tsx +++ b/frontend/src/components/__tests__/Results.headlineFirst.test.tsx @@ -62,6 +62,7 @@ describe("Results - headline before the curve", () => { it("fills in the marginal rate and charts when the curve arrives", () => { render(); expect(screen.getByText("$1,589")).toBeInTheDocument(); + expect(screen.getByText("Average savings per extra dollar")).toBeInTheDocument(); expect(screen.getByText("28.4%")).toBeInTheDocument(); expect(screen.getByTestId("tax-chart")).toBeInTheDocument(); expect(screen.getByTestId("marginal-chart")).toBeInTheDocument(); diff --git a/frontend/src/components/faq/questions.tsx b/frontend/src/components/faq/questions.tsx index ee16732..d80f0bd 100644 --- a/frontend/src/components/faq/questions.tsx +++ b/frontend/src/components/faq/questions.tsx @@ -142,10 +142,12 @@ export const FAQ_ITEMS: FaqItem[] = [ limit adds no deduction for that year. From {us.year}, itemizers then subtract{" "} {formatPercent(us.itemizer_floor_share_of_agi, 1)} of that income - from the gifts the percentage limits allow. In your results, “Saved on - the next $1” is the tax each extra dollar saves, averaged over the - next {usd(us.next_dollars)} above your gift, or over a wider range - when your tax bill tops about $500,000. + from the gifts the percentage limits allow. In your results, + “Average savings per extra dollar” is the reduction in net taxes per + dollar over the next {usd(us.next_dollars)} above your gift. The range + widens when the gap between your taxes and benefits at your gift is + about $500,000 or more. A negative rate means giving more increases + net taxes. {/* 26 U.S.C. 170(b)(1)(G) and (H) define the cash limit and contribution base; (b)(1)(I), the floor on gifts otherwise allowable. */} diff --git a/tests/test_faq_numbers.py b/tests/test_faq_numbers.py index bd9cb8d..12da260 100644 --- a/tests/test_faq_numbers.py +++ b/tests/test_faq_numbers.py @@ -120,11 +120,11 @@ def test_us_rules_match_policyengine_us(): def test_next_dollar_window_matches_the_api(): - """The FAQ: "averaged over the next $100 above your gift, or over a - wider range when your tax bill tops about $500,000".""" + """The FAQ's $100 window widens for large net taxes or net benefits.""" assert RULES["us"]["next_dollars"] == NEXT_DOLLARS assert next_dollar_window(500_000) == NEXT_DOLLARS assert next_dollar_window(550_000) > NEXT_DOLLARS + assert next_dollar_window(-550_000) > NEXT_DOLLARS def test_uk_rules_match_policyengine_uk(): diff --git a/tests/test_next_dollar_rate.py b/tests/test_next_dollar_rate.py index 10ffda0..c1fca7b 100644 --- a/tests/test_next_dollar_rate.py +++ b/tests/test_next_dollar_rate.py @@ -1,14 +1,16 @@ -"""The "Saved on the next $1" rate is the forward rate at the gift. +"""The US card shows average net tax savings per extra dollar. -/api/calculate's ``marginal_savings_rate`` is what the next dollars of a -gift save: (net tax at the gift - net tax a window above it) / the window, -from two point runs. The window is ``NEXT_DOLLARS``, wider for a net tax -large enough that float32 rounding would show (``next_dollar_window``). +/api/calculate's ``marginal_savings_rate`` is the reduction in net taxes +per dollar over a window above the gift: (net tax at the gift - net tax a +window above it) / the window, from two point runs. The window is +``NEXT_DOLLARS``, wider for a net tax large enough that float32 rounding +would show (``next_dollar_window``). The rate used to be the donation sweep's central difference at the -nearest grid point, which averages the rates on either side of a kink. A gift that sits on a kink, -such as $1,000 for a single filer who takes the standard deduction (the -26 U.S.C. 170(p) cap), then showed a rate it gets on neither side. +nearest grid point, which averages the rates on either side of a kink. A +gift that sits on a kink, such as $1,000 for a single filer who takes the +standard deduction (the 26 U.S.C. 170(p) cap), then showed a rate it gets +on neither side. The households are those of GiveCalc's Giving Tuesday 2026 posts: a single 30-year-old with $75,000 in wages, built as the wizard builds it, giving @@ -18,10 +20,12 @@ 19.7% (2026-12-01). Invariants: -- On a kink, the rate is the right-hand rate: TX 0%, MA 5% for a single - filer at $1,000 and a joint filer at $2,000. -- Off a kink, the rate is the bracket's: 22% federal for the Texan at - $500, below the cap. +- A window starting at the non-itemizer cap sees only the rates above the + cap: TX 0%, MA 5% for a single filer at $1,000 and a joint filer at + $2,000. +- A window starting at $500 in Texas sees only the 22% federal rate. +- A window that crosses the cap averages the rates on either side, as the + card and FAQ say: TX at $925 saves 22% on $75 and 0% on $25, 16.5%. - Identity: the rate equals the change in /api/savings' tax savings from the gift to the gift plus ``NEXT_DOLLARS``, divided by ``NEXT_DOLLARS``. - Rounding: the window is at least ``SPACINGS_PER_WINDOW`` float32 spacings @@ -94,6 +98,8 @@ def rate(body): ("MA", True, 2_000, 0.05), # Below the cap: the 22% bracket, and no Texas income tax. ("TX", False, 500, 0.22), + # A window across the cap: $75 at 22%, $25 at 0%. + ("TX", False, 925, 0.165), ], ids=[ "TX single at the $1,000 cap", @@ -101,6 +107,7 @@ def rate(body): "TX joint at the $2,000 cap", "MA joint at the $2,000 cap", "TX single below the cap", + "TX single with the cap inside the window", ], ) def test_next_dollar_rate_is_the_forward_rate(state, married, gift, expected):