Skip to content

Return TIMED_OUT when a 429 or 503 body is cut off at the wait deadline - #106

Open
Aaron-hub-dev-maker wants to merge 5 commits into
prooflinedev:mainfrom
Aaron-Stephen:fix/wait-retryable-refusal-deadline
Open

Aaron-hub-dev-maker wants to merge 5 commits into
prooflinedev:mainfrom
Aaron-Stephen:fix/wait-retryable-refusal-deadline

Conversation

@Aaron-hub-dev-maker

Copy link
Copy Markdown

waitForReview throws ProoflineError(503, "urn:proofline:sdk:invalid-response") instead of returning TIMED_OUT when a 429 or 503 body is still streaming at the wait deadline. This PR ports the wait half of the Python SDK's rule for that case.

Problem

An overloaded gateway may send 503 (or 429) headers, then stall before finishing the body. If the wait deadline passes while waitForReview is reading that body, the transport throws

ProoflineError(503, "urn:proofline:sdk:invalid-response", "the response is not valid UTF-8 JSON")

and waitForReview rethrows it, because its status is not 0. The wait fails instead of reporting TIMED_OUT. A CI job that gates on the outcome therefore sees an error rather than a timeout it can handle.

The Python SDK already times this case out, both ways the deadline can strike. An expired read of a 429 or 503 body raises its timeout error, and prooflinedev/sdk-python#12 extended that to a chunk checked after the deadline: "Retryable statuses time out as an expired read does; other problems keep their status." The TypeScript transport does neither during a wait. Given the same stalled 503, Python returns TIMED_OUT and TypeScript throws (output below).

Change

In decoded() (src/transport.ts), a 429 or 503 body read cut off by the wait deadline now raises the urn:proofline:sdk:timeout error that a successful body already raises there. waitForReview already maps that error to TIMED_OUT. A new RETRYABLE_STATUSES constant is shared with the retry loop, so the two lists cannot drift apart.

When it applies: only to a read that starts while the wait deadline is within the request timeout (waitTimeout). With the defaults, that is a read starting in the last 30 s of a wait, or any read if timeoutMs ≤ requestTimeoutMs. A read that starts earlier hits requestTimeoutMs first and keeps its current error, as a successful body does.

What does not change:

  • Other refusals, such as 403, keep their status, as the wait timeout includes an in-flight request and returns the retained review URL requires.
  • Plain reads outside a wait keep invalid-response with the refusal's status, which refusal retries preserve response bounds and the caller deadline and invalid UTF-8 never hides successful-body or incomplete-body failures pin. Python times these out too. I kept the tested TypeScript behaviour rather than change it here.
  • waitForReview is the only caller that passes a wait deadline to the transport, so mutations, exports and MCP calls are unaffected.

Only src/transport.ts (+9/−2) and tests/http.test.mjs (+63) change.

Verification

Unit test. a retryable refusal times the wait out only when cut off at the wait deadline covers 429, 503 and 403. Each status runs three ways:

  • elapsed: the observed clock passes the deadline, then the connection ends while the abort signal is still 20 s away.
  • native-abort: the observed clock is frozen and only the abort signal fires.
  • interrupted: the connection ends while the deadline is still 20 s away. Every status must keep its invalid-response error.

To check that each case tests its own branch, I disabled each check in turn (false && …, so the build still type-checks), then bypassed both deadline checks for 429/503:

Code under test 429/503 elapsed 429/503 native-abort 429/503 interrupted 403 (all three)
this PR pass pass pass (keeps its error) pass (keeps 403)
clock check disabled fail pass pass pass
abort-signal check disabled pass fail pass pass
both deadline checks bypassed for 429/503 pass pass fail pass
main (no fix) fail fail pass pass

The test passed 15 of 15 repeated runs on the final commit.

Project checks. CI ran the Checks workflow on the final commit in my fork, on ubuntu-24.04. Generate with no diff, lint, typecheck, claims check, build, every test, and pack all passed: https://github.com/Aaron-Stephen/sdk-typescript/actions/runs/46588004772. On Windows 11 with Node 22.16, everything passes except a new public operation generates a callable typed client method. That test fails there with spawnSync pnpm ENOENT, on main too (see #53).

Through a fault proxy in front of the real API. A small loopback proxy forwards to https://proofline.sh. The real service won't stall on demand, so when armed, the proxy answers the next review read itself with 503 or 429, Retry-After: 1 and half a problem body, then stalls. The plain waits read a real completed review in my organization (60 s timeout). The stall runs use a 3 s timeout and never reach the server. Review URLs are trimmed from the output.

