Skip to content

Calculate households through the dashboard API - #234

Merged
anth-volk merged 10 commits into
mainfrom
calls-through-dashboard-api
Nov 13, 2026
Merged

anth-volk merged 10 commits into
mainfrom
calls-through-dashboard-api

Conversation

@anth-volk

@anth-volk anth-volk commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #233

The reform analyzer's household calculations and its model-version read now go through @policyengine/api-client to www.policyengine.org's dashboard API, instead of calling the PolicyEngine Public API (api.policyengine.org) from the browser. The Public API will soon answer only PolicyEngine's own servers. Not stacked on another PR.

Change

src/hooks/usePolicyEngineAPI.js:

  • Calculations: runCalculation sends {country: "us", household}, plus policy: buildApiPolicy(reform) for the reform, through calculateHousehold.
    • The dashboard API forwards the household to the Public API's /us/calculate with policy: {} for the baseline, which the Public API reads the same as the old missing policy.
    • It still resolves as {status: "ok", message: null, result}, so ResultsDisplay reads .result as before.
    • Errors carry the dashboard API's or the Public API's message.
  • Model version: read with getMetadata("us"), cached for the page as before. A failure still gives null, which keeps a structural reform's household tab disabled.
  • New readModelVersion option: ReformAnalyzer sets it only for structural reforms, the only ones whose household tab depends on the model version. Other analyses no longer download the whole US metadata. Before, every analyzer mount did, and that download now passes through www.policyengine.org's server.

Deployment: modal_app.py's APP_VERSION goes from v41 to v42, so the Modal image rebuilds the app with this code. The build runs npm install without a lockfile, so it installs @policyengine/api-client from package.json.

Origins: readers use www.policyengine.org/us/bill-tracker, where these requests are same-origin and need nothing else. Direct visits to policyengine--state-legislative-tracker.modal.run are allowed by PolicyEngine/policyengine-app-v2#1552, merged and deployed on 2026-11-12.

Red-green runs

Each test was run alone with npx vitest run src/hooks/usePolicyEngineAPI.calls.test.js -t "<name>".

Test 972e0f7 3017476 6637964 33a0354
compareReform calculates both through the dashboard API failed on its assertion, exit 1 passed passed passed
compareReform resolves with each calculation's result failed on its assertion, exit 1 passed passed passed
reads the model version from the dashboard API's metadata failed on its assertion, exit 1 passed passed passed
the error carries its message failed on its assertion, exit 1 passed passed passed
a reform that needs no structural code reads no metadata — — failed on its assertion, exit 1 passed
the metadata read fails then the model version stays unknown — — passed (pins the existing fail-closed behaviour) passed

ESLint passes on the three changed source files. A production next build succeeds, and the exported out/ names no api.policyengine.org.

Browser check

On http://localhost:3115/UT/ut-sb60-bill (next dev --webpack, with the public Supabase URL and anon key from modal_app.py), "Your Household" → "Calculate Impact" with the default household:

  • At 3017476: GET https://www.policyengine.org/api/metadata/us and two POST https://www.policyengine.org/api/household/calculate, all 200.
  • At 33a0354: only the two calculations (200, 200), since SB60 is not a structural reform.
  • Neither sent anything to api.policyengine.org.
  • Both showed a change in household net income of −$25 a year.

The production page, which calls the Public API directly, showed the same: −$25, federal tax $3,820 in both, state tax $1,667 → $1,692.

Review

Two rounds of adversarial self-review, each in a fresh clone; neither found a bug.

  • Round 1: confirmed the request bodies, result shape, the model-version check and error handling, and that calculations run only on "Calculate Impact". Applied from it: reading the metadata only for structural reforms, a test for a failed version read, and a corrected comment.
  • Round 2: reviewed those changes. A structural reform's tab can't be enabled wrongly. Its version read now starts when the analysis opens, so the tab may enable a little later than before.

