Skip to content

Calculate households on API v1 by submitting and polling (server helper) - #1613

Draft
anth-volk wants to merge 10 commits into
mainfrom
apiv2-d3-5-submit-and-poll
Draft

anth-volk wants to merge 10 commits into
mainfrom
apiv2-d3-5-submit-and-poll

Conversation

@anth-volk

Copy link
Copy Markdown
Collaborator

Fixes #1612

What this adds

A server-side helper in packages/public-api-forwarding, createHouseholdCalculator({ forwarder }).calculateHousehold(request, options). It calculates a household on API v1 without storing it, taking the same household and policy as API v1's synchronous POST /{country}/calculate:

  1. It submits {country_id, household, policy?, axes?, add_missing_variables?, spm?} to POST /v2/household-calculations. The household's axes go in the separate axes field, and the caller's object isn't changed. API v1 keeps the calculation as a household job only: no stored household, policy or user association.
  2. It reads GET /v2/household-calculations/{calculation_id} every 2 seconds until the calculation succeeds or fails. When the submission's answer already says it finished, it reads it at once.
  3. It gives up 10 minutes after the call starts (timeLimitMilliseconds). No wait runs past the deadline, and an accepted calculation is read at least once.

It resolves with the calculated household (what /calculate answered as result), plus warnings, spmConfig, spmProvenance, the calculation ID and the versions it ran with. It throws one of these:

  • HouseholdCalculationFailedError, for a failed job: its code, inputErrors and spmError.
  • HouseholdCalculationTimeoutError, when the limit passes: the calculation ID and the last status.
  • HouseholdCalculationRefusedError, for a refusal or an unreadable answer: the status, API v1's message and code, the body, Retry-After, and the observability and request IDs.
  • PublicApiUnavailableError, when API v1 can't be called.
  • The signal's reason, when the caller aborts.

Retries

Reads are retried until 90 seconds pass without a good answer. They are retried on 429, 502, 503 and 504, and when API v1 can't be reached, doesn't answer in time, its answer is lost, or the server credential can't be obtained.

The submission is retried only when API v1 can't have created the job:

  • on API v1's own 503 (with its JSON error body), which it answers when no job will run;
  • when the credential can't be obtained, so nothing was sent.