TypeScript main (633ea92)
  plain wait  outcome COMPLETED after 1817 ms | review status COMPLETED
  stall-503   threw ProoflineError status=503 type=urn:proofline:sdk:invalid-response detail="the response is not valid UTF-8 JSON" after 3014 ms
  stall-429   threw ProoflineError status=429 type=urn:proofline:sdk:invalid-response detail="the response is not valid UTF-8 JSON" after 3021 ms

TypeScript, this branch (43e6f9c)
  plain wait  outcome COMPLETED after 798 ms | review status COMPLETED
  stall-503   outcome TIMED_OUT after 3018 ms | review status none
  stall-429   outcome TIMED_OUT after 3024 ms | review status none

Python SDK (proofline-sdk 10.3.0, sdk-python 8fc13b4)
  plain wait  outcome COMPLETED after 812 ms | review status COMPLETED
  stall-503   outcome TIMED_OUT after 3015 ms | review status none
  stall-429   outcome TIMED_OUT after 3003 ms | review status none
Reproduce with the fault proxy (fault-proxy.mjs, wait.mjs)
pnpm install --frozen-lockfile && pnpm build   # on this branch, and on main in a second checkout
node fault-proxy.mjs 8787                       # terminal 1: forwards to https://proofline.sh
# terminal 2: a completed review and a token with "Read reviews"
export PROOFLINE_TOKEN=... PROOFLINE_ORGANIZATION_ID=... PROOFLINE_REVIEW_ID=...
node wait.mjs ./dist http://127.0.0.1:8787            # plain wait
node wait.mjs ./dist http://127.0.0.1:8787 stall-503  # the first review read stalls after a 503
node wait.mjs ./dist http://127.0.0.1:8787 stall-429

fault-proxy.mjs

// A loopback proxy in front of the real Proofline API that can inject one fault.
//
//   node fault-proxy.mjs [port]
//
// Every request is forwarded to https://proofline.sh unchanged (the SDK's token
// passes through; nothing is logged but method, path and status). Send
// `POST /__fault/stall-503` or `/__fault/stall-429` to make the NEXT review read
// (GET /api/v1/organizations/{org}/reviews/{review}) answer with the status, a
// Retry-After header and the first bytes of a problem body, then stall without
// ever finishing it, as an overloaded gateway does. `POST /__fault/off` clears it.
import { createServer } from "node:http";

const upstream = new URL(process.env.PROOFLINE_UPSTREAM ?? "https://proofline.sh");
const port = Number(process.argv[2] ?? 8787);
const reviewRead = /^\/api\/v1\/organizations\/[^/]+\/reviews\/[^/?]+$/;
let fault = null;

const server = createServer(async (request, response) => {
  const path = request.url ?? "/";
  if (path.startsWith("/__fault/")) {
    const next = path.slice("/__fault/".length);
    fault = next === "off" ? null : next;
    response.writeHead(204).end();
    console.log(`[proxy] fault armed: ${fault ?? "none"}`);
    return;
  }
  const pathname = new URL(path, upstream).pathname;
  if (fault && request.method === "GET" && reviewRead.test(pathname)) {
    const status = fault === "stall-429" ? 429 : 503;
    fault = null;
    console.log(`[proxy] ${request.method} ${pathname} -> injected ${status}, body stalls`);
    response.writeHead(status, {
      "Content-Type": "application/problem+json",
      "Retry-After": "1",
    });
    response.write('{"type":"about:blank","title":"Service Unavailable","detail":"');
    return; // never finish the body
  }
  const chunks = [];
  for await (const chunk of request) chunks.push(chunk);
  const headers = { ...request.headers };
  delete headers.host;
  delete headers.connection;
  delete headers["content-length"];
  try {
    const answer = await fetch(new URL(path, upstream), {
      method: request.method,
      headers,
      body: chunks.length ? Buffer.concat(chunks) : undefined,
      redirect: "manual",
    });
    const body = Buffer.from(await answer.arrayBuffer());
    const outHeaders = Object.fromEntries(answer.headers);
    delete outHeaders["content-encoding"];
    delete outHeaders["transfer-encoding"];
    outHeaders["content-length"] = String(body.length);
    response.writeHead(answer.status, outHeaders).end(body);
    console.log(`[proxy] ${request.method} ${pathname} -> ${answer.status}`);
  } catch (error) {
    console.log(`[proxy] ${request.method} ${pathname} -> upstream error ${error.code ?? error.name}`);
    response.destroy();
  }
});

server.listen(port, "127.0.0.1", () =>
  console.log(`[proxy] http://127.0.0.1:${port} -> ${upstream.origin}`),
);

wait.mjs