Rate-limit handling (added 2026-11-13)

www.policyengine.org's firewall allows each address 30 household calculations a minute. Over that it answers 429 with no CORS headers, so the Modal host sees a request with no answer instead. The policyengine-api-access skill asks a page refused for the limit to keep its last answer, say that everyone on the same network shares the limit, and send nothing more for a minute. These commits do that.

src/hooks/usePolicyEngineAPI.js:

  • Every client failure becomes a HouseholdCalculationError with status and rateLimited:
    • 429: "Everyone on your network, such as a workshop or an office, shares a limit on calculations a minute, and it has been reached."
    • No answer, on any origin but www.policyengine.org: "PolicyEngine's calculation service could not be reached. Everyone on your network, …, which may have been reached." A refused origin (403) looks the same there.
    • No answer on www.policyengine.org: a network failure ("…could not be reached. Check your connection and try again."), with no pause.
    • Anything else: the dashboard API's message, as before.
  • A rate-limited failure pauses household calculations for 60 seconds before it is rethrown, so the baseline–reform pair pauses even when Promise.all reports the other failure. The pause keeps the failure's message as its reason.
  • While paused, a calculation is refused without sending a request. Nothing retries.
  • useHouseholdCalculationPause() returns the seconds left and the reason, and counts down once a second.

ReformAnalyzer and HouseholdForm:

  • After a rate-limited refusal, the answer on screen stays, with "The results below are for the household calculated before." above it, until the next answer. No error box appears.
  • While paused, "Calculate Impact" is disabled and reads "Calculate again in N s". Below it, the refusal's message sits in a role="status" span, followed by "This page can calculate again in N s." When the minute ends, the button and notice return to normal.
  • Other failures are shown as before, and clear the answer.

Red-green runs

Each test was run alone with bunx vitest run <file> -t "<name>". Every test committed first failed on an assertion and passed after the code that followed it.

Tests commit Code commit Tests
97d6491 622ef81 9 hook tests in usePolicyEngineAPI.rateLimit.test.js (classification, pause, holding back, 504 message, ending a pause) and 3 component tests in ReformAnalyzer.rateLimit.test.jsx (answer kept with countdown; no answer yet; an earlier error's answer doesn't come back)
e290f7d 91cf6be the kept answer says it is for the household calculated before
92b6207 d0f7856 the notice gives the refusal's own message (3 changed, 2 new, including a baseline 500 followed by a reform 429)

ESLint on the changed files exits 0 (its one warning, on HouseholdForm's year-sync effect, is on main too). bun run build exits 0, and the exported files name no api.policyengine.org.

Browser check

On http://localhost:3115/UT/ut-sb60-bill at d0f7856:

  • "Calculate Impact" sent two calculations to www.policyengine.org (both 200) and showed −$25 a year.
  • With the page's requests to /api/household/calculate made to fail, which is how localhost sees the firewall's 429, the next click sent two requests and both were refused.
  • The −$25 answer stayed, with "The results below are for the household calculated before." There was no error box.
  • The button read "Calculate again in 59 s" and was disabled. The notice read "PolicyEngine's calculation service could not be reached. Everyone on your network, …, which may have been reached. This page can calculate again in 59 s."
  • At 622ef81 the button returned to "Calculate Impact", enabled, after the minute.

Review

Two rounds of adversarial self-review, each in a fresh clone:

  • Round 1 (622ef81): no bugs. Applied from it: the note above a kept answer.
  • Between rounds: across the four dashboards that got this change, the notice first showed only the shared-limit sentence. On the Modal host that hid the "could not be reached" information, so the notice now gives the refusal's own message.
  • Round 2 (d0f7856): no bugs. It confirmed all claims, including that a 400 still shows the dashboard API's message.

Left as it is

  • Sticky failed read: a failed version read stays cached for the page session, as before. After one 504 or firewall 429, structural reforms' household tabs stay disabled until a reload.
  • Untested:
    • ReformAnalyzer's wiring of readModelVersion (no component test);
    • a readable 429 on www.policyengine.org itself (the 429 tests run with the Modal host's origin);
    • that editing the form sends nothing.
  • Two calculations per click: each "Calculate Impact" sends a baseline and a reform calculation, also when the inputs haven't changed, so about eight clicks a minute pass the skill's 15-a-minute budget for one person. That was so before this PR.
  • Error box and notice together: if one calculation fails for another reason before the other is refused, the error box shows the first failure and the notice the refusal. Both are true, but the page doesn't say that one click sends two calculations.
  • After the minute: with no earlier answer, nothing shows that a refused click failed once the pause ends; the old error box stayed until the next calculation.
  • Screen readers: the role="status" span is added with its text already in it, which some screen readers don't announce.
  • Deployment check: the Modal build clones main itself and installs without a lockfile, so after merge the only check is that a served _tracker chunk contains /api/household/calculate and no api.policyengine.org.
  • Developer docs: the repository's .claude agent and command docs still tell developers to call the Public API directly.

Environment and secrets

No variable or secret is added or read. The client sends no credential (credentials: "omit"). The deployment change is the APP_VERSION bump only.

Variable or secret Provider Wiring Verified
MODAL_TOKEN_ID, MODAL_TOKEN_SECRET GitHub Actions repository secrets deploy.yml step env: on pushes to main, for modal deploy modal_app.py Both names exist; the last "Deploy to Modal" run (2026-10-30) succeeded
NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY, NEXT_PUBLIC_POSTHOG_KEY Literals in modal_app.py (public values) Set on the npm run build command in the image build (build time) Unchanged
SUPABASE_URL, SUPABASE_KEY, and the other runtime values Modal secret state-research-tracker-runtime Attached to the web function (run time) The secret exists in the policyengine workspace; its keys weren't read

🤖 Generated with Claude Code

anth-volk and others added 4 commits November 11, 2026 20:33
usePolicyEngineAPI posts the baseline and reform households to the
Public API's /us/calculate and reads its /us/metadata from the browser.
These tests fail until both go through www.policyengine.org's dashboard
API, with the same household and policy, and the results, model version
and error messages reach the page as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
usePolicyEngineAPI now sends the baseline and reform households, and its
model-version read, through @policyengine/api-client to
www.policyengine.org's dashboard API instead of the Public API. The
household and policy are the same, ResultsDisplay still reads each
answer's result, and errors still carry the message. The tracker's pages
are served from www.policyengine.org, so these are same-origin requests
there.

Bumps APP_VERSION so the Modal image rebuilds the app with this code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From review round 1: the model version gates only structural reforms,
but every analyzer mount streams the whole US metadata through
www.policyengine.org. The first test fails until the hook can skip that
read; the second pins that a failed read leaves the version unknown,
which keeps structural reforms' household tab disabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
usePolicyEngineAPI takes readModelVersion, and ReformAnalyzer passes it
only for structural reforms, the only ones gated on the deployed
policyengine-us version. Other analyses no longer download the whole US
metadata through www.policyengine.org. Also corrects the comment on the
shape runCalculation resolves with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk and others added 6 commits November 13, 2026 18:47
www.policyengine.org's firewall allows each IP address 30 household
calculations a minute and answers 429 over that limit, without CORS
headers. On www.policyengine.org the page reads the 429; on the tracker's
own Modal host the browser reports a network failure instead.

The hook tests check that a 429, or no answer on another origin, gives a
message explaining that everyone on the same network shares the limit,
marks the error as rate-limited, pauses calculations for a minute
(including when the other of the two parallel calculations failed first),
and holds back calculations during the pause without sending them; that
no answer on www.policyengine.org is reported as a network failure without
a pause; and that a 504 keeps its message, is sent once and does not pause.

The ReformAnalyzer tests check that after a rate-limited failure the last
answer stays on screen without the error box, and the Calculate button is
disabled and counts down beside a notice whose explanation alone has
role="status"; and that an answer already replaced by another failure's
error box does not come back.

All of these tests fail on their assertions until the handling is added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
www.policyengine.org's firewall allows each IP address 30 household
calculations a minute. Over that limit it answers 429 without CORS
headers, so the tracker reads the 429 when served from
www.policyengine.org, and sees a failed request (status null) when served
from its own Modal host.

usePolicyEngineAPI now classifies a failed calculation:
- 429: everyone on the network shares a limit on calculations a minute,
  and it has been reached.
- No answer on another origin: the calculation service could not be
  reached, and the shared limit may have been reached.
- No answer on www.policyengine.org: a network failure; check the
  connection and try again. No pause.
- Anything else keeps the dashboard API's own message.
The error is a HouseholdCalculationError with a rateLimited flag. A
failure the limit may have caused pauses household calculations for the
firewall's one-minute window at once, before the error is rethrown, so a
refusal of either of the two parallel calculations starts the pause.
During the pause a calculation is refused without sending a request. No
automatic retries are added.

The module exports SHARED_LIMIT_EXPLANATION, pauseHouseholdCalculations,
householdCalculationPauseRemaining, onHouseholdCalculationPause and a
useHouseholdCalculationPause hook that counts the pause down in seconds.

After a rate-limited failure the hook's error stays null, so
ReformAnalyzer keeps the last answer on screen instead of the error box.
While calculations are paused, HouseholdForm's Calculate button is
disabled and reads "Calculate again in N s", and a notice below it gives
the explanation (the only part with role="status") and the same
countdown. Another failure still shows its error box, and now also
forgets the answer it replaced, so that a later rate-limited failure
does not bring back an answer that was no longer on screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After a refusal for the dashboard API's rate limit, the page keeps the
answer it showed. The new test expects a note above it saying the
results are for the household calculated before, until the next answer
replaces them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After a refusal for the dashboard API's rate limit, the household tab
keeps the answer it showed. A note above it now says the results are
for the household calculated before, since the refused household may
differ. The next answer, or any other failure, removes the note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After review, the notice beside the Calculate button gives the message of
the rate-limited failure that started the pause, so that "could not be
reached" stays visible on hosts other than www.policyengine.org.

The pause test now checks that pauseHouseholdCalculations stores a reason,
the message "Everyone on your network, ..., which may have been reached."
by default, and that householdCalculationPauseReason returns it.

The ReformAnalyzer notice tests now expect the 429's message ("..., and it
has been reached.") in the role="status" element, followed by the
countdown. Two tests are new: on the tracker's own host a request with no
answer shows "PolicyEngine's calculation service could not be reached."
followed by the shared-limit explanation; and when the baseline fails for
another reason and the reform is refused for the limit afterwards, the
notice gives the refusal's message, which ReformAnalyzer never received.

These tests fail on their assertions until the reason is kept with the
pause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The notice beside the Calculate button gave only the shared-limit
explanation, so on hosts other than www.policyengine.org, such as the
tracker's Modal host, a request with no answer no longer said that the
calculation service could not be reached.

pauseHouseholdCalculations(milliseconds, reason) now stores the
user-facing message of the refusal that started the pause (by default
"Everyone on your network, ..., which may have been reached."), and
householdCalculationPauseReason() returns it. A rate-limited failure
passes its own message when it pauses calculations, so the notice gives
the right message even when ReformAnalyzer received the other parallel
calculation's failure first.

useHouseholdCalculationPause now returns { secondsRemaining, reason },
and HouseholdForm's notice reads "<reason> This page can calculate again
in N s.", with only the reason in the role="status" element. The error
box still does not appear for a rate-limited failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk
anth-volk merged commit 8f42e13 into main Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Calculate households through the dashboard API

1 participant