It is never retried after any other 503 (such as Cloud Run's), a 502, or a connection failure or timeout after sending, since a second submission would create a second job. Its timeout is the time left before the deadline, at least 30 seconds, so a request that waits for an API v1 instance to start isn't cut short.

Changes to the forwarder

  • fetchFromServer takes a signal. It rejects with the signal's reason as soon as the caller aborts, including while the server token is being fetched; that token request goes on, since other requests may be waiting on it.
  • PublicApiUnavailableError takes a reason: unknown_route, not_configured, credential_unavailable, unreachable, timed_out or answer_lost. requestMayHaveArrived follows from it. Only this package constructs the error.

How it differs from /calculate

  • There is no {status, message, result} envelope. warnings and spm_provenance are fields of the result.
  • Inputs the model doesn't recognise come back as a failed calculation (code: "invalid_inputs", inputErrors), not as a 400 with errors.
  • A call takes at least one submission and one read, and is bounded by the time limit rather than by API v1's 300-second request limit.

Not in this PR

  • The website route. Moving website/src/app/api/household/calculate/route.ts onto the helper is a separate change. That route will need to build /calculate's envelope from the result. It should also stream it, as forward does, to stay under Vercel's 4.5 MB limit for large axes results.
  • The inline form in API v1. API v1's /v2/household-calculations doesn't accept the inline household yet; that work is in progress separately. The request shape above is the one agreed for it.

Tests

The new tests run against a fake API v1, an injected fetchFromServer on a fake clock. Two of them use the helper's own timer under Vitest's fake timers. They cover:

  • submitting, several reads and success; failure; the time limit, including 0, fractions and Infinity;
  • each retry rule and each case that is not retried;
  • Retry-After; unreadable answers; lost bodies;
  • aborts during waits, requests, body reads and the token fetch;
  • the new fetchFromServer behaviour.

I ran each of the 63 new or changed tests on its own (npx vitest run tests/<file>.test.ts -t "<name>$" in packages/public-api-forwarding), and all pass. The package's tsc --noEmit and Prettier check pass.

🤖 Generated with Claude Code

anth-volk and others added 10 commits November 28, 2026 01:27
Failing tests for a server-side helper that calculates an inline household
on API v1's /v2/household-calculations: submit, read every 2 seconds until
the calculation succeeds or fails, a 10-minute limit, retries of brief
outages, and which submission failures are safe to retry. Also tests that
fetchFromServer takes the caller's AbortSignal and says whether a failed
request may have reached API v1. The helper module is a stub for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds createHouseholdCalculator to @policyengine/public-api-forwarding. Its
calculateHousehold submits /calculate's household and policy to API v1's
POST /v2/household-calculations, which keeps the calculation as a
household job only, then reads it every 2 seconds until it succeeds or
fails, for up to 10 minutes. Brief outages are retried for 90 seconds; a
submission is retried only when API v1 cannot have created the job.

fetchFromServer now takes the caller's AbortSignal, and its
PublicApiUnavailableError says whether the request may have reached API v1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A time limit that is not a number, or is negative, should reject with
RangeError before anything is submitted; today NaN and a string make the
helper read with no wait. Infinity stays allowed (that test passes already).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
calculateHousehold now rejects with RangeError, before submitting, when
timeLimitMilliseconds is not a number, is NaN or is negative. Infinity is
still allowed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Failing tests for:
- the household's axes travelling as a separate top-level axes field,
  as API v1's inline request takes them;
- the submission's timeout covering the time left before the deadline,
  at least 30 seconds, so a starting API v1 instance doesn't fail it;
- a 503 that isn't API v1's own (Cloud Run's plain-text one) not being
  resubmitted, since the job may exist;
- a submission retry that would wait until the deadline throwing instead;
- a time limit of 0 still reading the accepted calculation once;
- an abort while the server token is fetched rejecting with the signal's
  reason.

Also covers branches that had no test (they pass already): lost answer
bodies, read credential failures, submission 429s and 90 seconds of 503s,
Retry-After on a 429 and as a date, unreadable read answers, a failure
with no code, an abort while an answer arrives. The forwarder's abort
test now aborts after the request has started.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The household's axes go in the request's own axes field, as API v1's
  inline request takes them, without changing the caller's object.
- The submission may take until the deadline (at least 30 seconds), so a
  request that waits for an API v1 instance to start doesn't time out and
  leave a job that may exist. Reads keep 30 seconds.
- Only API v1's own 503, with its error body, is resubmitted; Cloud Run's
  plain-text 503 is not.
- A submission retry that would wait until the deadline throws instead,
  and an accepted calculation is read at least once, even with a time
  limit of 0.
- fetchFromServer checks the caller's signal before throwing a failed
  connection, so an abort while the token is fetched rejects with the
  signal's reason.
- Exported types no longer name unexported ones; the result-item casts
  are checks; requestMayHaveArrived and lastStatus are documented as they
  behave; the README's unrelated table reformatting is undone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Failing tests for:
- a submission answer that already says succeeded or failed (API v1's
  submitted item allows every status, and the simulation service answers
  with the job's current status when Modal doesn't confirm the call):
  read it at once rather than refusing it;
- a time limit that isn't a whole number: the submission's timeout must
  be whole milliseconds, which AbortSignal.timeout requires (the fake
  fetchFromServer now checks each timeout the same way);
- PublicApiUnavailableError naming why API v1 can't be called (unknown
  route, no configuration, no credential, unreachable, timed out), so the
  helper's resubmission rule no longer depends on which status a failure
  gets;
- an abort while the server token is fetched rejecting at once, without
  waiting for the token request.

The abort-while-an-answer-arrives test now aborts during the body read,
after the submission was sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A submission answer that already says succeeded or failed is read at
  once, for its result or error, instead of being refused as unreadable.
- The submission's timeout is rounded up to whole milliseconds, which
  AbortSignal.timeout requires, so a fractional time limit no longer
  fails every call.
- PublicApiUnavailableError names its reason (unknown_route,
  not_configured, credential_unavailable, unreachable, timed_out,
  answer_lost); requestMayHaveArrived follows from it, and the helper's
  resubmission and retry rules check the reason, not the status code.
- fetchFromServer rejects with the signal's reason as soon as the caller
  aborts while the token is fetched; the shared token request goes on.
- warnings are checked as strings by a type predicate.
- The README differs from main only by the new sections, which say that
  "API v1" is the service it calls the Public API, and give the token
  time in the worst-case call length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 3 found no bugs, but tests that would pass without the
behaviour they name, and untested branches. These cover:
- a read at the deadline that answers 503, or can't reach API v1,
  ending with HouseholdCalculationTimeoutError rather than reading again;
- 90 seconds of reads that can't reach API v1 ending with that failure;
- the helper's own timer: the first read 2 seconds after submitting, and
  an abort during the wait rejecting at once and leaving no timer.

The abort-during-a-wait test now uses a wait that ends only through the
signal it is given, and the forwarder's abort test uses a 60-second
request timeout, so each fails if the signal stops being passed on. They
cover existing behaviour, so they pass already.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 3's documentation findings: the PublicApiUnavailableError
doc comment sits on the class again, not above the new reason type; and
the notes now say a call can end up to about 80 seconds after its
deadline (a submission started just before it, then the read it is
owed), and that Node's fetch and API v1's Cloud Run service each end a
submission after 300 seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
policyengine-calculator-next Ready Ready Preview Nov 27, 2026 10:26pm UTC
policyengine-website Ready Ready Preview Nov 27, 2026 10:26pm UTC

Request Review

This branch was successfully deployed

2 active deployments
Preview – policyengine-website — 87eaa144 Deployed Nov 27, 2026 by vercel[bot]
Preview – policyengine-calculator-next — 87eaa144 Deployed Nov 27, 2026 by vercel[bot]
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 on API v1 by submitting and polling, from the website's server

1 participant