// Wait for a real Proofline review through the loopback fault proxy.
//
//   node wait.mjs <path-to-sdk-dist> <proxy-url> [fault]
//
// Reads PROOFLINE_TOKEN, PROOFLINE_ORGANIZATION_ID and PROOFLINE_REVIEW_ID from
// the environment. With a fault (stall-503 or stall-429) it arms the proxy so
// the first review read stalls, then waits with a 3 second timeout.
import { pathToFileURL } from "node:url";
import { join } from "node:path";

const [dist, proxy, fault] = process.argv.slice(2);
const { ProoflineClient, ProoflineError } = await import(
  pathToFileURL(join(dist, "index.js")).href
);
const orgId = process.env.PROOFLINE_ORGANIZATION_ID;
const reviewId = process.env.PROOFLINE_REVIEW_ID;
if (!process.env.PROOFLINE_TOKEN || !orgId || !reviewId)
  throw new Error("set PROOFLINE_TOKEN, PROOFLINE_ORGANIZATION_ID and PROOFLINE_REVIEW_ID");

await fetch(new URL(`/__fault/${fault ?? "off"}`, proxy), { method: "POST" });
const client = new ProoflineClient({ baseUrl: proxy }); // token from PROOFLINE_TOKEN
const started = performance.now();
try {
  const outcome = await client.waitForReview(orgId, reviewId, {
    timeoutMs: fault ? 3_000 : 60_000,
  });
  console.log(
    `outcome ${outcome.status} after ${Math.round(performance.now() - started)} ms` +
      ` | review status ${outcome.review?.status ?? "none"} | ${outcome.reviewUrl}`,
  );
} catch (error) {
  if (!(error instanceof ProoflineError)) throw error;
  console.log(
    `threw ProoflineError status=${error.status} type=${error.type}` +
      ` detail="${error.detail}" after ${Math.round(performance.now() - started)} ms`,
  );
}

Proofline review

I installed Proofline on my organization and reviewed this change there: Aaron-Stephen#1.

  • Run 1 raised one warning: the elapsed case never reached the clock check. I confirmed it before changing anything: with that check removed, all six subtests still passed. I rewrote the case as recommended, and the table above shows each case now fails without its own check.
  • Runs 2, 3, 4 and 5, the last one on the final commit, found nothing.

Overlap

#83, #84, #92 and #100 add lines in the same catch block of decoded() without changing this condition, so a rebase would be mechanical. #88 handles a different deadline case: a successful body that finishes after the deadline.

I worked with Claude Code (Claude Opus 5.5) on this change. The commits carry its co-author trailer, and the session prompts are in the hidden section below, as AGENTS.md asks.

🤖 Generated with Claude Code

Aaron-hub-dev-maker and others added 5 commits November 30, 2026 14:18
waitForReview returns TIMED_OUT when a 429 or 503 arrives with a complete
body and its Retry-After cannot start before the deadline. When the same
refusal's body is still streaming as the deadline passes, the transport
reported it as HTTP 429/503 "the response is not valid UTF-8 JSON", and
waitForReview rethrew it, so a slow overloaded gateway turned a timed-out
wait into an error with a misleading diagnosis.

At the wait deadline a 429 or 503 body read now times out as a successful
body does. Other refusals, such as 403, keep their status. Plain reads
outside a wait are unchanged. This matches the Python SDK's check_stream
rule ("Retryable statuses time out as an expired read does").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In the "elapsed" case the stalled body was cut off by the request's abort
signal, so decoded() returned through signal.aborted and the
performance.now() >= deadline branch was never exercised: removing it left
every case passing. The elapsed case now moves the observed clock past the
wait deadline and then ends the connection while the request's abort signal
is still 20 seconds away, so it fails without the clock check, and the
native-abort case fails without the signal check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The flag is true for every successful response, timed out or not; it
decides whether an expired body read is reported as a timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The rule does not make a cut-off refusal behave exactly like a complete one:
a complete 429/503 is still thrown when its Retry-After exceeds 60 s or the
retries are spent. Say what it does instead, rename the test accordingly, and
use one RETRYABLE_STATUSES list for both the retry loop and the deadline rule
so they cannot drift apart. The native-abort case gets a 500 ms budget so the
response headers arrive before its abort fires on a slow runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test proved that a 429 or 503 body cut off at the wait deadline times
the wait out, but not that the rule stops there: making every cut-off
retryable refusal in a wait time out, even long before the deadline, still
passed the whole suite. Add an "interrupted" case whose body ends while
the deadline is far away. Every status must keep its invalid-response
error, so a change that bypasses both deadline checks now fails it.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant