From bf2fa099aa53c5db6794aa4558ceb86dd911d065 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:27:22 +0400 Subject: [PATCH 01/10] Test submitting and polling household calculations from the server 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 --- .../src/householdCalculation.ts | 73 ++ .../tests/forward.test.ts | 72 ++ .../tests/householdCalculation.test.ts | 697 ++++++++++++++++++ 3 files changed, 842 insertions(+) create mode 100644 packages/public-api-forwarding/src/householdCalculation.ts create mode 100644 packages/public-api-forwarding/tests/householdCalculation.test.ts diff --git a/packages/public-api-forwarding/src/householdCalculation.ts b/packages/public-api-forwarding/src/householdCalculation.ts new file mode 100644 index 0000000000..66dd462859 --- /dev/null +++ b/packages/public-api-forwarding/src/householdCalculation.ts @@ -0,0 +1,73 @@ +// Calculates a household on API v1 by submitting it to +// POST /v2/household-calculations and reading the calculation until it +// finishes. Not implemented yet: the tests come first. + +import type { PublicApiForwarder } from "./forward"; + +export const HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS = 2_000; +export const HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS = 10 * 60_000; + +export type HouseholdCalculationCountry = "us" | "uk"; +export type HouseholdCalculationStatus = + | "pending" + | "running" + | "succeeded" + | "failed"; + +export interface InlineHouseholdCalculationRequest { + readonly country: HouseholdCalculationCountry; + readonly household: Readonly>; + readonly policy?: Readonly>; + readonly addMissingVariables?: boolean; + readonly spm?: Readonly>; +} + +export interface HouseholdCalculationOptions { + readonly signal?: AbortSignal; + readonly timeLimitMilliseconds?: number; +} + +export interface CalculatedHousehold { + readonly calculationId: string; + readonly household: Record; + readonly warnings: readonly string[]; + readonly spmConfig: Record | null; + readonly spmProvenance: Record | null; + readonly countryPackageVersion: string; + readonly policyengineVersion: string; +} + +export interface HouseholdCalculatorDependencies { + readonly forwarder: Pick; + readonly now?: () => number; + readonly wait?: (milliseconds: number, signal?: AbortSignal) => Promise; +} + +export interface HouseholdCalculator { + calculateHousehold( + request: InlineHouseholdCalculationRequest, + options?: HouseholdCalculationOptions, + ): Promise; +} + +export class HouseholdCalculationFailedError extends Error { + override name = "HouseholdCalculationFailedError"; +} + +export class HouseholdCalculationTimeoutError extends Error { + override name = "HouseholdCalculationTimeoutError"; +} + +export class HouseholdCalculationRefusedError extends Error { + override name = "HouseholdCalculationRefusedError"; +} + +export function createHouseholdCalculator( + _dependencies: HouseholdCalculatorDependencies, +): HouseholdCalculator { + return { + async calculateHousehold() { + throw new Error("calculateHousehold is not implemented yet."); + }, + }; +} diff --git a/packages/public-api-forwarding/tests/forward.test.ts b/packages/public-api-forwarding/tests/forward.test.ts index 9fb47f837a..29e21c86de 100644 --- a/packages/public-api-forwarding/tests/forward.test.ts +++ b/packages/public-api-forwarding/tests/forward.test.ts @@ -775,4 +775,76 @@ describe("fetchFromServer", () => { expect(failure).toMatchObject({ statusCode: 404 }); expect(fetchImplementation).not.toHaveBeenCalled(); }); + + test("given the caller's signal aborts then it rejects with the signal's reason", async () => { + // Given an API v1 that answers only when the request is aborted + const forwarder = createPublicApiForwarder({ + environment: PREVIEW_ENVIRONMENT_WITHOUT_CREDENTIAL, + callerName: "policyengine-test-caller", + sharedTokenStore: null, + clientAddress: () => undefined, + fetchImplementation: (_input, init) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => + reject(init.signal?.reason), + ); + }), + logger: silentLogger, + }); + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + + // When + const pendingRequest = forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST, { + signal: controller.signal, + timeoutMilliseconds: 1_000, + }) + .catch((error: unknown) => error); + controller.abort(callerLeft); + const failure = await pendingRequest; + + // Then + expect(failure).toBe(callerLeft); + }); + + test("given the token request fails then the error says the request never reached API v1", async () => { + // Given + const { forwarder } = forwarderWith({ + tokenAnswer: () => jsonResponse({ error: "access_denied" }, 403), + }); + + // When + const failure = await forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST) + .catch((error: unknown) => error); + + // Then + expect(failure).toBeInstanceOf(PublicApiUnavailableError); + expect(failure).toMatchObject({ + statusCode: 502, + requestMayHaveArrived: false, + }); + }); + + test("given API v1 cannot be reached then the error says the request may have arrived", async () => { + // Given + const { forwarder } = forwarderWith({ + publicApiAnswer: () => { + throw new TypeError("fetch failed"); + }, + }); + + // When + const failure = await forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST) + .catch((error: unknown) => error); + + // Then + expect(failure).toBeInstanceOf(PublicApiUnavailableError); + expect(failure).toMatchObject({ + statusCode: 502, + requestMayHaveArrived: true, + }); + }); }); diff --git a/packages/public-api-forwarding/tests/householdCalculation.test.ts b/packages/public-api-forwarding/tests/householdCalculation.test.ts new file mode 100644 index 0000000000..0c098414bb --- /dev/null +++ b/packages/public-api-forwarding/tests/householdCalculation.test.ts @@ -0,0 +1,697 @@ +import { describe, expect, test, vi } from "vitest"; + +import { + PublicApiUnavailableError, + type PublicApiRequest, + type ServerRequestOptions, +} from "../src/forward"; +import { + HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS, + HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS, + HouseholdCalculationFailedError, + HouseholdCalculationRefusedError, + HouseholdCalculationTimeoutError, + createHouseholdCalculator, + type HouseholdCalculatorDependencies, + type InlineHouseholdCalculationRequest, +} from "../src/householdCalculation"; +import { jsonResponse } from "./fixtures"; + +const CALCULATION_ID = "8a1f6b0e-3c2d-4e5f-9a7b-1c2d3e4f5a6b"; +const CALCULATION_PATH = `/v2/household-calculations/${CALCULATION_ID}`; +const OBSERVABILITY_ID = "obs-4d2c1b0a"; +const COUNTRY_PACKAGE_VERSION = "1.500.0"; +const POLICYENGINE_VERSION = "3.4.0"; + +const US_SITUATION = { + people: { you: { age: { 2026: 40 }, employment_income: { 2026: 50_000 } } }, + households: { + your_household: { + members: ["you"], + household_net_income: { 2026: null }, + }, + }, +}; + +const CALCULATED_US_SITUATION = { + people: { you: { age: { 2026: 40 }, employment_income: { 2026: 50_000 } } }, + households: { + your_household: { + members: ["you"], + household_net_income: { 2026: 44_210.5 }, + }, + }, +}; + +const CHILD_TAX_CREDIT_REFORM = { + "gov.irs.credits.ctc.amount.base[0].amount": { + "2026-01-01.2100-12-31": 3000, + }, +}; + +const US_REFORM_REQUEST: InlineHouseholdCalculationRequest = { + country: "us", + household: US_SITUATION, + policy: CHILD_TAX_CREDIT_REFORM, +}; + +const INVALID_INPUT_ERROR = { + type: "unknown_variable", + name: "employment_incme", + path: "people.you.employment_incme", + message: "employment_incme is not a variable of the US model.", +}; + +type CalculationStatus = "pending" | "running" | "succeeded" | "failed"; + +function submittedAnswer(): Response { + return jsonResponse( + { + status: "ok", + message: null, + result: { + item: { + calculation_id: CALCULATION_ID, + status: "pending", + country_id: "us", + household_id: null, + policy_id: null, + dynamic_id: null, + year: 2026, + }, + }, + }, + 202, + ); +} + +function calculationAnswer( + status: CalculationStatus, + outcome: { result?: unknown; error?: unknown } = {}, +): Response { + return jsonResponse({ + status: "ok", + message: null, + result: { + item: { + calculation_id: CALCULATION_ID, + country_id: "us", + household_id: null, + policy_id: null, + dynamic_id: null, + year: 2026, + catalog_version_id: "0b9d7c55-6e1f-4a2b-8c3d-4e5f6a7b8c9d", + country_package_version: COUNTRY_PACKAGE_VERSION, + policyengine_version: POLICYENGINE_VERSION, + status, + created_at: "2026-11-28T12:00:00Z", + started_at: status === "pending" ? null : "2026-11-28T12:00:01Z", + completed_at: + status === "succeeded" || status === "failed" + ? "2026-11-28T12:00:05Z" + : null, + result: outcome.result ?? null, + error: outcome.error ?? null, + }, + }, + }); +} + +function succeededAnswer(): Response { + return calculationAnswer("succeeded", { + result: { + household: CALCULATED_US_SITUATION, + warnings: ["Ignored input: rent"], + spm_config: { geography_kind: "national" }, + spm_provenance: { forecast_content_sha256: "ab12" }, + }, + }); +} + +function errorAnswer( + statusCode: number, + message: string, + extraFields: Record = {}, + headers: Record = {}, +): Response { + return jsonResponse( + { status: "error", message, ...extraFields }, + statusCode, + headers, + ); +} + +type ScriptedAnswer = Response | Error; + +interface RecordedRequest { + readonly request: PublicApiRequest; + readonly options: ServerRequestOptions | undefined; + readonly atMilliseconds: number; +} + +/** + * A fake API v1 on a fake clock: each request gets the next answer that + * `answerFor` gives, and each wait moves the clock on instead of sleeping. + */ +function fakeApiV1( + answerFor: (request: PublicApiRequest) => ScriptedAnswer, + overrides: Partial = {}, +) { + const clock = { milliseconds: 0 }; + const requests: RecordedRequest[] = []; + const waits: number[] = []; + const fetchFromServer = vi.fn( + async (request: PublicApiRequest, options?: ServerRequestOptions) => { + requests.push({ request, options, atMilliseconds: clock.milliseconds }); + const answer = answerFor(request); + if (answer instanceof Error) { + throw answer; + } + return answer; + }, + ); + const calculator = createHouseholdCalculator({ + forwarder: { fetchFromServer }, + now: () => clock.milliseconds, + wait: async (milliseconds, signal) => { + signal?.throwIfAborted(); + waits.push(milliseconds); + clock.milliseconds += milliseconds; + }, + ...overrides, + }); + const submissions = () => + requests.filter(({ request }) => request.method === "POST"); + const reads = () => + requests.filter(({ request }) => request.method === "GET"); + return { calculator, requests, submissions, reads, waits, clock }; +} + +/** Answers the requests in order from a list, failing on any request past its end. */ +function inOrder(answers: ScriptedAnswer[]) { + const remaining = [...answers]; + return (request: PublicApiRequest): ScriptedAnswer => { + const answer = remaining.shift(); + if (answer === undefined) { + throw new Error( + `The test expected no request ${request.method} ${request.path}`, + ); + } + return answer; + }; +} + +/** Answers the submission with `submission`, and every read with `readAnswer()`. */ +function submissionThenEveryRead( + submission: () => ScriptedAnswer, + readAnswer: () => ScriptedAnswer, +) { + return (request: PublicApiRequest): ScriptedAnswer => + request.method === "POST" ? submission() : readAnswer(); +} + +async function failureOf(promise: Promise): Promise { + return promise.then( + () => { + throw new Error("Expected the calculation to fail, but it resolved."); + }, + (error: unknown) => error, + ); +} + +function submittedBody(recorded: RecordedRequest): unknown { + return JSON.parse(recorded.request.body ?? "null"); +} + +describe("calculateHousehold", () => { + test("given a calculation that finishes after several reads then it resolves with the calculated household", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("pending"), + calculationAnswer("running"), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated).toEqual({ + calculationId: CALCULATION_ID, + household: CALCULATED_US_SITUATION, + warnings: ["Ignored input: rent"], + spmConfig: { geography_kind: "national" }, + spmProvenance: { forecast_content_sha256: "ab12" }, + countryPackageVersion: COUNTRY_PACKAGE_VERSION, + policyengineVersion: POLICYENGINE_VERSION, + }); + expect(api.requests.map(({ request }) => request.method)).toEqual([ + "POST", + "GET", + "GET", + "GET", + ]); + expect(api.submissions()[0].request.path).toBe( + "/v2/household-calculations", + ); + expect(submittedBody(api.submissions()[0])).toEqual({ + country_id: "us", + household: US_SITUATION, + policy: CHILD_TAX_CREDIT_REFORM, + }); + expect(api.reads().map(({ request }) => request.path)).toEqual([ + CALCULATION_PATH, + CALCULATION_PATH, + CALCULATION_PATH, + ]); + expect(api.waits).toEqual([2_000, 2_000, 2_000]); + }); + + test("given no policy and the missing-variable and SPM options then the submission sends the options and leaves policy out", async () => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + await api.calculator.calculateHousehold({ + country: "us", + household: US_SITUATION, + addMissingVariables: true, + spm: { geography_kind: "national" }, + }); + + // Then + expect(submittedBody(api.submissions()[0])).toEqual({ + country_id: "us", + household: US_SITUATION, + add_missing_variables: true, + spm: { geography_kind: "national" }, + }); + }); + + test("given a calculation that fails then it throws HouseholdCalculationFailedError with the job's error", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("running"), + calculationAnswer("failed", { + error: { + code: "invalid_inputs", + message: "The household names inputs the US model does not have.", + input_errors: [INVALID_INPUT_ERROR], + spm_error: null, + }, + }), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationFailedError); + expect(failure).toMatchObject({ + calculationId: CALCULATION_ID, + code: "invalid_inputs", + message: "The household names inputs the US model does not have.", + inputErrors: [INVALID_INPUT_ERROR], + spmError: null, + }); + expect(api.reads()).toHaveLength(2); + }); + + test("given a calculation still running at its time limit then it reads once more at the deadline and throws HouseholdCalculationTimeoutError", async () => { + // Given + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => + calculationAnswer("running"), + ), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 5_000, + }), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationTimeoutError); + expect(failure).toMatchObject({ + calculationId: CALCULATION_ID, + lastStatus: "running", + }); + expect(api.waits).toEqual([2_000, 2_000, 1_000]); + expect(api.reads().map(({ atMilliseconds }) => atMilliseconds)).toEqual([ + 2_000, 4_000, 5_000, + ]); + }); + + test("given the default settings then it reads every 2 seconds and gives up 10 minutes after it starts", async () => { + // Given + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => + calculationAnswer("pending"), + ), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS).toBe(2_000); + expect(HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS).toBe(600_000); + expect(failure).toBeInstanceOf(HouseholdCalculationTimeoutError); + expect(new Set(api.waits)).toEqual(new Set([2_000])); + expect(api.reads()).toHaveLength(300); + expect(api.reads().at(-1)?.atMilliseconds).toBe(600_000); + }); + + test.each([429, 502, 503, 504])( + "given a read answers %i then it waits one interval and reads again", + async (statusCode) => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer(statusCode, "Try again shortly"), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.household).toEqual(CALCULATED_US_SITUATION); + expect(api.reads()).toHaveLength(2); + expect(api.waits).toEqual([2_000, 2_000]); + }, + ); + + test("given a read answers 503 with Retry-After then it waits that many seconds before reading again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer(503, "Storage is unavailable", {}, { "Retry-After": "7" }), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(api.waits).toEqual([2_000, 7_000]); + }); + + test("given a read cannot reach API v1 then it reads again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + new PublicApiUnavailableError("Could not be reached.", 502, true), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.reads()).toHaveLength(2); + }); + + test("given reads fail for 90 seconds without a good answer then it throws the last failure", async () => { + // Given + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => + errorAnswer(502, "Bad gateway"), + ), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ + statusCode: 502, + calculationId: CALCULATION_ID, + }); + expect(api.reads().at(-1)?.atMilliseconds).toBe(90_000); + expect(api.reads()).toHaveLength(45); + }); + + test("given a read answers 404 then it throws HouseholdCalculationRefusedError without reading again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer(404, `Household calculation ${CALCULATION_ID} not found.`), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ + statusCode: 404, + message: `Household calculation ${CALCULATION_ID} not found.`, + calculationId: CALCULATION_ID, + }); + expect(api.reads()).toHaveLength(1); + }); + + test("given the submission answers 503 then it submits again after Retry-After", async () => { + // Given + const api = fakeApiV1( + inOrder([ + errorAnswer( + 503, + "The simulation service cannot be reached", + {}, + { "Retry-After": "3" }, + ), + submittedAnswer(), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.submissions()).toHaveLength(2); + expect(api.waits).toEqual([3_000, 2_000]); + }); + + test("given the submission answers 502 then it throws without submitting again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + errorAnswer( + 502, + "The simulation service's answer cannot be read; submitting again creates a second job if the first went through.", + ), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 502, calculationId: null }); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the submission may have reached API v1 before its connection failed then it throws without submitting again", async () => { + // Given + const timedOut = new PublicApiUnavailableError( + "The Public API did not answer in time.", + 504, + true, + ); + const api = fakeApiV1(inOrder([timedOut])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(timedOut); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the credential cannot be obtained before submitting then it submits again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + new PublicApiUnavailableError( + "Could not obtain a credential for the Public API.", + 502, + false, + ), + submittedAnswer(), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.submissions()).toHaveLength(2); + }); + + test("given API v1 is not configured on the deployment then it throws without trying again", async () => { + // Given + const notConfigured = new PublicApiUnavailableError( + "The Public API is not configured on this deployment.", + 503, + false, + ); + const api = fakeApiV1(inOrder([notConfigured])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(notConfigured); + expect(api.requests).toHaveLength(1); + }); + + test("given API v1 refuses a policy with missing parameters then it throws HouseholdCalculationRefusedError with the code and body", async () => { + // Given + const refusalBody = { + status: "error", + message: "The policy sets parameters the running catalog does not have.", + code: "missing_parameters", + missing_parameters: ["gov.irs.credits.ctc.amount.base[0].amount"], + }; + const api = fakeApiV1( + inOrder([ + jsonResponse(refusalBody, 422, { + "X-PolicyEngine-Observability-Id": OBSERVABILITY_ID, + }), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ + statusCode: 422, + code: "missing_parameters", + message: refusalBody.message, + body: refusalBody, + observabilityId: OBSERVABILITY_ID, + calculationId: null, + }); + expect(api.requests).toHaveLength(1); + }); + + test("given an accepted submission without a calculation ID then it throws HouseholdCalculationRefusedError", async () => { + // Given + const api = fakeApiV1( + inOrder([ + jsonResponse( + { status: "ok", message: null, result: { item: {} } }, + 202, + ), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 202, calculationId: null }); + }); + + test("given a signal then every request carries it", async () => { + // Given + const controller = new AbortController(); + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("running"), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST, { + signal: controller.signal, + }); + + // Then + expect(api.requests).toHaveLength(3); + for (const { options } of api.requests) { + expect(options?.signal).toBe(controller.signal); + } + }); + + test("given the signal aborts during a wait then it rejects with the abort reason and reads no more", async () => { + // Given + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => + calculationAnswer("running"), + ), + { + wait: async (_milliseconds, signal) => { + controller.abort(callerLeft); + signal?.throwIfAborted(); + }, + }, + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + signal: controller.signal, + }), + ); + + // Then + expect(failure).toBe(callerLeft); + expect(api.reads()).toHaveLength(0); + }); +}); From 74ba6350fe1a74af18a6983a92993330e9967893 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:31:33 +0400 Subject: [PATCH 02/10] Calculate inline households on API v1 by submitting and polling 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 --- packages/public-api-forwarding/README.md | 80 ++- packages/public-api-forwarding/src/forward.ts | 36 +- .../src/householdCalculation.ts | 586 +++++++++++++++++- packages/public-api-forwarding/src/index.ts | 17 + 4 files changed, 684 insertions(+), 35 deletions(-) diff --git a/packages/public-api-forwarding/README.md b/packages/public-api-forwarding/README.md index e54cac2ce5..2bfb3322e1 100644 --- a/packages/public-api-forwarding/README.md +++ b/packages/public-api-forwarding/README.md @@ -18,19 +18,20 @@ The calculator's pages reach the Public API only through its route (`BASE_URL` i - without one, it stays in `Authorization`, as on a direct browser call. Cookies, `Origin`, `Referer` and any `PolicyEngine-User-Authorization` the browser sends are dropped. + - **Streams the answer back** with an allow list of response headers (`Content-Type`, `ETag`, `Last-Modified`, `Retry-After`, `WWW-Authenticate` and the Public API's request IDs). `Content-Encoding` and `Content-Length` are dropped, because `fetch` has already decompressed the body. Streaming matters because Vercel caps a buffered function answer at 4.5 MB. - **Caches nothing it should not**: the route's `cacheControl` applies only to 2xx and 304 answers; every other answer is `no-store`, and so is every answer when the route gives none. - **Maps failures to JSON** in the Public API's own error shape, `{"status": "error", "message": ..., "result": null}`, marked with `X-PolicyEngine-Route-Error: true` (`ROUTE_ERROR_HEADER`) so a same-origin caller, such as the calculator's pages, can tell them from the Public API's own errors, such as its 502 for a failed calculation. A cross-origin caller sees the header only if the route's CORS policy exposes it, and the website's dashboard API doesn't: - | Failure | Status | - | --- | --- | - | A path outside the letters, digits and `-_.~` segments a route may name | 404 | - | `POLICYENGINE_API_URL` missing outside production, or a partial credential | 503 | - | Auth0 refuses or does not answer the token request | 502 | - | The Public API cannot be reached | 502 | - | The Public API answers with a redirect (never followed: it would carry the credential) | 502 | - | No response headers within the route's timeout | 504 | - | A non-JSON error from in front of the Public API, such as the load balancer's 429 | same status, JSON body | + | Failure | Status | + | -------------------------------------------------------------------------------------- | ---------------------- | + | A path outside the letters, digits and `-_.~` segments a route may name | 404 | + | `POLICYENGINE_API_URL` missing outside production, or a partial credential | 503 | + | Auth0 refuses or does not answer the token request | 502 | + | The Public API cannot be reached | 502 | + | The Public API answers with a redirect (never followed: it would carry the credential) | 502 | + | No response headers within the route's timeout | 504 | + | A non-JSON error from in front of the Public API, such as the load balancer's 429 | same status, JSON body | JSON errors from the Public API itself pass through unchanged. @@ -44,15 +45,62 @@ The Auth0 token request never follows a redirect, which would re-send the client `isJsonMediaType()` is the JSON content-type check the package and its routes share: `application/json` or any `application/...+json` type. +`fetchFromServer()` also takes a `signal`. When it aborts, the request stops and `fetchFromServer()` rejects with the signal's reason. Its `PublicApiUnavailableError` says in `requestMayHaveArrived` whether API v1 may have received the request: `false` when it was never sent (an unknown path, no configuration, or no credential), `true` when the connection failed or timed out after sending. + +## Household calculations + +`createHouseholdCalculator({ forwarder })` returns `calculateHousehold(request, options)`, which calculates a household on API v1 without storing it. It is for server code that used to send API v1's synchronous `POST /{country}/calculate`, and takes the same household and policy: + +```ts +import { createHouseholdCalculator } from "@policyengine/public-api-forwarding"; + +const calculator = createHouseholdCalculator({ forwarder: websitePublicApi }); +const calculated = await calculator.calculateHousehold( + { + country: "us", + household: situation, // /calculate's situation, axes included + policy: { + "gov.irs.credits.ctc.amount.base[0].amount": { + "2026-01-01.2100-12-31": 3000, + }, + }, + }, + { signal: request.signal }, +); +calculated.household; // what /calculate answered as `result` +``` + +What it does, through `fetchFromServer()`: + +1. Submits `{country_id, household, policy?, add_missing_variables?, spm?}` to `POST /v2/household-calculations`. API v1 keeps the calculation as a household job only: no stored household, policy or user association. +2. Reads `GET /v2/household-calculations/{calculation_id}` every 2 seconds until the calculation succeeds or fails. +3. Gives up 10 minutes after the call starts (`timeLimitMilliseconds`). No wait runs past that deadline; the last read happens at it. + +It resolves with the calculated household, `warnings`, `spmConfig`, `spmProvenance`, the calculation ID and the versions it ran with. It throws: + +- `HouseholdCalculationFailedError` when the calculation fails, with the household function's `code` (such as `invalid_inputs`), `inputErrors` and `spmError`. A null `code` means the function raised or was cancelled, and submitting again may succeed. +- `HouseholdCalculationTimeoutError` when the time limit passes, with the calculation ID and the last status read. +- `HouseholdCalculationRefusedError` when API v1 refuses a request or its answer cannot be read, with the HTTP status, API v1's message and `code` (such as `missing_parameters`), the parsed body, `Retry-After` and the observability and request IDs. +- `PublicApiUnavailableError` when API v1 cannot be called. +- The signal's reason when the signal aborts. + +Brief outages are retried until 90 seconds pass without a good answer: + +- **Reads** are retried on 429, 502, 503 and 504, and when API v1 cannot be reached, does not answer in time, or the credential cannot be obtained. A 429 or 503 with `Retry-After` waits that many seconds, or 2 seconds if that is longer; anything else waits 2 seconds. +- **The submission** is retried only when no job can exist: on API v1's 503, which it answers when no job of the submission will run, and when the credential cannot be obtained, so the request was never sent. It is not retried on a 502, or when the connection fails or times out after sending, because API v1 may have created the job and submitting again would create a second one. +- Nothing else is retried, including 400, 401, 403, 404, 409, 413, 422 and 500. + +How `calculated` differs from `/calculate`'s answer: there is no `{status, message, result}` envelope; `warnings` and `spm_provenance` are fields of the result, as `warnings` and `spmProvenance`; and inputs the model does not recognise come back as a failed calculation (`code: "invalid_inputs"`, `inputErrors`), thrown as `HouseholdCalculationFailedError`, not as a 400 with `errors`. + ## Configuration -| Variable | Meaning | -| --- | --- | -| `POLICYENGINE_API_URL` | The Public API's base URL, https (or http on localhost). Required outside production. | -| `POLICYENGINE_API_AUTH0_DOMAIN` | Host of the Auth0 token endpoint. Tokens carry this host as their issuer, so it must be the issuer the Public API checks. | -| `POLICYENGINE_API_AUTH0_AUDIENCE` | The Auth0 API identifier the token is for. | -| `POLICYENGINE_API_AUTH0_CLIENT_ID` | The caller's own Auth0 machine-to-machine client. | -| `POLICYENGINE_API_AUTH0_CLIENT_SECRET` | That client's secret. Read on the server only; never put it in a `NEXT_PUBLIC_*` or `VITE_*` variable. | +| Variable | Meaning | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| `POLICYENGINE_API_URL` | The Public API's base URL, https (or http on localhost). Required outside production. | +| `POLICYENGINE_API_AUTH0_DOMAIN` | Host of the Auth0 token endpoint. Tokens carry this host as their issuer, so it must be the issuer the Public API checks. | +| `POLICYENGINE_API_AUTH0_AUDIENCE` | The Auth0 API identifier the token is for. | +| `POLICYENGINE_API_AUTH0_CLIENT_ID` | The caller's own Auth0 machine-to-machine client. | +| `POLICYENGINE_API_AUTH0_CLIENT_SECRET` | That client's secret. Read on the server only; never put it in a `NEXT_PUBLIC_*` or `VITE_*` variable. | Production deployments use the production Public API and a production Auth0 client. Preview and development deployments use the Public API's staging service and a staging client. For local work, `vercel env pull` writes the development values. diff --git a/packages/public-api-forwarding/src/forward.ts b/packages/public-api-forwarding/src/forward.ts index beac2b35f7..0a3f75bf58 100644 --- a/packages/public-api-forwarding/src/forward.ts +++ b/packages/public-api-forwarding/src/forward.ts @@ -57,12 +57,18 @@ export interface ServerRequestOptions { }; /** How long to wait for the whole request. */ readonly timeoutMilliseconds?: number; + /** + * The caller's signal. When it aborts, the request stops and + * fetchFromServer rejects with the signal's reason. + */ + readonly signal?: AbortSignal; } /** * The Public API cannot be called: it is not configured, the server * credential cannot be obtained, or the path is not one a route may name. - * The message is safe to show; details go to the server's log. + * Or, from fetchFromServer, API v1 could not be reached or did not answer in + * time. The message is safe to show; details go to the server's log. */ export class PublicApiUnavailableError extends Error { override name = "PublicApiUnavailableError"; @@ -71,6 +77,12 @@ export class PublicApiUnavailableError extends Error { message: string, /** The status a route would answer with for this failure. */ readonly statusCode: number, + /** + * False when the request was never sent, so sending it again cannot + * repeat it. True when it was sent and the connection failed or timed + * out, so API v1 may have received it and acted on it. + */ + readonly requestMayHaveArrived: boolean = false, ) { super(message); } @@ -466,10 +478,14 @@ export function createPublicApiForwarder( publicApiRequest: PublicApiRequest, serverOptions: ServerRequestOptions = {}, ): Promise { + const callerSignal = serverOptions.signal; + callerSignal?.throwIfAborted(); const connection = await connect(publicApiRequest); if (!connection.ok) { throw connection.error; } + // Getting the token can take a while; the caller may have left meanwhile. + callerSignal?.throwIfAborted(); const { upstreamUrl, serverToken } = connection; const headers = new Headers({ @@ -483,14 +499,18 @@ export function createPublicApiForwarder( headers.set("Authorization", `Bearer ${serverToken}`); } + const timeoutSignal = AbortSignal.timeout( + serverOptions.timeoutMilliseconds ?? + DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, + ); const init: RequestInit & { next?: ServerRequestOptions["next"] } = { method: publicApiRequest.method, headers, body: publicApiRequest.body, - signal: AbortSignal.timeout( - serverOptions.timeoutMilliseconds ?? - DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, - ), + signal: + callerSignal === undefined + ? timeoutSignal + : AbortSignal.any([timeoutSignal, callerSignal]), // Never followed: a redirect would carry the server credential. redirect: "manual", }; @@ -501,6 +521,9 @@ export function createPublicApiForwarder( try { upstream = await fetchImplementation(upstreamUrl, init); } catch (error) { + if (callerSignal?.aborted) { + throw callerSignal.reason; + } const timedOut = error instanceof DOMException && error.name === "TimeoutError"; logger.error( @@ -509,14 +532,17 @@ export function createPublicApiForwarder( : `Could not reach the Public API for ${publicApiRequest.method} ${publicApiRequest.path}:`, error instanceof Error ? error.message : error, ); + // The request was sent, so API v1 may have received it. throw timedOut ? new PublicApiUnavailableError( "The Public API did not answer in time.", 504, + true, ) : new PublicApiUnavailableError( "The Public API could not be reached.", 502, + true, ); } warnIfCredentialRefused(publicApiRequest, serverToken, upstream); diff --git a/packages/public-api-forwarding/src/householdCalculation.ts b/packages/public-api-forwarding/src/householdCalculation.ts index 66dd462859..df9d66db3b 100644 --- a/packages/public-api-forwarding/src/householdCalculation.ts +++ b/packages/public-api-forwarding/src/householdCalculation.ts @@ -1,11 +1,46 @@ -// Calculates a household on API v1 by submitting it to -// POST /v2/household-calculations and reading the calculation until it -// finishes. Not implemented yet: the tests come first. +// Calculates a household on API v1 without storing it. The household, in +// the situation shape POST /{country}/calculate takes, goes to +// POST /v2/household-calculations; the helper then reads +// GET /v2/household-calculations/{calculation_id} until the calculation +// succeeds or fails. API v1 keeps the calculation as a household job only, +// with no stored household, policy or user association. +// +// For server code: every request goes through the forwarder's +// fetchFromServer, which adds the server credential. -import type { PublicApiForwarder } from "./forward"; +import { + PublicApiUnavailableError, + type PublicApiForwarder, + type PublicApiRequest, +} from "./forward"; +/** How long the helper waits between reads of a calculation. */ export const HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS = 2_000; +/** How long after it starts the helper gives up on a calculation. */ export const HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS = 10 * 60_000; +/** + * How long brief outages are retried without a good answer from API v1 + * before the helper gives up and throws the last failure. + */ +export const HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS = 90_000; + +const SUBMISSION_PATH = "/v2/household-calculations"; +/** Read answers that a brief outage or a rate limit explains. */ +const RETRIED_READ_STATUSES = new Set([429, 502, 503, 504]); +/** + * The submission answer after which API v1 says no job will run, so + * submitting again cannot create a second one. A 502 is not retried: API v1 + * answers it when the job may exist. + */ +const RETRIED_SUBMISSION_STATUSES = new Set([503]); +/** Answers whose Retry-After the helper waits out. */ +const RETRY_AFTER_STATUSES = new Set([429, 503]); +const OBSERVABILITY_ID_HEADER = "x-policyengine-observability-id"; +const REQUEST_ID_HEADER = "x-policyengine-request-id"; +/** setTimeout runs any longer delay at once, so no wait is longer. */ +const LONGEST_TIMER_MILLISECONDS = 2 ** 31 - 1; +/** A calculation ID is a UUID; this also keeps it one path segment. */ +const CALCULATION_ID_PATTERN = /^[0-9A-Fa-f-]{1,64}$/; export type HouseholdCalculationCountry = "us" | "uk"; export type HouseholdCalculationStatus = @@ -13,61 +48,584 @@ export type HouseholdCalculationStatus = | "running" | "succeeded" | "failed"; +type UnfinishedStatus = "pending" | "running"; + +type JsonObject = Record; +/** A household to calculate, as POST /{country}/calculate takes it. */ export interface InlineHouseholdCalculationRequest { readonly country: HouseholdCalculationCountry; - readonly household: Readonly>; - readonly policy?: Readonly>; + /** The household in the situation shape, axes included. */ + readonly household: Readonly; + /** + * Parameter changes keyed by parameter path, each mapping a period such as + * "2026-01-01.2100-12-31" to a value. Current law when omitted. + */ + readonly policy?: Readonly; + /** Adds every variable the household lacks, as /calculate-full does. */ readonly addMissingVariables?: boolean; - readonly spm?: Readonly>; + /** SPM settings for a US household. */ + readonly spm?: Readonly; } export interface HouseholdCalculationOptions { + /** Stops the requests in flight and any wait, rejecting with its reason. */ readonly signal?: AbortSignal; + /** + * How long after the call starts to give up, 10 minutes by default. The + * last read happens at the deadline. + */ readonly timeLimitMilliseconds?: number; } +/** A calculation that succeeded. */ export interface CalculatedHousehold { readonly calculationId: string; - readonly household: Record; + /** + * The household with each calculated value filled in by period, in the + * shape /calculate answered as `result`. + */ + readonly household: JsonObject; + /** Inputs the country model ignored. */ readonly warnings: readonly string[]; - readonly spmConfig: Record | null; - readonly spmProvenance: Record | null; + /** For a US household, the SPM selection the calculation applied. */ + readonly spmConfig: JsonObject | null; + /** For a US household, the receipt of the SPM forecast it used. */ + readonly spmProvenance: JsonObject | null; readonly countryPackageVersion: string; readonly policyengineVersion: string; } export interface HouseholdCalculatorDependencies { readonly forwarder: Pick; + /** The current time in milliseconds; Date.now by default. */ readonly now?: () => number; + /** Waits, rejecting with the signal's reason when it aborts; a timer by default. */ readonly wait?: (milliseconds: number, signal?: AbortSignal) => Promise; } export interface HouseholdCalculator { + /** + * Submits the household and reads the calculation until it finishes. + * Resolves with the calculated household. Throws + * HouseholdCalculationFailedError when the calculation fails, + * HouseholdCalculationTimeoutError when the time limit passes, + * HouseholdCalculationRefusedError when API v1 refuses a request or its + * answer cannot be read, and PublicApiUnavailableError when API v1 cannot + * be called. + */ calculateHousehold( request: InlineHouseholdCalculationRequest, options?: HouseholdCalculationOptions, ): Promise; } +/** The calculation ran and failed. */ export class HouseholdCalculationFailedError extends Error { override name = "HouseholdCalculationFailedError"; + + constructor( + message: string, + readonly calculationId: string, + /** + * The household function's error code, such as "invalid_inputs". Null + * when the function raised or was cancelled; submitting again may then + * succeed. + */ + readonly code: string | null, + /** For "invalid_inputs", each input the country model does not recognise. */ + readonly inputErrors: readonly JsonObject[], + /** For "invalid_spm_selection", what is wrong with the SPM settings. */ + readonly spmError: JsonObject | null, + ) { + super(message); + } } +/** + * The time limit passed before the calculation finished. API v1 may still + * finish it; GET /v2/household-calculations/{calculationId} reads it. + */ export class HouseholdCalculationTimeoutError extends Error { override name = "HouseholdCalculationTimeoutError"; + + constructor( + message: string, + readonly calculationId: string, + /** The status the last successful read gave. */ + readonly lastStatus: UnfinishedStatus, + ) { + super(message); + } } -export class HouseholdCalculationRefusedError extends Error { +export interface HouseholdCalculationRefusal { + /** The HTTP status of API v1's answer. */ + readonly statusCode: number; + /** The answer's parsed body, or null when it was empty or not JSON. */ + readonly body: unknown; + /** API v1's error code, such as "missing_parameters", when it gave one. */ + readonly code: string | null; + /** Seconds from the answer's Retry-After, when it had one. */ + readonly retryAfterSeconds: number | null; + readonly observabilityId: string | null; + readonly requestId: string | null; + /** The calculation the answer concerns, or null before one was accepted. */ + readonly calculationId: string | null; +} + +/** + * API v1 refused a request, failed with an error status, or answered in a + * shape the helper cannot read. The message is API v1's, when it gave one. + */ +export class HouseholdCalculationRefusedError + extends Error + implements HouseholdCalculationRefusal +{ override name = "HouseholdCalculationRefusedError"; + readonly statusCode: number; + readonly body: unknown; + readonly code: string | null; + readonly retryAfterSeconds: number | null; + readonly observabilityId: string | null; + readonly requestId: string | null; + readonly calculationId: string | null; + + constructor(message: string, refusal: HouseholdCalculationRefusal) { + super(message); + this.statusCode = refusal.statusCode; + this.body = refusal.body; + this.code = refusal.code; + this.retryAfterSeconds = refusal.retryAfterSeconds; + this.observabilityId = refusal.observabilityId; + this.requestId = refusal.requestId; + this.calculationId = refusal.calculationId; + } +} + +interface ApiV1Answer { + readonly response: Response; + readonly body: unknown; +} + +interface SubmittedCalculation { + readonly calculationId: string; + readonly status: UnfinishedStatus; +} + +function isJsonObject(value: unknown): value is JsonObject { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function objectOrNull(value: unknown): JsonObject | null | undefined { + if (value === undefined || value === null) { + return null; + } + return isJsonObject(value) ? value : undefined; +} + +function retryAfterSeconds(response: Response): number | null { + const value = response.headers.get("retry-after"); + if (value === null) { + return null; + } + // A delay is decimal digits only; a date, or anything else, is ignored. + const digits = value.trim(); + return /^[0-9]+$/.test(digits) ? Number(digits) : null; +} + +function waitWithTimer( + milliseconds: number, + signal?: AbortSignal, +): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, milliseconds); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +function submissionBody( + request: InlineHouseholdCalculationRequest, +): JsonObject { + return { + country_id: request.country, + household: request.household, + ...(request.policy === undefined ? {} : { policy: request.policy }), + ...(request.addMissingVariables === undefined + ? {} + : { add_missing_variables: request.addMissingVariables }), + ...(request.spm === undefined ? {} : { spm: request.spm }), + }; +} + +function refusal( + answer: ApiV1Answer, + calculationId: string | null, + fallbackMessage = `API v1 answered HTTP ${answer.response.status}.`, +): HouseholdCalculationRefusedError { + const fields = isJsonObject(answer.body) ? answer.body : {}; + const message = + typeof fields.message === "string" && fields.message.length > 0 + ? fields.message + : fallbackMessage; + return new HouseholdCalculationRefusedError(message, { + statusCode: answer.response.status, + body: answer.body, + code: typeof fields.code === "string" ? fields.code : null, + retryAfterSeconds: retryAfterSeconds(answer.response), + observabilityId: answer.response.headers.get(OBSERVABILITY_ID_HEADER), + requestId: answer.response.headers.get(REQUEST_ID_HEADER), + calculationId, + }); +} + +/** + * An answer that came with a success status but cannot be read. Its own + * message, if any, is not the reason, so `message` replaces it. + */ +function unreadable( + answer: ApiV1Answer, + calculationId: string | null, + message: string, +): HouseholdCalculationRefusedError { + return new HouseholdCalculationRefusedError( + message, + refusal(answer, calculationId), + ); +} + +/** The accepted calculation in a submission's answer. */ +function readSubmitted(answer: ApiV1Answer): SubmittedCalculation { + const item = isJsonObject(answer.body) + ? (answer.body.result as JsonObject | undefined)?.item + : undefined; + const calculationId = isJsonObject(item) ? item.calculation_id : undefined; + const status = isJsonObject(item) ? item.status : undefined; + if ( + typeof calculationId !== "string" || + !CALCULATION_ID_PATTERN.test(calculationId) || + (status !== "pending" && status !== "running") + ) { + throw unreadable( + answer, + null, + "API v1 accepted the household calculation, but its answer has no calculation ID the helper can read, so the calculation, if one started, cannot be read.", + ); + } + return { calculationId, status }; +} + +type CalculationRead = + | { readonly status: UnfinishedStatus } + | { readonly status: "succeeded"; readonly calculated: CalculatedHousehold } + | { + readonly status: "failed"; + readonly failure: HouseholdCalculationFailedError; + }; + +/** The calculation in a read's answer, or a refusal when it cannot be read. */ +function readCalculation( + answer: ApiV1Answer, + calculationId: string, +): CalculationRead { + const cannotRead = () => + unreadable( + answer, + calculationId, + `API v1's answer for household calculation ${calculationId} cannot be read.`, + ); + const item = isJsonObject(answer.body) + ? (answer.body.result as JsonObject | undefined)?.item + : undefined; + if (!isJsonObject(item) || item.calculation_id !== calculationId) { + throw cannotRead(); + } + + if (item.status === "pending" || item.status === "running") { + return { status: item.status }; + } + + if (item.status === "succeeded") { + const result = item.result; + if (!isJsonObject(result) || !isJsonObject(result.household)) { + throw cannotRead(); + } + const warnings = result.warnings ?? []; + const spmConfig = objectOrNull(result.spm_config); + const spmProvenance = objectOrNull(result.spm_provenance); + if ( + !Array.isArray(warnings) || + !warnings.every((warning) => typeof warning === "string") || + spmConfig === undefined || + spmProvenance === undefined || + typeof item.country_package_version !== "string" || + typeof item.policyengine_version !== "string" + ) { + throw cannotRead(); + } + return { + status: "succeeded", + calculated: { + calculationId, + household: result.household, + warnings, + spmConfig, + spmProvenance, + countryPackageVersion: item.country_package_version, + policyengineVersion: item.policyengine_version, + }, + }; + } + + if (item.status === "failed") { + const error = item.error; + if (!isJsonObject(error) || typeof error.message !== "string") { + throw cannotRead(); + } + const code = error.code ?? null; + const inputErrors = error.input_errors ?? []; + const spmError = objectOrNull(error.spm_error); + if ( + (code !== null && typeof code !== "string") || + !Array.isArray(inputErrors) || + !inputErrors.every(isJsonObject) || + spmError === undefined + ) { + throw cannotRead(); + } + return { + status: "failed", + failure: new HouseholdCalculationFailedError( + error.message, + calculationId, + code, + inputErrors, + spmError, + ), + }; + } + + throw cannotRead(); +} + +/** + * A failure of fetchFromServer that sending again cannot repeat: the server + * credential could not be obtained, so the request was never sent. + */ +function isUnsentCredentialFailure(error: unknown): boolean { + return ( + error instanceof PublicApiUnavailableError && + !error.requestMayHaveArrived && + error.statusCode === 502 + ); +} + +/** + * A failure of fetchFromServer that a brief outage explains: the credential + * could not be obtained, or API v1 could not be reached or did not answer in + * time. A deployment with no API v1 configured is not one. + */ +function isBriefOutage(error: unknown): boolean { + return ( + error instanceof PublicApiUnavailableError && + (error.requestMayHaveArrived || error.statusCode === 502) + ); } export function createHouseholdCalculator( - _dependencies: HouseholdCalculatorDependencies, + dependencies: HouseholdCalculatorDependencies, ): HouseholdCalculator { + const { forwarder } = dependencies; + const now = dependencies.now ?? Date.now; + const wait = dependencies.wait ?? waitWithTimer; + + async function send( + request: PublicApiRequest, + signal: AbortSignal | undefined, + ): Promise { + const response = await forwarder.fetchFromServer(request, { signal }); + let text: string; + try { + text = await response.text(); + } catch (error) { + if (signal?.aborted) { + throw signal.reason; + } + // The answer was lost after the request arrived. + throw new PublicApiUnavailableError( + "API v1's answer was lost before it could be read.", + 502, + true, + ); + } + let body: unknown = null; + try { + body = text === "" ? null : JSON.parse(text); + } catch { + // Not JSON, such as a load balancer's error page; the status still tells. + } + return { response, body }; + } + + /** How long to wait before trying again after a retried answer. */ + function retryWaitMilliseconds(response: Response): number { + const seconds = RETRY_AFTER_STATUSES.has(response.status) + ? retryAfterSeconds(response) + : null; + return seconds === null + ? HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS + : Math.max( + seconds * 1_000, + HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS, + ); + } + + /** Waits, but never past the deadline; false when no time is left. */ + async function waitWithin( + milliseconds: number, + deadline: number, + signal: AbortSignal | undefined, + ): Promise { + const remainingMilliseconds = deadline - now(); + if (remainingMilliseconds <= 0) { + return false; + } + await wait( + Math.min(milliseconds, remainingMilliseconds, LONGEST_TIMER_MILLISECONDS), + signal, + ); + return true; + } + + async function submit( + request: InlineHouseholdCalculationRequest, + deadline: number, + signal: AbortSignal | undefined, + ): Promise { + const body = JSON.stringify(submissionBody(request)); + const startedAt = now(); + const canRetry = () => + now() - startedAt < HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS; + + for (;;) { + signal?.throwIfAborted(); + let answer: ApiV1Answer; + try { + answer = await send( + { method: "POST", path: SUBMISSION_PATH, body }, + signal, + ); + } catch (error) { + if ( + !isUnsentCredentialFailure(error) || + !canRetry() || + !(await waitWithin( + HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS, + deadline, + signal, + )) + ) { + throw error; + } + continue; + } + + if (answer.response.ok) { + return readSubmitted(answer); + } + const failure = refusal(answer, null); + if ( + !RETRIED_SUBMISSION_STATUSES.has(answer.response.status) || + !canRetry() || + !(await waitWithin( + retryWaitMilliseconds(answer.response), + deadline, + signal, + )) + ) { + throw failure; + } + } + } + + async function readUntilFinished( + submitted: SubmittedCalculation, + deadline: number, + signal: AbortSignal | undefined, + ): Promise { + const { calculationId } = submitted; + const path = `${SUBMISSION_PATH}/${calculationId}`; + let lastStatus: UnfinishedStatus = submitted.status; + let lastGoodAnswerAt = now(); + let nextWaitMilliseconds = HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS; + const outageLimitReached = () => + now() - lastGoodAnswerAt >= + HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS; + + for (;;) { + if (!(await waitWithin(nextWaitMilliseconds, deadline, signal))) { + throw new HouseholdCalculationTimeoutError( + `Household calculation ${calculationId} did not finish in time.`, + calculationId, + lastStatus, + ); + } + signal?.throwIfAborted(); + nextWaitMilliseconds = HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS; + + let answer: ApiV1Answer; + try { + answer = await send({ method: "GET", path }, signal); + } catch (error) { + if (!isBriefOutage(error) || outageLimitReached()) { + throw error; + } + continue; + } + + if (!answer.response.ok) { + if ( + !RETRIED_READ_STATUSES.has(answer.response.status) || + outageLimitReached() + ) { + throw refusal(answer, calculationId); + } + nextWaitMilliseconds = retryWaitMilliseconds(answer.response); + continue; + } + + const calculation = readCalculation(answer, calculationId); + lastGoodAnswerAt = now(); + if (calculation.status === "succeeded") { + return calculation.calculated; + } + if (calculation.status === "failed") { + throw calculation.failure; + } + lastStatus = calculation.status; + } + } + return { - async calculateHousehold() { - throw new Error("calculateHousehold is not implemented yet."); + async calculateHousehold(request, options = {}) { + const { signal } = options; + const deadline = + now() + + (options.timeLimitMilliseconds ?? + HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS); + const submitted = await submit(request, deadline, signal); + return readUntilFinished(submitted, deadline, signal); }, }; } diff --git a/packages/public-api-forwarding/src/index.ts b/packages/public-api-forwarding/src/index.ts index a11ce037b2..c225f46d29 100644 --- a/packages/public-api-forwarding/src/index.ts +++ b/packages/public-api-forwarding/src/index.ts @@ -31,6 +31,23 @@ export { type PublicApiRequest, type ServerRequestOptions, } from "./forward"; +export { + HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS, + HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS, + HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS, + HouseholdCalculationFailedError, + HouseholdCalculationRefusedError, + HouseholdCalculationTimeoutError, + createHouseholdCalculator, + type CalculatedHousehold, + type HouseholdCalculationCountry, + type HouseholdCalculationOptions, + type HouseholdCalculationRefusal, + type HouseholdCalculationStatus, + type HouseholdCalculator, + type HouseholdCalculatorDependencies, + type InlineHouseholdCalculationRequest, +} from "./householdCalculation"; export { isJsonMediaType } from "./mediaType"; export { ROUTE_ERROR_HEADER, errorResponse } from "./responses"; export { From 47ac9ca1cb709586992d769bbbe32c3619c24b48 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:32:04 +0400 Subject: [PATCH 03/10] Test that calculateHousehold refuses a time limit that is not 0 or more 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 --- .../tests/householdCalculation.test.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/packages/public-api-forwarding/tests/householdCalculation.test.ts b/packages/public-api-forwarding/tests/householdCalculation.test.ts index 0c098414bb..fd445942f8 100644 --- a/packages/public-api-forwarding/tests/householdCalculation.test.ts +++ b/packages/public-api-forwarding/tests/householdCalculation.test.ts @@ -694,4 +694,48 @@ describe("calculateHousehold", () => { expect(failure).toBe(callerLeft); expect(api.reads()).toHaveLength(0); }); + + test.each([ + ["not a number", Number.NaN], + ["negative", -1], + ["a string", "600000" as unknown as number], + ])( + "given a time limit that is %s then it rejects with RangeError before submitting", + async (_description, timeLimitMilliseconds) => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds, + }), + ); + + // Then + expect(failure).toBeInstanceOf(RangeError); + expect(api.requests).toHaveLength(0); + }, + ); + + test("given an infinite time limit then it keeps reading until the calculation finishes", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + ...Array.from({ length: 400 }, () => calculationAnswer("running")), + succeededAnswer(), + ]), + ); + + // When + const calculated = await api.calculator.calculateHousehold( + US_REFORM_REQUEST, + { timeLimitMilliseconds: Number.POSITIVE_INFINITY }, + ); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.reads()).toHaveLength(401); + }); }); From 07d4e738e651bcf428f7629ef3fceb478f6ba615 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:33:12 +0400 Subject: [PATCH 04/10] Refuse a household calculation time limit that is not 0 or more 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 --- packages/public-api-forwarding/README.md | 2 +- .../src/householdCalculation.ts | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/public-api-forwarding/README.md b/packages/public-api-forwarding/README.md index 2bfb3322e1..a46ed4ddff 100644 --- a/packages/public-api-forwarding/README.md +++ b/packages/public-api-forwarding/README.md @@ -74,7 +74,7 @@ What it does, through `fetchFromServer()`: 1. Submits `{country_id, household, policy?, add_missing_variables?, spm?}` to `POST /v2/household-calculations`. API v1 keeps the calculation as a household job only: no stored household, policy or user association. 2. Reads `GET /v2/household-calculations/{calculation_id}` every 2 seconds until the calculation succeeds or fails. -3. Gives up 10 minutes after the call starts (`timeLimitMilliseconds`). No wait runs past that deadline; the last read happens at it. +3. Gives up 10 minutes after the call starts, or after `timeLimitMilliseconds`: a number, 0 or more, or `Infinity`; anything else rejects with `RangeError` before submitting. No wait runs past that deadline; the last read happens at it. It resolves with the calculated household, `warnings`, `spmConfig`, `spmProvenance`, the calculation ID and the versions it ran with. It throws: diff --git a/packages/public-api-forwarding/src/householdCalculation.ts b/packages/public-api-forwarding/src/householdCalculation.ts index df9d66db3b..7bc098b04d 100644 --- a/packages/public-api-forwarding/src/householdCalculation.ts +++ b/packages/public-api-forwarding/src/householdCalculation.ts @@ -620,10 +620,21 @@ export function createHouseholdCalculator( return { async calculateHousehold(request, options = {}) { const { signal } = options; - const deadline = - now() + - (options.timeLimitMilliseconds ?? - HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS); + const timeLimitMilliseconds = + options.timeLimitMilliseconds ?? + HOUSEHOLD_CALCULATION_TIME_LIMIT_MILLISECONDS; + // Anything else would make a deadline that never comes, or waits that + // setTimeout runs at once. + if ( + typeof timeLimitMilliseconds !== "number" || + Number.isNaN(timeLimitMilliseconds) || + timeLimitMilliseconds < 0 + ) { + throw new RangeError( + `timeLimitMilliseconds must be a number, 0 or more, or Infinity; got ${String(timeLimitMilliseconds)}.`, + ); + } + const deadline = now() + timeLimitMilliseconds; const submitted = await submit(request, deadline, signal); return readUntilFinished(submitted, deadline, signal); }, From 46576157101d106eddaabce174a48ed0c4201b39 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:46:21 +0400 Subject: [PATCH 05/10] Test review round 1's findings and the separate axes field 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 --- .../tests/forward.test.ts | 61 ++- .../tests/householdCalculation.test.ts | 397 +++++++++++++++++- 2 files changed, 448 insertions(+), 10 deletions(-) diff --git a/packages/public-api-forwarding/tests/forward.test.ts b/packages/public-api-forwarding/tests/forward.test.ts index 29e21c86de..e8fb57591f 100644 --- a/packages/public-api-forwarding/tests/forward.test.ts +++ b/packages/public-api-forwarding/tests/forward.test.ts @@ -777,37 +777,82 @@ describe("fetchFromServer", () => { }); test("given the caller's signal aborts then it rejects with the signal's reason", async () => { - // Given an API v1 that answers only when the request is aborted - const forwarder = createPublicApiForwarder({ - environment: PREVIEW_ENVIRONMENT_WITHOUT_CREDENTIAL, - callerName: "policyengine-test-caller", - sharedTokenStore: null, - clientAddress: () => undefined, - fetchImplementation: (_input, init) => + // Given an API v1 that answers only when the request is aborted, and + // says when the request has started + let requestStarted: () => void = () => {}; + const started = new Promise((resolve) => { + requestStarted = resolve; + }); + const fetchImplementation = vi.fn( + (_input: RequestInfo | URL, init?: RequestInit) => new Promise((_resolve, reject) => { init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), ); + requestStarted(); }), + ); + const forwarder = createPublicApiForwarder({ + environment: PREVIEW_ENVIRONMENT_WITHOUT_CREDENTIAL, + callerName: "policyengine-test-caller", + sharedTokenStore: null, + clientAddress: () => undefined, + fetchImplementation, logger: silentLogger, }); const controller = new AbortController(); const callerLeft = new Error("The caller went away."); - // When + // When the caller aborts while the request is in flight const pendingRequest = forwarder .fetchFromServer(DEPLOYMENT_REPORT_REQUEST, { signal: controller.signal, timeoutMilliseconds: 1_000, }) .catch((error: unknown) => error); + await started; controller.abort(callerLeft); const failure = await pendingRequest; // Then + expect(fetchImplementation).toHaveBeenCalledTimes(1); expect(failure).toBe(callerLeft); }); + test("given the caller aborts while the token is fetched and the token request fails then it rejects with the signal's reason", async () => { + // Given a token request that fails only when the test says so + let tokenRequested: () => void = () => {}; + const requested = new Promise((resolve) => { + tokenRequested = resolve; + }); + let failTokenRequest: () => void = () => {}; + const tokenFailure = new Promise((resolve) => { + failTokenRequest = () => + resolve(jsonResponse({ error: "access_denied" }, 403)); + }); + const { forwarder, publicApiCalls } = forwarderWith({ + tokenAnswer: () => { + tokenRequested(); + return tokenFailure; + }, + }); + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + + // When + const pendingRequest = forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST, { signal: controller.signal }) + .catch((error: unknown) => error); + await requested; + controller.abort(callerLeft); + failTokenRequest(); + const failure = await pendingRequest; + + // Then + expect(failure).toBe(callerLeft); + expect(publicApiCalls()).toHaveLength(0); + }); + test("given the token request fails then the error says the request never reached API v1", async () => { // Given const { forwarder } = forwarderWith({ diff --git a/packages/public-api-forwarding/tests/householdCalculation.test.ts b/packages/public-api-forwarding/tests/householdCalculation.test.ts index fd445942f8..a17a8103bd 100644 --- a/packages/public-api-forwarding/tests/householdCalculation.test.ts +++ b/packages/public-api-forwarding/tests/householdCalculation.test.ts @@ -64,6 +64,18 @@ const INVALID_INPUT_ERROR = { type CalculationStatus = "pending" | "running" | "succeeded" | "failed"; +const EMPLOYMENT_INCOME_AXES = [ + [ + { + name: "employment_income", + count: 401, + min: 0, + max: 200_000, + period: 2026, + }, + ], +]; + function submittedAnswer(): Response { return jsonResponse( { @@ -86,15 +98,16 @@ function submittedAnswer(): Response { } function calculationAnswer( - status: CalculationStatus, + status: CalculationStatus | "queued", outcome: { result?: unknown; error?: unknown } = {}, + calculationId = CALCULATION_ID, ): Response { return jsonResponse({ status: "ok", message: null, result: { item: { - calculation_id: CALCULATION_ID, + calculation_id: calculationId, country_id: "us", household_id: null, policy_id: null, @@ -141,6 +154,26 @@ function errorAnswer( ); } +/** An answer whose body is lost while it arrives: reading it rejects. */ +function lostBodyAnswer(statusCode: number): Response { + return new Response( + new ReadableStream({ + start(controller) { + controller.error(new TypeError("terminated")); + }, + }), + { status: statusCode, headers: { "Content-Type": "application/json" } }, + ); +} + +/** A 503 from Cloud Run in front of API v1: plain text, not API v1's envelope. */ +function cloudRunUnavailableAnswer(): Response { + return new Response("Service Unavailable", { + status: 503, + headers: { "Content-Type": "text/html" }, + }); +} + type ScriptedAnswer = Response | Error; interface RecordedRequest { @@ -738,4 +771,364 @@ describe("calculateHousehold", () => { expect(calculated.calculationId).toBe(CALCULATION_ID); expect(api.reads()).toHaveLength(401); }); + test("given a household with axes then the submission sends them as a separate axes field", async () => { + // Given + const householdWithAxes = { ...US_SITUATION, axes: EMPLOYMENT_INCOME_AXES }; + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + await api.calculator.calculateHousehold({ + country: "us", + household: householdWithAxes, + policy: CHILD_TAX_CREDIT_REFORM, + }); + + // Then + expect(submittedBody(api.submissions()[0])).toEqual({ + country_id: "us", + household: US_SITUATION, + policy: CHILD_TAX_CREDIT_REFORM, + axes: EMPLOYMENT_INCOME_AXES, + }); + expect(householdWithAxes.axes).toBe(EMPLOYMENT_INCOME_AXES); + }); + + test("given the default time limit then the submission may take until the deadline and each read 30 seconds", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("running"), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(api.submissions()[0].options?.timeoutMilliseconds).toBe(600_000); + expect( + api.reads().map(({ options }) => options?.timeoutMilliseconds), + ).toEqual([30_000, 30_000]); + }); + + test("given a short time limit then the submission still gets 30 seconds", async () => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 5_000, + }); + + // Then + expect(api.submissions()[0].options?.timeoutMilliseconds).toBe(30_000); + }); + + test("given the submission gets a 503 that is not API v1's own then it throws without submitting again", async () => { + // Given + const api = fakeApiV1(inOrder([cloudRunUnavailableAnswer()])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 503, body: null }); + expect(api.submissions()).toHaveLength(1); + }); + + test("given a submission retry would wait until the deadline then it throws the last failure without submitting again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + errorAnswer(503, "No job will run", {}, { "Retry-After": "10" }), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 5_000, + }), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 503 }); + expect(api.submissions()).toHaveLength(1); + expect(api.waits).toEqual([]); + }); + + test("given a time limit of 0 then it submits, reads once and throws HouseholdCalculationTimeoutError", async () => { + // Given + const api = fakeApiV1( + inOrder([submittedAnswer(), calculationAnswer("running")]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 0, + }), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationTimeoutError); + expect(failure).toMatchObject({ lastStatus: "running" }); + expect(api.reads()).toHaveLength(1); + }); + + test("given the submission's connection fails after sending then it throws without submitting again", async () => { + // Given + const connectionLost = new PublicApiUnavailableError( + "The Public API could not be reached.", + 502, + true, + ); + const api = fakeApiV1(inOrder([connectionLost])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(connectionLost); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the submission's answer is lost while it arrives then it throws without submitting again", async () => { + // Given + const api = fakeApiV1(inOrder([lostBodyAnswer(202)])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(PublicApiUnavailableError); + expect(failure).toMatchObject({ requestMayHaveArrived: true }); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the submission answers 429 then it throws without submitting again", async () => { + // Given + const api = fakeApiV1(inOrder([errorAnswer(429, "Too many requests")])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toMatchObject({ statusCode: 429 }); + expect(api.submissions()).toHaveLength(1); + }); + + test("given the submission answers 503 for 90 seconds then it throws the last answer", async () => { + // Given + const api = fakeApiV1(() => errorAnswer(503, "No job will run")); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ statusCode: 503 }); + expect(api.submissions().at(-1)?.atMilliseconds).toBe(90_000); + expect(api.submissions()).toHaveLength(46); + }); + + test("given a read's answer is lost while it arrives then it reads again", async () => { + // Given + const api = fakeApiV1( + inOrder([submittedAnswer(), lostBodyAnswer(200), succeededAnswer()]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.reads()).toHaveLength(2); + }); + + test("given the credential cannot be obtained for a read then it reads again", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + new PublicApiUnavailableError( + "Could not obtain a credential for the Public API.", + 502, + false, + ), + succeededAnswer(), + ]), + ); + + // When + const calculated = + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.reads()).toHaveLength(2); + }); + + test("given API v1 is no longer configured when it reads then it throws without reading again", async () => { + // Given + const notConfigured = new PublicApiUnavailableError( + "The Public API is not configured on this deployment.", + 503, + false, + ); + const api = fakeApiV1(inOrder([submittedAnswer(), notConfigured])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(notConfigured); + expect(api.reads()).toHaveLength(1); + }); + + test("given a read answers 429 with Retry-After then it waits that many seconds", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer(429, "Too many requests", {}, { "Retry-After": "5" }), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(api.waits).toEqual([2_000, 5_000]); + }); + + test("given a Retry-After that is a date then it waits one interval", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + errorAnswer( + 503, + "Storage is unavailable", + {}, + { "Retry-After": "Sat, 28 Nov 2026 12:00:00 GMT" }, + ), + succeededAnswer(), + ]), + ); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + expect(api.waits).toEqual([2_000, 2_000]); + }); + + test.each([ + [ + "another calculation's ID", + () => + calculationAnswer( + "running", + {}, + "00000000-0000-4000-8000-000000000000", + ), + ], + ["an unknown status", () => calculationAnswer("queued")], + ["a failure without its error", () => calculationAnswer("failed")], + ["a success without its result", () => calculationAnswer("succeeded")], + ])( + "given a read answer with %s then it throws HouseholdCalculationRefusedError", + async (_description, unreadableAnswer) => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), unreadableAnswer()])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationRefusedError); + expect(failure).toMatchObject({ + statusCode: 200, + calculationId: CALCULATION_ID, + }); + expect(api.reads()).toHaveLength(1); + }, + ); + + test("given a failure without a code then HouseholdCalculationFailedError has a null code", async () => { + // Given + const api = fakeApiV1( + inOrder([ + submittedAnswer(), + calculationAnswer("failed", { + error: { + code: null, + message: "household_function_error: worker ran out of memory", + input_errors: [], + spm_error: null, + }, + }), + ]), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationFailedError); + expect(failure).toMatchObject({ + code: null, + message: "household_function_error: worker ran out of memory", + inputErrors: [], + }); + }); + + test("given the signal aborts while an answer arrives then it rejects with the abort reason", async () => { + // Given + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + const abortingAnswer = new Response( + new ReadableStream({ + start(streamController) { + controller.abort(callerLeft); + streamController.error(new DOMException("aborted", "AbortError")); + }, + }), + { status: 202 }, + ); + const api = fakeApiV1(inOrder([abortingAnswer])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + signal: controller.signal, + }), + ); + + // Then + expect(failure).toBe(callerLeft); + }); }); From ce2d63f682ebf72dd86b6500f2bf2be63a64cfd9 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:49:54 +0400 Subject: [PATCH 06/10] Fix review round 1's findings and send axes as their own field - 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 --- packages/public-api-forwarding/README.md | 28 +-- packages/public-api-forwarding/src/forward.ts | 13 +- .../src/householdCalculation.ts | 168 +++++++++++++----- packages/public-api-forwarding/src/index.ts | 1 + 4 files changed, 144 insertions(+), 66 deletions(-) diff --git a/packages/public-api-forwarding/README.md b/packages/public-api-forwarding/README.md index a46ed4ddff..b495093b24 100644 --- a/packages/public-api-forwarding/README.md +++ b/packages/public-api-forwarding/README.md @@ -45,7 +45,7 @@ The Auth0 token request never follows a redirect, which would re-send the client `isJsonMediaType()` is the JSON content-type check the package and its routes share: `application/json` or any `application/...+json` type. -`fetchFromServer()` also takes a `signal`. When it aborts, the request stops and `fetchFromServer()` rejects with the signal's reason. Its `PublicApiUnavailableError` says in `requestMayHaveArrived` whether API v1 may have received the request: `false` when it was never sent (an unknown path, no configuration, or no credential), `true` when the connection failed or timed out after sending. +`fetchFromServer()` also takes a `signal`. When it aborts, the request stops and `fetchFromServer()` rejects with the signal's reason. Its `PublicApiUnavailableError` says in `requestMayHaveArrived` whether API v1 may have received the request: `false` when it was never sent (an unknown path, no configuration, or no credential), `true` when fetch rejected or timed out. Fetch doesn't say whether anything was sent, so it is `true` even for a connection refused before sending. An abort while the credential is being fetched also rejects with the signal's reason. ## Household calculations @@ -58,7 +58,7 @@ const calculator = createHouseholdCalculator({ forwarder: websitePublicApi }); const calculated = await calculator.calculateHousehold( { country: "us", - household: situation, // /calculate's situation, axes included + household: situation, // /calculate's situation; its axes are sent separately policy: { "gov.irs.credits.ctc.amount.base[0].amount": { "2026-01-01.2100-12-31": 3000, @@ -72,14 +72,16 @@ calculated.household; // what /calculate answered as `result` What it does, through `fetchFromServer()`: -1. Submits `{country_id, household, policy?, add_missing_variables?, spm?}` to `POST /v2/household-calculations`. API v1 keeps the calculation as a household job only: no stored household, policy or user association. +1. Submits `{country_id, household, policy?, axes?, add_missing_variables?, spm?}` to `POST /v2/household-calculations`. `household` is the situation without its `axes`, which go in the request's own `axes` field; the caller's object is not changed. API v1 keeps the calculation as a household job only: no stored household, policy or user association. 2. Reads `GET /v2/household-calculations/{calculation_id}` every 2 seconds until the calculation succeeds or fails. -3. Gives up 10 minutes after the call starts, or after `timeLimitMilliseconds`: a number, 0 or more, or `Infinity`; anything else rejects with `RangeError` before submitting. No wait runs past that deadline; the last read happens at it. +3. Gives up 10 minutes after the call starts, or after `timeLimitMilliseconds`: a number, 0 or more, or `Infinity`; anything else rejects with `RangeError` before submitting. No wait runs past that deadline; the last read happens at it, and an accepted calculation is read at least once, even with a limit of 0. + +The submission may take until the deadline, and at least 30 seconds: it may wait for an API v1 instance to start, which takes minutes after the service has scaled to zero, and timing it out sooner would leave a job that may exist. Each read takes at most 30 seconds. So a request in flight at the deadline may take up to 30 seconds more; with the 10-minute default, a call ends within about 10.5 minutes. It resolves with the calculated household, `warnings`, `spmConfig`, `spmProvenance`, the calculation ID and the versions it ran with. It throws: - `HouseholdCalculationFailedError` when the calculation fails, with the household function's `code` (such as `invalid_inputs`), `inputErrors` and `spmError`. A null `code` means the function raised or was cancelled, and submitting again may succeed. -- `HouseholdCalculationTimeoutError` when the time limit passes, with the calculation ID and the last status read. +- `HouseholdCalculationTimeoutError` when the time limit passes, with the calculation ID and the last status read (the submission's status if no read succeeded). - `HouseholdCalculationRefusedError` when API v1 refuses a request or its answer cannot be read, with the HTTP status, API v1's message and `code` (such as `missing_parameters`), the parsed body, `Retry-After` and the observability and request IDs. - `PublicApiUnavailableError` when API v1 cannot be called. - The signal's reason when the signal aborts. @@ -87,20 +89,20 @@ It resolves with the calculated household, `warnings`, `spmConfig`, `spmProvenan Brief outages are retried until 90 seconds pass without a good answer: - **Reads** are retried on 429, 502, 503 and 504, and when API v1 cannot be reached, does not answer in time, or the credential cannot be obtained. A 429 or 503 with `Retry-After` waits that many seconds, or 2 seconds if that is longer; anything else waits 2 seconds. -- **The submission** is retried only when no job can exist: on API v1's 503, which it answers when no job of the submission will run, and when the credential cannot be obtained, so the request was never sent. It is not retried on a 502, or when the connection fails or times out after sending, because API v1 may have created the job and submitting again would create a second one. +- **The submission** is retried only when no job can exist: on API v1's own 503 (with its `{status: "error", message}` body), which it answers when no job of the submission will run, and when the credential cannot be obtained, so the request was never sent. It is not retried on any other 503, such as Cloud Run's plain-text one when its connection to an instance fails; on a 502; or when fetch rejects or times out after the request was handed to it: in each case API v1 may have created the job, and submitting again would create a second one. Nor is it retried when the wait before it would reach the deadline, since the calculation could then not be read. - Nothing else is retried, including 400, 401, 403, 404, 409, 413, 422 and 500. How `calculated` differs from `/calculate`'s answer: there is no `{status, message, result}` envelope; `warnings` and `spm_provenance` are fields of the result, as `warnings` and `spmProvenance`; and inputs the model does not recognise come back as a failed calculation (`code: "invalid_inputs"`, `inputErrors`), thrown as `HouseholdCalculationFailedError`, not as a 400 with `errors`. ## Configuration -| Variable | Meaning | -| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| `POLICYENGINE_API_URL` | The Public API's base URL, https (or http on localhost). Required outside production. | -| `POLICYENGINE_API_AUTH0_DOMAIN` | Host of the Auth0 token endpoint. Tokens carry this host as their issuer, so it must be the issuer the Public API checks. | -| `POLICYENGINE_API_AUTH0_AUDIENCE` | The Auth0 API identifier the token is for. | -| `POLICYENGINE_API_AUTH0_CLIENT_ID` | The caller's own Auth0 machine-to-machine client. | -| `POLICYENGINE_API_AUTH0_CLIENT_SECRET` | That client's secret. Read on the server only; never put it in a `NEXT_PUBLIC_*` or `VITE_*` variable. | +| Variable | Meaning | +| --- | --- | +| `POLICYENGINE_API_URL` | The Public API's base URL, https (or http on localhost). Required outside production. | +| `POLICYENGINE_API_AUTH0_DOMAIN` | Host of the Auth0 token endpoint. Tokens carry this host as their issuer, so it must be the issuer the Public API checks. | +| `POLICYENGINE_API_AUTH0_AUDIENCE` | The Auth0 API identifier the token is for. | +| `POLICYENGINE_API_AUTH0_CLIENT_ID` | The caller's own Auth0 machine-to-machine client. | +| `POLICYENGINE_API_AUTH0_CLIENT_SECRET` | That client's secret. Read on the server only; never put it in a `NEXT_PUBLIC_*` or `VITE_*` variable. | Production deployments use the production Public API and a production Auth0 client. Preview and development deployments use the Public API's staging service and a staging client. For local work, `vercel env pull` writes the development values. diff --git a/packages/public-api-forwarding/src/forward.ts b/packages/public-api-forwarding/src/forward.ts index 0a3f75bf58..c0ae7b395d 100644 --- a/packages/public-api-forwarding/src/forward.ts +++ b/packages/public-api-forwarding/src/forward.ts @@ -78,9 +78,11 @@ export class PublicApiUnavailableError extends Error { /** The status a route would answer with for this failure. */ readonly statusCode: number, /** - * False when the request was never sent, so sending it again cannot - * repeat it. True when it was sent and the connection failed or timed - * out, so API v1 may have received it and acted on it. + * False when the request was never sent (an unknown path, no + * configuration, or no credential), so sending it again cannot repeat + * it. True when fetch rejected or timed out: API v1 may have received + * the request and acted on it. Fetch doesn't say whether anything was + * sent, so this is true even for a connection refused before sending. */ readonly requestMayHaveArrived: boolean = false, ) { @@ -481,11 +483,12 @@ export function createPublicApiForwarder( const callerSignal = serverOptions.signal; callerSignal?.throwIfAborted(); const connection = await connect(publicApiRequest); + // Getting the token can take a while; the caller may have left meanwhile, + // and then the abort is the answer, not a failed token request. + callerSignal?.throwIfAborted(); if (!connection.ok) { throw connection.error; } - // Getting the token can take a while; the caller may have left meanwhile. - callerSignal?.throwIfAborted(); const { upstreamUrl, serverToken } = connection; const headers = new Headers({ diff --git a/packages/public-api-forwarding/src/householdCalculation.ts b/packages/public-api-forwarding/src/householdCalculation.ts index 7bc098b04d..03e670cbdd 100644 --- a/packages/public-api-forwarding/src/householdCalculation.ts +++ b/packages/public-api-forwarding/src/householdCalculation.ts @@ -9,6 +9,7 @@ // fetchFromServer, which adds the server credential. import { + DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, PublicApiUnavailableError, type PublicApiForwarder, type PublicApiRequest, @@ -29,8 +30,10 @@ const SUBMISSION_PATH = "/v2/household-calculations"; const RETRIED_READ_STATUSES = new Set([429, 502, 503, 504]); /** * The submission answer after which API v1 says no job will run, so - * submitting again cannot create a second one. A 502 is not retried: API v1 - * answers it when the job may exist. + * submitting again cannot create a second one. It counts only with API v1's + * own error body: Cloud Run, in front of API v1, also answers 503 when its + * connection to an instance fails mid-request, after which the job may + * exist. A 502 is never retried: API v1 answers it when the job may exist. */ const RETRIED_SUBMISSION_STATUSES = new Set([503]); /** Answers whose Retry-After the helper waits out. */ @@ -48,24 +51,28 @@ export type HouseholdCalculationStatus = | "running" | "succeeded" | "failed"; -type UnfinishedStatus = "pending" | "running"; +/** The statuses of a calculation that has not finished yet. */ +export type HouseholdCalculationUnfinishedStatus = "pending" | "running"; type JsonObject = Record; /** A household to calculate, as POST /{country}/calculate takes it. */ export interface InlineHouseholdCalculationRequest { readonly country: HouseholdCalculationCountry; - /** The household in the situation shape, axes included. */ - readonly household: Readonly; + /** + * The household in the situation shape. Its `axes`, if any, are sent as + * the request's own `axes` field, which is where API v1 takes them. + */ + readonly household: Readonly>; /** * Parameter changes keyed by parameter path, each mapping a period such as * "2026-01-01.2100-12-31" to a value. Current law when omitted. */ - readonly policy?: Readonly; + readonly policy?: Readonly>; /** Adds every variable the household lacks, as /calculate-full does. */ readonly addMissingVariables?: boolean; /** SPM settings for a US household. */ - readonly spm?: Readonly; + readonly spm?: Readonly>; } export interface HouseholdCalculationOptions { @@ -73,7 +80,9 @@ export interface HouseholdCalculationOptions { readonly signal?: AbortSignal; /** * How long after the call starts to give up, 10 minutes by default. The - * last read happens at the deadline. + * last read happens at the deadline, and an accepted calculation is read + * at least once. A request in flight at the deadline may take up to 30 + * seconds more. */ readonly timeLimitMilliseconds?: number; } @@ -85,13 +94,13 @@ export interface CalculatedHousehold { * The household with each calculated value filled in by period, in the * shape /calculate answered as `result`. */ - readonly household: JsonObject; + readonly household: Record; /** Inputs the country model ignored. */ readonly warnings: readonly string[]; /** For a US household, the SPM selection the calculation applied. */ - readonly spmConfig: JsonObject | null; + readonly spmConfig: Record | null; /** For a US household, the receipt of the SPM forecast it used. */ - readonly spmProvenance: JsonObject | null; + readonly spmProvenance: Record | null; readonly countryPackageVersion: string; readonly policyengineVersion: string; } @@ -134,9 +143,9 @@ export class HouseholdCalculationFailedError extends Error { */ readonly code: string | null, /** For "invalid_inputs", each input the country model does not recognise. */ - readonly inputErrors: readonly JsonObject[], + readonly inputErrors: readonly Record[], /** For "invalid_spm_selection", what is wrong with the SPM settings. */ - readonly spmError: JsonObject | null, + readonly spmError: Record | null, ) { super(message); } @@ -152,8 +161,11 @@ export class HouseholdCalculationTimeoutError extends Error { constructor( message: string, readonly calculationId: string, - /** The status the last successful read gave. */ - readonly lastStatus: UnfinishedStatus, + /** + * The status the last successful read gave, or the submission's when no + * read succeeded. + */ + readonly lastStatus: HouseholdCalculationUnfinishedStatus, ) { super(message); } @@ -210,7 +222,7 @@ interface ApiV1Answer { interface SubmittedCalculation { readonly calculationId: string; - readonly status: UnfinishedStatus; + readonly status: HouseholdCalculationUnfinishedStatus; } function isJsonObject(value: unknown): value is JsonObject { @@ -255,13 +267,19 @@ function waitWithTimer( }); } +/** + * API v1's inline request: the situation without its axes, which go in the + * request's own `axes` field. + */ function submissionBody( request: InlineHouseholdCalculationRequest, ): JsonObject { + const { axes, ...householdWithoutAxes } = request.household; return { country_id: request.country, - household: request.household, + household: householdWithoutAxes, ...(request.policy === undefined ? {} : { policy: request.policy }), + ...(axes === undefined ? {} : { axes }), ...(request.addMissingVariables === undefined ? {} : { add_missing_variables: request.addMissingVariables }), @@ -305,13 +323,27 @@ function unreadable( ); } +/** `result.item` of a success answer, when the answer has one. */ +function resultItem(body: unknown): JsonObject | undefined { + const result = isJsonObject(body) ? body.result : undefined; + const item = isJsonObject(result) ? result.item : undefined; + return isJsonObject(item) ? item : undefined; +} + +/** Whether a body is API v1's own error answer: `{status: "error", message}`. */ +function isApiV1ErrorBody(body: unknown): boolean { + return ( + isJsonObject(body) && + body.status === "error" && + typeof body.message === "string" + ); +} + /** The accepted calculation in a submission's answer. */ function readSubmitted(answer: ApiV1Answer): SubmittedCalculation { - const item = isJsonObject(answer.body) - ? (answer.body.result as JsonObject | undefined)?.item - : undefined; - const calculationId = isJsonObject(item) ? item.calculation_id : undefined; - const status = isJsonObject(item) ? item.status : undefined; + const item = resultItem(answer.body); + const calculationId = item?.calculation_id; + const status = item?.status; if ( typeof calculationId !== "string" || !CALCULATION_ID_PATTERN.test(calculationId) || @@ -327,7 +359,7 @@ function readSubmitted(answer: ApiV1Answer): SubmittedCalculation { } type CalculationRead = - | { readonly status: UnfinishedStatus } + | { readonly status: HouseholdCalculationUnfinishedStatus } | { readonly status: "succeeded"; readonly calculated: CalculatedHousehold } | { readonly status: "failed"; @@ -345,10 +377,8 @@ function readCalculation( calculationId, `API v1's answer for household calculation ${calculationId} cannot be read.`, ); - const item = isJsonObject(answer.body) - ? (answer.body.result as JsonObject | undefined)?.item - : undefined; - if (!isJsonObject(item) || item.calculation_id !== calculationId) { + const item = resultItem(answer.body); + if (item === undefined || item.calculation_id !== calculationId) { throw cannotRead(); } @@ -453,12 +483,16 @@ export function createHouseholdCalculator( async function send( request: PublicApiRequest, signal: AbortSignal | undefined, + timeoutMilliseconds: number, ): Promise { - const response = await forwarder.fetchFromServer(request, { signal }); + const response = await forwarder.fetchFromServer(request, { + signal, + timeoutMilliseconds, + }); let text: string; try { text = await response.text(); - } catch (error) { + } catch { if (signal?.aborted) { throw signal.reason; } @@ -478,7 +512,12 @@ export function createHouseholdCalculator( return { response, body }; } - /** How long to wait before trying again after a retried answer. */ + /** + * How long to wait before trying again after a retried answer: its + * Retry-After for a 429 or 503, but never less than one interval, so + * that a Retry-After of 0 cannot make the helper send requests back to + * back. + */ function retryWaitMilliseconds(response: Response): number { const seconds = RETRY_AFTER_STATUSES.has(response.status) ? retryAfterSeconds(response) @@ -491,20 +530,20 @@ export function createHouseholdCalculator( ); } - /** Waits, but never past the deadline; false when no time is left. */ - async function waitWithin( + /** + * Waits before submitting again, and true; or false, without waiting, + * when the wait would reach the deadline, since a calculation submitted + * then could not be read. + */ + async function waitToResubmit( milliseconds: number, deadline: number, signal: AbortSignal | undefined, ): Promise { - const remainingMilliseconds = deadline - now(); - if (remainingMilliseconds <= 0) { + if (now() + milliseconds >= deadline) { return false; } - await wait( - Math.min(milliseconds, remainingMilliseconds, LONGEST_TIMER_MILLISECONDS), - signal, - ); + await wait(Math.min(milliseconds, LONGEST_TIMER_MILLISECONDS), signal); return true; } @@ -520,17 +559,26 @@ export function createHouseholdCalculator( for (;;) { signal?.throwIfAborted(); + // A submission may wait for an API v1 instance to start, which can + // take minutes, so it may take until the deadline (at least the + // forwarder's usual 30 seconds). Timing it out sooner would leave a + // job that may exist, which the helper must not submit again. + const timeoutMilliseconds = Math.min( + Math.max(DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, deadline - now()), + LONGEST_TIMER_MILLISECONDS, + ); let answer: ApiV1Answer; try { answer = await send( { method: "POST", path: SUBMISSION_PATH, body }, signal, + timeoutMilliseconds, ); } catch (error) { if ( !isUnsentCredentialFailure(error) || !canRetry() || - !(await waitWithin( + !(await waitToResubmit( HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS, deadline, signal, @@ -547,8 +595,9 @@ export function createHouseholdCalculator( const failure = refusal(answer, null); if ( !RETRIED_SUBMISSION_STATUSES.has(answer.response.status) || + !isApiV1ErrorBody(answer.body) || !canRetry() || - !(await waitWithin( + !(await waitToResubmit( retryWaitMilliseconds(answer.response), deadline, signal, @@ -566,31 +615,48 @@ export function createHouseholdCalculator( ): Promise { const { calculationId } = submitted; const path = `${SUBMISSION_PATH}/${calculationId}`; - let lastStatus: UnfinishedStatus = submitted.status; + let lastStatus: HouseholdCalculationUnfinishedStatus = submitted.status; let lastGoodAnswerAt = now(); let nextWaitMilliseconds = HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS; const outageLimitReached = () => now() - lastGoodAnswerAt >= HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS; + const timedOut = () => + new HouseholdCalculationTimeoutError( + `Household calculation ${calculationId} did not finish in time.`, + calculationId, + lastStatus, + ); + // Wait, read, then stop if the deadline has come: so the accepted + // calculation is read at least once, and the last read happens at the + // deadline. for (;;) { - if (!(await waitWithin(nextWaitMilliseconds, deadline, signal))) { - throw new HouseholdCalculationTimeoutError( - `Household calculation ${calculationId} did not finish in time.`, - calculationId, - lastStatus, - ); + const waitMilliseconds = Math.min( + nextWaitMilliseconds, + Math.max(deadline - now(), 0), + LONGEST_TIMER_MILLISECONDS, + ); + if (waitMilliseconds > 0) { + await wait(waitMilliseconds, signal); } signal?.throwIfAborted(); nextWaitMilliseconds = HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS; let answer: ApiV1Answer; try { - answer = await send({ method: "GET", path }, signal); + answer = await send( + { method: "GET", path }, + signal, + DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, + ); } catch (error) { if (!isBriefOutage(error) || outageLimitReached()) { throw error; } + if (now() >= deadline) { + throw timedOut(); + } continue; } @@ -601,6 +667,9 @@ export function createHouseholdCalculator( ) { throw refusal(answer, calculationId); } + if (now() >= deadline) { + throw timedOut(); + } nextWaitMilliseconds = retryWaitMilliseconds(answer.response); continue; } @@ -614,6 +683,9 @@ export function createHouseholdCalculator( throw calculation.failure; } lastStatus = calculation.status; + if (now() >= deadline) { + throw timedOut(); + } } } diff --git a/packages/public-api-forwarding/src/index.ts b/packages/public-api-forwarding/src/index.ts index c225f46d29..3a0f6058a2 100644 --- a/packages/public-api-forwarding/src/index.ts +++ b/packages/public-api-forwarding/src/index.ts @@ -44,6 +44,7 @@ export { type HouseholdCalculationOptions, type HouseholdCalculationRefusal, type HouseholdCalculationStatus, + type HouseholdCalculationUnfinishedStatus, type HouseholdCalculator, type HouseholdCalculatorDependencies, type InlineHouseholdCalculationRequest, From 44705569049695d3ba7d3c14a01df4be7c51d475 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:03:43 +0400 Subject: [PATCH 07/10] Test review round 2's findings 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 --- .../tests/forward.test.ts | 71 +++++++++- .../tests/householdCalculation.test.ts | 124 +++++++++++++++--- 2 files changed, 173 insertions(+), 22 deletions(-) diff --git a/packages/public-api-forwarding/tests/forward.test.ts b/packages/public-api-forwarding/tests/forward.test.ts index e8fb57591f..397681aabb 100644 --- a/packages/public-api-forwarding/tests/forward.test.ts +++ b/packages/public-api-forwarding/tests/forward.test.ts @@ -819,7 +819,7 @@ describe("fetchFromServer", () => { expect(failure).toBe(callerLeft); }); - test("given the caller aborts while the token is fetched and the token request fails then it rejects with the signal's reason", async () => { + test("given the caller aborts while the token is fetched then it rejects with the signal's reason without waiting for the token request", async () => { // Given a token request that fails only when the test says so let tokenRequested: () => void = () => {}; const requested = new Promise((resolve) => { @@ -839,14 +839,14 @@ describe("fetchFromServer", () => { const controller = new AbortController(); const callerLeft = new Error("The caller went away."); - // When + // When the caller aborts while the token request is still running const pendingRequest = forwarder .fetchFromServer(DEPLOYMENT_REPORT_REQUEST, { signal: controller.signal }) .catch((error: unknown) => error); await requested; controller.abort(callerLeft); - failTokenRequest(); const failure = await pendingRequest; + failTokenRequest(); // Then expect(failure).toBe(callerLeft); @@ -868,6 +868,7 @@ describe("fetchFromServer", () => { expect(failure).toBeInstanceOf(PublicApiUnavailableError); expect(failure).toMatchObject({ statusCode: 502, + reason: "credential_unavailable", requestMayHaveArrived: false, }); }); @@ -889,6 +890,70 @@ describe("fetchFromServer", () => { expect(failure).toBeInstanceOf(PublicApiUnavailableError); expect(failure).toMatchObject({ statusCode: 502, + reason: "unreachable", + requestMayHaveArrived: true, + }); + }); + + test("given a path that could leave API v1 then the error names an unknown route that was never sent", async () => { + // Given + const { forwarder } = forwarderWith(); + + // When + const failure = await forwarder + .fetchFromServer({ method: "GET", path: "/../deployment" }) + .catch((error: unknown) => error); + + // Then + expect(failure).toMatchObject({ + reason: "unknown_route", + requestMayHaveArrived: false, + }); + }); + + test("given no API v1 URL on a preview deployment then the error names a missing configuration that was never sent", async () => { + // Given + const { forwarder } = forwarderWith({ + environment: { VERCEL_ENV: "preview" }, + }); + + // When + const failure = await forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST) + .catch((error: unknown) => error); + + // Then + expect(failure).toMatchObject({ + reason: "not_configured", + requestMayHaveArrived: false, + }); + }); + + test("given API v1 does not answer in time then the error names a timeout that may have arrived", async () => { + // Given an API v1 that answers only when the request is aborted + const forwarder = createPublicApiForwarder({ + environment: PREVIEW_ENVIRONMENT_WITHOUT_CREDENTIAL, + callerName: "policyengine-test-caller", + sharedTokenStore: null, + clientAddress: () => undefined, + fetchImplementation: (_input, init) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => + reject(new DOMException("timed out", "TimeoutError")), + ); + }), + logger: silentLogger, + }); + + // When + const failure = await forwarder + .fetchFromServer(DEPLOYMENT_REPORT_REQUEST, { timeoutMilliseconds: 10 }) + .catch((error: unknown) => error); + + // Then + expect(failure).toMatchObject({ + statusCode: 504, + reason: "timed_out", requestMayHaveArrived: true, }); }); diff --git a/packages/public-api-forwarding/tests/householdCalculation.test.ts b/packages/public-api-forwarding/tests/householdCalculation.test.ts index a17a8103bd..85f39d12f1 100644 --- a/packages/public-api-forwarding/tests/householdCalculation.test.ts +++ b/packages/public-api-forwarding/tests/householdCalculation.test.ts @@ -76,7 +76,7 @@ const EMPLOYMENT_INCOME_AXES = [ ], ]; -function submittedAnswer(): Response { +function submittedAnswer(status: CalculationStatus = "pending"): Response { return jsonResponse( { status: "ok", @@ -84,7 +84,7 @@ function submittedAnswer(): Response { result: { item: { calculation_id: CALCULATION_ID, - status: "pending", + status, country_id: "us", household_id: null, policy_id: null, @@ -195,6 +195,11 @@ function fakeApiV1( const waits: number[] = []; const fetchFromServer = vi.fn( async (request: PublicApiRequest, options?: ServerRequestOptions) => { + // fetchFromServer hands the timeout to AbortSignal.timeout, which + // throws for a value it cannot take; so does the fake. + if (options?.timeoutMilliseconds !== undefined) { + AbortSignal.timeout(options.timeoutMilliseconds); + } requests.push({ request, options, atMilliseconds: clock.milliseconds }); const answer = answerFor(request); if (answer instanceof Error) { @@ -453,7 +458,11 @@ describe("calculateHousehold", () => { const api = fakeApiV1( inOrder([ submittedAnswer(), - new PublicApiUnavailableError("Could not be reached.", 502, true), + new PublicApiUnavailableError( + "Could not be reached.", + 502, + "unreachable", + ), succeededAnswer(), ]), ); @@ -566,7 +575,7 @@ describe("calculateHousehold", () => { const timedOut = new PublicApiUnavailableError( "The Public API did not answer in time.", 504, - true, + "timed_out", ); const api = fakeApiV1(inOrder([timedOut])); @@ -587,7 +596,7 @@ describe("calculateHousehold", () => { new PublicApiUnavailableError( "Could not obtain a credential for the Public API.", 502, - false, + "credential_unavailable", ), submittedAnswer(), succeededAnswer(), @@ -608,7 +617,7 @@ describe("calculateHousehold", () => { const notConfigured = new PublicApiUnavailableError( "The Public API is not configured on this deployment.", 503, - false, + "not_configured", ); const api = fakeApiV1(inOrder([notConfigured])); @@ -887,7 +896,7 @@ describe("calculateHousehold", () => { const connectionLost = new PublicApiUnavailableError( "The Public API could not be reached.", 502, - true, + "unreachable", ); const api = fakeApiV1(inOrder([connectionLost])); @@ -969,7 +978,7 @@ describe("calculateHousehold", () => { new PublicApiUnavailableError( "Could not obtain a credential for the Public API.", 502, - false, + "credential_unavailable", ), succeededAnswer(), ]), @@ -989,7 +998,7 @@ describe("calculateHousehold", () => { const notConfigured = new PublicApiUnavailableError( "The Public API is not configured on this deployment.", 503, - false, + "not_configured", ); const api = fakeApiV1(inOrder([submittedAnswer(), notConfigured])); @@ -1110,16 +1119,22 @@ describe("calculateHousehold", () => { // Given const controller = new AbortController(); const callerLeft = new Error("The caller went away."); - const abortingAnswer = new Response( - new ReadableStream({ - start(streamController) { - controller.abort(callerLeft); - streamController.error(new DOMException("aborted", "AbortError")); - }, - }), - { status: 202 }, - ); - const api = fakeApiV1(inOrder([abortingAnswer])); + // Built when the submission is sent; the caller aborts only when the + // helper starts reading the answer's body. + const abortingAnswer = () => + new Response( + new ReadableStream( + { + pull(streamController) { + controller.abort(callerLeft); + streamController.error(new DOMException("aborted", "AbortError")); + }, + }, + { highWaterMark: 0 }, + ), + { status: 202 }, + ); + const api = fakeApiV1(() => abortingAnswer()); // When const failure = await failureOf( @@ -1130,5 +1145,76 @@ describe("calculateHousehold", () => { // Then expect(failure).toBe(callerLeft); + expect(api.submissions()).toHaveLength(1); + }); + test.each([ + [ + "succeeded", + () => succeededAnswer(), + async (outcome: Promise) => { + await expect(outcome).resolves.toMatchObject({ + household: CALCULATED_US_SITUATION, + }); + }, + ], + [ + "failed", + () => + calculationAnswer("failed", { + error: { + code: "invalid_household", + message: "The household has no people.", + input_errors: [], + spm_error: null, + }, + }), + async (outcome: Promise) => { + await expect(outcome).rejects.toBeInstanceOf( + HouseholdCalculationFailedError, + ); + }, + ], + ] as const)( + "given the submission answers that the calculation already %s then it reads it at once", + async (status, readAnswer, checkOutcome) => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(status), readAnswer()])); + + // When + const outcome = api.calculator.calculateHousehold(US_REFORM_REQUEST); + + // Then + await checkOutcome(outcome); + expect(api.reads()).toHaveLength(1); + expect(api.waits).toEqual([]); + }, + ); + + test("given a time limit that is not a whole number then the submission's timeout is whole milliseconds", async () => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + const calculated = await api.calculator.calculateHousehold( + US_REFORM_REQUEST, + { timeLimitMilliseconds: 45_000.5 }, + ); + + // Then + expect(calculated.calculationId).toBe(CALCULATION_ID); + expect(api.submissions()[0].options?.timeoutMilliseconds).toBe(45_001); + }); + + test("given an infinite time limit then the submission's timeout is the longest a timer can wait", async () => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), succeededAnswer()])); + + // When + await api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: Number.POSITIVE_INFINITY, + }); + + // Then + expect(api.submissions()[0].options?.timeoutMilliseconds).toBe(2 ** 31 - 1); }); }); From dfc695027ecaeb81d2d03005123102aaf43129bc Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:07:56 +0400 Subject: [PATCH 08/10] Fix review round 2's findings - 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 --- packages/public-api-forwarding/README.md | 34 ++++--- packages/public-api-forwarding/src/forward.ts | 98 ++++++++++++++++--- .../src/householdCalculation.ts | 86 ++++++++++++---- packages/public-api-forwarding/src/index.ts | 1 + 4 files changed, 171 insertions(+), 48 deletions(-) diff --git a/packages/public-api-forwarding/README.md b/packages/public-api-forwarding/README.md index b495093b24..e884166825 100644 --- a/packages/public-api-forwarding/README.md +++ b/packages/public-api-forwarding/README.md @@ -18,20 +18,19 @@ The calculator's pages reach the Public API only through its route (`BASE_URL` i - without one, it stays in `Authorization`, as on a direct browser call. Cookies, `Origin`, `Referer` and any `PolicyEngine-User-Authorization` the browser sends are dropped. - - **Streams the answer back** with an allow list of response headers (`Content-Type`, `ETag`, `Last-Modified`, `Retry-After`, `WWW-Authenticate` and the Public API's request IDs). `Content-Encoding` and `Content-Length` are dropped, because `fetch` has already decompressed the body. Streaming matters because Vercel caps a buffered function answer at 4.5 MB. - **Caches nothing it should not**: the route's `cacheControl` applies only to 2xx and 304 answers; every other answer is `no-store`, and so is every answer when the route gives none. - **Maps failures to JSON** in the Public API's own error shape, `{"status": "error", "message": ..., "result": null}`, marked with `X-PolicyEngine-Route-Error: true` (`ROUTE_ERROR_HEADER`) so a same-origin caller, such as the calculator's pages, can tell them from the Public API's own errors, such as its 502 for a failed calculation. A cross-origin caller sees the header only if the route's CORS policy exposes it, and the website's dashboard API doesn't: - | Failure | Status | - | -------------------------------------------------------------------------------------- | ---------------------- | - | A path outside the letters, digits and `-_.~` segments a route may name | 404 | - | `POLICYENGINE_API_URL` missing outside production, or a partial credential | 503 | - | Auth0 refuses or does not answer the token request | 502 | - | The Public API cannot be reached | 502 | - | The Public API answers with a redirect (never followed: it would carry the credential) | 502 | - | No response headers within the route's timeout | 504 | - | A non-JSON error from in front of the Public API, such as the load balancer's 429 | same status, JSON body | + | Failure | Status | + | --- | --- | + | A path outside the letters, digits and `-_.~` segments a route may name | 404 | + | `POLICYENGINE_API_URL` missing outside production, or a partial credential | 503 | + | Auth0 refuses or does not answer the token request | 502 | + | The Public API cannot be reached | 502 | + | The Public API answers with a redirect (never followed: it would carry the credential) | 502 | + | No response headers within the route's timeout | 504 | + | A non-JSON error from in front of the Public API, such as the load balancer's 429 | same status, JSON body | JSON errors from the Public API itself pass through unchanged. @@ -45,7 +44,11 @@ The Auth0 token request never follows a redirect, which would re-send the client `isJsonMediaType()` is the JSON content-type check the package and its routes share: `application/json` or any `application/...+json` type. -`fetchFromServer()` also takes a `signal`. When it aborts, the request stops and `fetchFromServer()` rejects with the signal's reason. Its `PublicApiUnavailableError` says in `requestMayHaveArrived` whether API v1 may have received the request: `false` when it was never sent (an unknown path, no configuration, or no credential), `true` when fetch rejected or timed out. Fetch doesn't say whether anything was sent, so it is `true` even for a connection refused before sending. An abort while the credential is being fetched also rejects with the signal's reason. +The sections below call the Public API "API v1", its name in PolicyEngine's other repositories. + +`fetchFromServer()` also takes a `signal`. When it aborts, the request stops and `fetchFromServer()` rejects with the signal's reason at once, also while the server credential is being fetched; that token request goes on, since other requests may be waiting on it. + +Its `PublicApiUnavailableError` names why API v1 cannot be called in `reason`: `unknown_route`, `not_configured` or `credential_unavailable`, found before anything is sent; or `unreachable`, `timed_out` or `answer_lost` (API v1 answered, but the answer was lost while it arrived). `requestMayHaveArrived` is `false` for the first three and `true` for the others: API v1 may have received the request. Fetch doesn't say whether anything was sent, so it is `true` even for a connection refused before sending. ## Household calculations @@ -73,23 +76,24 @@ calculated.household; // what /calculate answered as `result` What it does, through `fetchFromServer()`: 1. Submits `{country_id, household, policy?, axes?, add_missing_variables?, spm?}` to `POST /v2/household-calculations`. `household` is the situation without its `axes`, which go in the request's own `axes` field; the caller's object is not changed. API v1 keeps the calculation as a household job only: no stored household, policy or user association. -2. Reads `GET /v2/household-calculations/{calculation_id}` every 2 seconds until the calculation succeeds or fails. +2. Reads `GET /v2/household-calculations/{calculation_id}` every 2 seconds until the calculation succeeds or fails. When the submission's answer already says `succeeded` or `failed`, which the simulation service answers for a job that finished before it could confirm the call, it reads the calculation at once. 3. Gives up 10 minutes after the call starts, or after `timeLimitMilliseconds`: a number, 0 or more, or `Infinity`; anything else rejects with `RangeError` before submitting. No wait runs past that deadline; the last read happens at it, and an accepted calculation is read at least once, even with a limit of 0. -The submission may take until the deadline, and at least 30 seconds: it may wait for an API v1 instance to start, which takes minutes after the service has scaled to zero, and timing it out sooner would leave a job that may exist. Each read takes at most 30 seconds. So a request in flight at the deadline may take up to 30 seconds more; with the 10-minute default, a call ends within about 10.5 minutes. +The submission may take until the deadline, and at least 30 seconds: it may wait for an API v1 instance to start, which takes minutes after the service has scaled to zero, and timing it out sooner would leave a job that may exist. Each read takes at most 30 seconds. A request's timeout starts once the server credential is in hand, which takes up to 10 seconds when a new token is needed. So a request in flight at the deadline may take up to about 40 seconds more; with the 10-minute default, a call ends within about 11 minutes, inside the website route's 800-second limit. It resolves with the calculated household, `warnings`, `spmConfig`, `spmProvenance`, the calculation ID and the versions it ran with. It throws: - `HouseholdCalculationFailedError` when the calculation fails, with the household function's `code` (such as `invalid_inputs`), `inputErrors` and `spmError`. A null `code` means the function raised or was cancelled, and submitting again may succeed. - `HouseholdCalculationTimeoutError` when the time limit passes, with the calculation ID and the last status read (the submission's status if no read succeeded). +- `RangeError` for a time limit that is not a number, 0 or more, or `Infinity`. A limit that isn't a whole number is fine: timeouts are rounded up to whole milliseconds. - `HouseholdCalculationRefusedError` when API v1 refuses a request or its answer cannot be read, with the HTTP status, API v1's message and `code` (such as `missing_parameters`), the parsed body, `Retry-After` and the observability and request IDs. - `PublicApiUnavailableError` when API v1 cannot be called. - The signal's reason when the signal aborts. Brief outages are retried until 90 seconds pass without a good answer: -- **Reads** are retried on 429, 502, 503 and 504, and when API v1 cannot be reached, does not answer in time, or the credential cannot be obtained. A 429 or 503 with `Retry-After` waits that many seconds, or 2 seconds if that is longer; anything else waits 2 seconds. -- **The submission** is retried only when no job can exist: on API v1's own 503 (with its `{status: "error", message}` body), which it answers when no job of the submission will run, and when the credential cannot be obtained, so the request was never sent. It is not retried on any other 503, such as Cloud Run's plain-text one when its connection to an instance fails; on a 502; or when fetch rejects or times out after the request was handed to it: in each case API v1 may have created the job, and submitting again would create a second one. Nor is it retried when the wait before it would reach the deadline, since the calculation could then not be read. +- **Reads** are retried on 429, 502, 503 and 504, and on a `PublicApiUnavailableError` whose `reason` is `credential_unavailable`, `unreachable`, `timed_out` or `answer_lost`. A 429 or 503 with `Retry-After` waits that many seconds, or 2 seconds if that is longer; anything else waits 2 seconds. +- **The submission** is retried only when no job can exist: on API v1's own 503 (with its `{status: "error", message}` body), which it answers when no job of the submission will run, and when the credential cannot be obtained (`reason: "credential_unavailable"`), so the request was never sent. It is not retried on any other 503, such as Cloud Run's plain-text one when its connection to an instance fails; on a 502; or when fetch rejects or times out after the request was handed to it: in each case API v1 may have created the job, and submitting again would create a second one. Nor is it retried when the wait before it would reach the deadline, since the calculation could then not be read. - Nothing else is retried, including 400, 401, 403, 404, 409, 413, 422 and 500. How `calculated` differs from `/calculate`'s answer: there is no `{status, message, result}` envelope; `warnings` and `spm_provenance` are fields of the result, as `warnings` and `spmProvenance`; and inputs the model does not recognise come back as a failed calculation (`code: "invalid_inputs"`, `inputErrors`), thrown as `HouseholdCalculationFailedError`, not as a 400 with `errors`. diff --git a/packages/public-api-forwarding/src/forward.ts b/packages/public-api-forwarding/src/forward.ts index c0ae7b395d..ffda33544e 100644 --- a/packages/public-api-forwarding/src/forward.ts +++ b/packages/public-api-forwarding/src/forward.ts @@ -70,24 +70,83 @@ export interface ServerRequestOptions { * Or, from fetchFromServer, API v1 could not be reached or did not answer in * time. The message is safe to show; details go to the server's log. */ +/** + * Why API v1 cannot be called: + * - "unknown_route": the path is not one a route may name; + * - "not_configured": the deployment has no API v1 URL, or a partial + * credential; + * - "credential_unavailable": the server credential could not be obtained; + * - "unreachable": fetch rejected, so API v1 could not be reached; + * - "timed_out": API v1 did not answer in time; + * - "answer_lost": API v1 answered, but the answer was lost while it arrived. + * The first three are found before anything is sent. + */ +export type PublicApiUnavailableReason = + | "unknown_route" + | "not_configured" + | "credential_unavailable" + | "unreachable" + | "timed_out" + | "answer_lost"; + +const REASONS_AFTER_SENDING: ReadonlySet = new Set([ + "unreachable", + "timed_out", + "answer_lost", +]); + export class PublicApiUnavailableError extends Error { override name = "PublicApiUnavailableError"; + /** + * False when the request was never sent (an unknown route, no + * configuration, or no credential), so sending it again cannot repeat + * it. True otherwise: API v1 may have received the request and acted on + * it. Fetch doesn't say whether anything was sent, so this is true even + * for a connection refused before sending. + */ + readonly requestMayHaveArrived: boolean; constructor( message: string, /** The status a route would answer with for this failure. */ readonly statusCode: number, - /** - * False when the request was never sent (an unknown path, no - * configuration, or no credential), so sending it again cannot repeat - * it. True when fetch rejected or timed out: API v1 may have received - * the request and acted on it. Fetch doesn't say whether anything was - * sent, so this is true even for a connection refused before sending. - */ - readonly requestMayHaveArrived: boolean = false, + readonly reason: PublicApiUnavailableReason, ) { super(message); + this.requestMayHaveArrived = REASONS_AFTER_SENDING.has(reason); + } +} + +/** + * Resolves or rejects as `promise` does, but rejects with the signal's + * reason as soon as the signal aborts. `promise` keeps running: a token + * request it waits on may be serving other requests too. + */ +function untilAborted( + promise: Promise, + signal: AbortSignal | undefined, +): Promise { + if (signal === undefined) { + return promise; } + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(signal.reason); + return; + } + const onAbort = () => reject(signal.reason); + signal.addEventListener("abort", onAbort, { once: true }); + promise.then( + (value) => { + signal.removeEventListener("abort", onAbort); + resolve(value); + }, + (error: unknown) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + }); } export interface PublicApiForwarder { @@ -321,7 +380,11 @@ export function createPublicApiForwarder( if (!isForwardablePath(publicApiRequest.path)) { return { ok: false, - error: new PublicApiUnavailableError("Unknown route.", 404), + error: new PublicApiUnavailableError( + "Unknown route.", + 404, + "unknown_route", + ), }; } @@ -335,6 +398,7 @@ export function createPublicApiForwarder( error: new PublicApiUnavailableError( "The Public API is not configured on this deployment.", 503, + "not_configured", ), }; } @@ -354,6 +418,7 @@ export function createPublicApiForwarder( error: new PublicApiUnavailableError( "Could not obtain a credential for the Public API.", 502, + "credential_unavailable", ), }; } @@ -482,10 +547,13 @@ export function createPublicApiForwarder( ): Promise { const callerSignal = serverOptions.signal; callerSignal?.throwIfAborted(); - const connection = await connect(publicApiRequest); - // Getting the token can take a while; the caller may have left meanwhile, - // and then the abort is the answer, not a failed token request. - callerSignal?.throwIfAborted(); + // Getting the token can take a while; when the caller leaves meanwhile, + // the abort is the answer at once, not whatever the token request + // ends with. + const connection = await untilAborted( + connect(publicApiRequest), + callerSignal, + ); if (!connection.ok) { throw connection.error; } @@ -540,12 +608,12 @@ export function createPublicApiForwarder( ? new PublicApiUnavailableError( "The Public API did not answer in time.", 504, - true, + "timed_out", ) : new PublicApiUnavailableError( "The Public API could not be reached.", 502, - true, + "unreachable", ); } warnIfCredentialRefused(publicApiRequest, serverToken, upstream); diff --git a/packages/public-api-forwarding/src/householdCalculation.ts b/packages/public-api-forwarding/src/householdCalculation.ts index 03e670cbdd..e182bde2fe 100644 --- a/packages/public-api-forwarding/src/householdCalculation.ts +++ b/packages/public-api-forwarding/src/householdCalculation.ts @@ -13,6 +13,7 @@ import { PublicApiUnavailableError, type PublicApiForwarder, type PublicApiRequest, + type PublicApiUnavailableReason, } from "./forward"; /** How long the helper waits between reads of a calculation. */ @@ -163,9 +164,11 @@ export class HouseholdCalculationTimeoutError extends Error { readonly calculationId: string, /** * The status the last successful read gave, or the submission's when no - * read succeeded. + * read succeeded. It is "succeeded" or "failed" only when the + * submission's answer said so and no read could get the outcome before + * the deadline. */ - readonly lastStatus: HouseholdCalculationUnfinishedStatus, + readonly lastStatus: HouseholdCalculationStatus, ) { super(message); } @@ -222,7 +225,36 @@ interface ApiV1Answer { interface SubmittedCalculation { readonly calculationId: string; - readonly status: HouseholdCalculationUnfinishedStatus; + /** + * Usually "pending". The simulation service answers with the job's + * current status, so a fast job can already have finished. + */ + readonly status: HouseholdCalculationStatus; +} + +const CALCULATION_STATUSES: ReadonlySet = new Set([ + "pending", + "running", + "succeeded", + "failed", +]); + +function isCalculationStatus( + value: unknown, +): value is HouseholdCalculationStatus { + return CALCULATION_STATUSES.has(value); +} + +function isString(value: unknown): value is string { + return typeof value === "string"; +} + +/** A list of strings; an absent list is empty; anything else is undefined. */ +function stringsOrUndefined(value: unknown): string[] | undefined { + if (value === undefined || value === null) { + return []; + } + return Array.isArray(value) && value.every(isString) ? value : undefined; } function isJsonObject(value: unknown): value is JsonObject { @@ -347,7 +379,7 @@ function readSubmitted(answer: ApiV1Answer): SubmittedCalculation { if ( typeof calculationId !== "string" || !CALCULATION_ID_PATTERN.test(calculationId) || - (status !== "pending" && status !== "running") + !isCalculationStatus(status) ) { throw unreadable( answer, @@ -391,12 +423,11 @@ function readCalculation( if (!isJsonObject(result) || !isJsonObject(result.household)) { throw cannotRead(); } - const warnings = result.warnings ?? []; + const warnings = stringsOrUndefined(result.warnings); const spmConfig = objectOrNull(result.spm_config); const spmProvenance = objectOrNull(result.spm_provenance); if ( - !Array.isArray(warnings) || - !warnings.every((warning) => typeof warning === "string") || + warnings === undefined || spmConfig === undefined || spmProvenance === undefined || typeof item.country_package_version !== "string" || @@ -456,20 +487,28 @@ function readCalculation( function isUnsentCredentialFailure(error: unknown): boolean { return ( error instanceof PublicApiUnavailableError && - !error.requestMayHaveArrived && - error.statusCode === 502 + error.reason === "credential_unavailable" ); } +/** Failures of fetchFromServer that a brief outage explains. */ +const BRIEF_OUTAGE_REASONS: ReadonlySet = new Set([ + "credential_unavailable", + "unreachable", + "timed_out", + "answer_lost", +]); + /** * A failure of fetchFromServer that a brief outage explains: the credential - * could not be obtained, or API v1 could not be reached or did not answer in - * time. A deployment with no API v1 configured is not one. + * could not be obtained, or API v1 could not be reached, did not answer in + * time, or its answer was lost. An unknown route or a deployment with no + * API v1 configured is not one. */ function isBriefOutage(error: unknown): boolean { return ( error instanceof PublicApiUnavailableError && - (error.requestMayHaveArrived || error.statusCode === 502) + BRIEF_OUTAGE_REASONS.has(error.reason) ); } @@ -500,7 +539,7 @@ export function createHouseholdCalculator( throw new PublicApiUnavailableError( "API v1's answer was lost before it could be read.", 502, - true, + "answer_lost", ); } let body: unknown = null; @@ -563,9 +602,15 @@ export function createHouseholdCalculator( // take minutes, so it may take until the deadline (at least the // forwarder's usual 30 seconds). Timing it out sooner would leave a // job that may exist, which the helper must not submit again. - const timeoutMilliseconds = Math.min( - Math.max(DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, deadline - now()), - LONGEST_TIMER_MILLISECONDS, + // AbortSignal.timeout takes whole milliseconds only. + const timeoutMilliseconds = Math.ceil( + Math.min( + Math.max( + DEFAULT_SERVER_REQUEST_TIMEOUT_MILLISECONDS, + deadline - now(), + ), + LONGEST_TIMER_MILLISECONDS, + ), ); let answer: ApiV1Answer; try { @@ -615,9 +660,14 @@ export function createHouseholdCalculator( ): Promise { const { calculationId } = submitted; const path = `${SUBMISSION_PATH}/${calculationId}`; - let lastStatus: HouseholdCalculationUnfinishedStatus = submitted.status; + let lastStatus: HouseholdCalculationStatus = submitted.status; let lastGoodAnswerAt = now(); - let nextWaitMilliseconds = HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS; + // A calculation the submission's answer says has finished is read at + // once, for its result or error. + let nextWaitMilliseconds = + submitted.status === "succeeded" || submitted.status === "failed" + ? 0 + : HOUSEHOLD_CALCULATION_POLL_INTERVAL_MILLISECONDS; const outageLimitReached = () => now() - lastGoodAnswerAt >= HOUSEHOLD_CALCULATION_OUTAGE_LIMIT_MILLISECONDS; diff --git a/packages/public-api-forwarding/src/index.ts b/packages/public-api-forwarding/src/index.ts index 3a0f6058a2..adc635c464 100644 --- a/packages/public-api-forwarding/src/index.ts +++ b/packages/public-api-forwarding/src/index.ts @@ -29,6 +29,7 @@ export { type PublicApiForwarderOptions, type PublicApiMethod, type PublicApiRequest, + type PublicApiUnavailableReason, type ServerRequestOptions, } from "./forward"; export { From 14621ee50d95c32fdfbf0cf27620a7ff8ea62357 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:21:41 +0400 Subject: [PATCH 09/10] Test the read loop's deadline and outage checks and both waits 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 --- .../tests/forward.test.ts | 5 +- .../tests/householdCalculation.test.ts | 135 +++++++++++++++++- 2 files changed, 133 insertions(+), 7 deletions(-) diff --git a/packages/public-api-forwarding/tests/forward.test.ts b/packages/public-api-forwarding/tests/forward.test.ts index 397681aabb..648d6d4567 100644 --- a/packages/public-api-forwarding/tests/forward.test.ts +++ b/packages/public-api-forwarding/tests/forward.test.ts @@ -803,11 +803,12 @@ describe("fetchFromServer", () => { const controller = new AbortController(); const callerLeft = new Error("The caller went away."); - // When the caller aborts while the request is in flight + // When the caller aborts while the request is in flight, long before + // the request's own timeout would end it const pendingRequest = forwarder .fetchFromServer(DEPLOYMENT_REPORT_REQUEST, { signal: controller.signal, - timeoutMilliseconds: 1_000, + timeoutMilliseconds: 60_000, }) .catch((error: unknown) => error); await started; diff --git a/packages/public-api-forwarding/tests/householdCalculation.test.ts b/packages/public-api-forwarding/tests/householdCalculation.test.ts index 85f39d12f1..ea6dcb83db 100644 --- a/packages/public-api-forwarding/tests/householdCalculation.test.ts +++ b/packages/public-api-forwarding/tests/householdCalculation.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test, vi } from "vitest"; +import { afterEach, describe, expect, test, vi } from "vitest"; import { PublicApiUnavailableError, @@ -718,10 +718,15 @@ describe("calculateHousehold", () => { calculationAnswer("running"), ), { - wait: async (_milliseconds, signal) => { - controller.abort(callerLeft); - signal?.throwIfAborted(); - }, + // A wait that ends only through the signal it is given: without + // it, the call would never finish. + wait: (_milliseconds, signal) => + new Promise((_resolve, reject) => { + signal?.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + controller.abort(callerLeft); + }), }, ); @@ -1217,4 +1222,124 @@ describe("calculateHousehold", () => { // Then expect(api.submissions()[0].options?.timeoutMilliseconds).toBe(2 ** 31 - 1); }); + test.each([ + ["answers 503", () => errorAnswer(503, "Storage is unavailable")], + [ + "cannot reach API v1", + () => + new PublicApiUnavailableError( + "The Public API could not be reached.", + 502, + "unreachable", + ), + ], + ])( + "given a read at the deadline %s then it throws HouseholdCalculationTimeoutError without reading again", + async (_description, failedRead) => { + // Given + const api = fakeApiV1(inOrder([submittedAnswer(), failedRead()])); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST, { + timeLimitMilliseconds: 2_000, + }), + ); + + // Then + expect(failure).toBeInstanceOf(HouseholdCalculationTimeoutError); + expect(failure).toMatchObject({ lastStatus: "pending" }); + expect(api.reads()).toHaveLength(1); + }, + ); + + test("given reads cannot reach API v1 for 90 seconds then it throws the last failure", async () => { + // Given + const unreachable = new PublicApiUnavailableError( + "The Public API could not be reached.", + 502, + "unreachable", + ); + const api = fakeApiV1( + submissionThenEveryRead(submittedAnswer, () => unreachable), + ); + + // When + const failure = await failureOf( + api.calculator.calculateHousehold(US_REFORM_REQUEST), + ); + + // Then + expect(failure).toBe(unreachable); + expect(api.reads().at(-1)?.atMilliseconds).toBe(90_000); + expect(api.reads()).toHaveLength(45); + }); +}); + +describe("calculateHousehold with its own timer", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + function calculatorWithTimer(answers: ScriptedAnswer[]) { + const answerFor = inOrder(answers); + const fetchFromServer = vi.fn(async (request: PublicApiRequest) => { + const answer = answerFor(request); + if (answer instanceof Error) { + throw answer; + } + return answer; + }); + const calculator = createHouseholdCalculator({ + forwarder: { fetchFromServer }, + now: () => Date.now(), + }); + return { calculator, fetchFromServer }; + } + + test("given no wait of its own then it reads after 2 seconds", async () => { + // Given + vi.useFakeTimers(); + const { calculator, fetchFromServer } = calculatorWithTimer([ + submittedAnswer(), + succeededAnswer(), + ]); + + // When + const calculation = calculator.calculateHousehold(US_REFORM_REQUEST); + await vi.advanceTimersByTimeAsync(1_999); + const requestsBeforeTheInterval = fetchFromServer.mock.calls.length; + await vi.advanceTimersByTimeAsync(1); + const calculated = await calculation; + + // Then + expect(requestsBeforeTheInterval).toBe(1); + expect(fetchFromServer).toHaveBeenCalledTimes(2); + expect(calculated.calculationId).toBe(CALCULATION_ID); + }); + + test("given the signal aborts during its own wait then it rejects at once and leaves no timer", async () => { + // Given + vi.useFakeTimers(); + const controller = new AbortController(); + const callerLeft = new Error("The caller went away."); + const { calculator, fetchFromServer } = calculatorWithTimer([ + submittedAnswer(), + ]); + + // When + const calculation = failureOf( + calculator.calculateHousehold(US_REFORM_REQUEST, { + signal: controller.signal, + }), + ); + await vi.advanceTimersByTimeAsync(500); + controller.abort(callerLeft); + const failure = await calculation; + + // Then + expect(failure).toBe(callerLeft); + expect(vi.getTimerCount()).toBe(0); + expect(fetchFromServer).toHaveBeenCalledTimes(1); + }); }); From 87eaa144b5b8cbce9399140cd4beecfcf666ca7a Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:22:15 +0400 Subject: [PATCH 10/10] Correct the household calculation's run-time notes 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 --- packages/public-api-forwarding/README.md | 2 +- packages/public-api-forwarding/src/forward.ts | 12 ++++++------ .../src/householdCalculation.ts | 14 +++++++++----- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/packages/public-api-forwarding/README.md b/packages/public-api-forwarding/README.md index e884166825..eff17ca716 100644 --- a/packages/public-api-forwarding/README.md +++ b/packages/public-api-forwarding/README.md @@ -79,7 +79,7 @@ What it does, through `fetchFromServer()`: 2. Reads `GET /v2/household-calculations/{calculation_id}` every 2 seconds until the calculation succeeds or fails. When the submission's answer already says `succeeded` or `failed`, which the simulation service answers for a job that finished before it could confirm the call, it reads the calculation at once. 3. Gives up 10 minutes after the call starts, or after `timeLimitMilliseconds`: a number, 0 or more, or `Infinity`; anything else rejects with `RangeError` before submitting. No wait runs past that deadline; the last read happens at it, and an accepted calculation is read at least once, even with a limit of 0. -The submission may take until the deadline, and at least 30 seconds: it may wait for an API v1 instance to start, which takes minutes after the service has scaled to zero, and timing it out sooner would leave a job that may exist. Each read takes at most 30 seconds. A request's timeout starts once the server credential is in hand, which takes up to 10 seconds when a new token is needed. So a request in flight at the deadline may take up to about 40 seconds more; with the 10-minute default, a call ends within about 11 minutes, inside the website route's 800-second limit. +The submission's timeout is the time left before the deadline, and at least 30 seconds: it may wait for an API v1 instance to start, which takes minutes after the service has scaled to zero, and timing it out sooner would leave a job that may exist. In practice it can't take longer than 300 seconds, after which Node's `fetch` stops waiting for the answer's headers and API v1's Cloud Run service ends the request; either way the submission is not sent again. Each read takes at most 30 seconds. A request's timeout starts once the server credential is in hand, which takes up to 10 seconds when a new token is needed. So a call can end up to about 80 seconds after the deadline (a submission started just before it, then the read it is owed); with the 10-minute default, a call ends within about 11.5 minutes, inside the website route's 800-second limit. It resolves with the calculated household, `warnings`, `spmConfig`, `spmProvenance`, the calculation ID and the versions it ran with. It throws: diff --git a/packages/public-api-forwarding/src/forward.ts b/packages/public-api-forwarding/src/forward.ts index ffda33544e..b448ca1218 100644 --- a/packages/public-api-forwarding/src/forward.ts +++ b/packages/public-api-forwarding/src/forward.ts @@ -64,12 +64,6 @@ export interface ServerRequestOptions { readonly signal?: AbortSignal; } -/** - * The Public API cannot be called: it is not configured, the server - * credential cannot be obtained, or the path is not one a route may name. - * Or, from fetchFromServer, API v1 could not be reached or did not answer in - * time. The message is safe to show; details go to the server's log. - */ /** * Why API v1 cannot be called: * - "unknown_route": the path is not one a route may name; @@ -95,6 +89,12 @@ const REASONS_AFTER_SENDING: ReadonlySet = new Set([ "answer_lost", ]); +/** + * The Public API cannot be called: it is not configured, the server + * credential cannot be obtained, or the path is not one a route may name. + * Or, from fetchFromServer, API v1 could not be reached or did not answer in + * time. The message is safe to show; details go to the server's log. + */ export class PublicApiUnavailableError extends Error { override name = "PublicApiUnavailableError"; /** diff --git a/packages/public-api-forwarding/src/householdCalculation.ts b/packages/public-api-forwarding/src/householdCalculation.ts index e182bde2fe..4163fa20f1 100644 --- a/packages/public-api-forwarding/src/householdCalculation.ts +++ b/packages/public-api-forwarding/src/householdCalculation.ts @@ -82,8 +82,10 @@ export interface HouseholdCalculationOptions { /** * How long after the call starts to give up, 10 minutes by default. The * last read happens at the deadline, and an accepted calculation is read - * at least once. A request in flight at the deadline may take up to 30 - * seconds more. + * at least once. So a call can end up to about 80 seconds after the + * deadline: a submission started just before it takes at least 30 + * seconds, the read after it up to 30, and each may first wait up to 10 + * seconds for a new server token. */ readonly timeLimitMilliseconds?: number; } @@ -599,9 +601,11 @@ export function createHouseholdCalculator( for (;;) { signal?.throwIfAborted(); // A submission may wait for an API v1 instance to start, which can - // take minutes, so it may take until the deadline (at least the - // forwarder's usual 30 seconds). Timing it out sooner would leave a - // job that may exist, which the helper must not submit again. + // take minutes, so its timeout is the time left before the deadline + // (at least the forwarder's usual 30 seconds). Timing it out sooner + // would leave a job that may exist, which the helper must not submit + // again. Node's fetch and API v1's Cloud Run service each end a + // request after 300 seconds anyway. // AbortSignal.timeout takes whole milliseconds only. const timeoutMilliseconds = Math.ceil( Math.min(