Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions packages/coding-agent/docs/step-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,14 +281,18 @@ header and no queue.
a code this client does not know, gets the generic text and no code.
`error.reason` keeps a named code. A 401 or 403 status answer is returned to the
caller as it is. A 429 or 5xx status answer, or a network error, is retried
with backoff from 1s to 8s; after 30s without a good answer the request ends
with the same 410. Any other status answer ends it too.
with backoff from 1s to 8s; after 30s without a good answer the original
bytes go out again under the same id, as on `ready` (the server runs a request
without its queue when it cannot keep one, and seats again a request whose
place expired); a queued answer starts a fresh 30s budget. Any other status
answer ends the request with the same 410.
- Once the server queued the call (it answered `429` with
`X-StepCode-Queue-State: waiting`), every way this side stops waiting releases
the place with the region's cancel endpoint (queue id header, no body; 200 on
success): a stop, the 20-minute bound, or a status endpoint that keeps failing
or answers an unexpected status. A place the server closed is not cancelled
again. A stop before any such
success): a stop, the 20-minute bound, a status endpoint that answers an
unexpected status, or a resend that fails on the way (the failure then goes to
the retry policy, which retries under a new id). A place the server closed is
not cancelled again. A stop before any such
answer sends nothing more; the server's lease ends a place the client never
saw, so a host without the queue never gets a cancel. The stopped call awaits
the cancel for at most 1s, and a queued call is a registered request teardown
Expand Down
57 changes: 36 additions & 21 deletions packages/coding-agent/src/step/model-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,15 @@ import type { ModelFetch, ModelFetchFactory, ModelFetchRequest, ModelQueueState
* `ready` sends the original bytes again under the same id. The poll interval is
* the server's `retry_after_ms` (5 s when it names none). A `closed` place (a
* poll, or a 429 with `X-StepCode-Queue-State: closed` on the first send or a
* resend) ends the call with an error naming the reason. A call waits in line at most 20 minutes in all; when it
* stops waiting on its own side (the caller's stop, that bound, or a status
* endpoint that keeps failing) it releases the place with `POST <queue>/cancel`
* (the id in `X-StepCode-Queue-ID`, no body). A stop before any queued answer
* sends nothing more: the server's lease ends a place nobody saw.
* resend) ends the call with an error naming the reason. A status endpoint that
* keeps failing does not end the call: once the failures outlast their budget
* the original bytes go out again under the same id, as on `ready` (the server
* may run the request without its queue, or seat it again). A call waits in line
* at most 20 minutes in all; when it stops waiting on its own side (the caller's
* stop, that bound, an unexpected status answer, or a resend that fails) it
* releases the place with `POST <queue>/cancel` (the id in
* `X-StepCode-Queue-ID`, no body). A stop before any queued answer sends nothing
* more: the server's lease ends a place nobody saw.
*
* POST .../chat/completions -> 429 queued (position 3)
* GET <queue> (X-StepCode-Queue-ID) -> waiting (position 1)
Expand Down Expand Up @@ -325,11 +329,11 @@ export function createStepModelQueueFetch(
controlHeaders.set(QUEUE_ID_HEADER, queueId);
// Leave the line so the place is not held until its lease expires. Sent only
// once the server has queued this call, so a host without the queue never
// sees it, and only when this side stops waiting (a stop, the wait bound, or
// a status endpoint that keeps failing); a place the server closed is gone
// already. Awaited (within CANCEL_TIMEOUT_MS) so a process exiting on the
// stop sends it; its outcome changes nothing for the call, so failures are
// dropped.
// sees it, and only when this side stops waiting (a stop, the wait bound, an
// unexpected status answer, or a resend that fails); a place the server
// closed is gone already. Awaited (within CANCEL_TIMEOUT_MS) so a process
// exiting on the stop sends it; its outcome changes nothing for the call, so
// failures are dropped.
const leave = async (): Promise<void> => {
try {
const response = await base(`${queueBase}/cancel`, {
Expand Down Expand Up @@ -403,7 +407,6 @@ export function createStepModelQueueFetch(
try {
let lastSuccess = now();
let failures = 0;
let lastFailure = "";
for (;;) {
const remaining = deadline - now();
if (remaining <= 0) return await giveUp("max_wait_exceeded");
Expand All @@ -420,7 +423,6 @@ export function createStepModelQueueFetch(
});
if (response.ok) {
status = readQueueStatus(await response.json().catch(() => undefined));
if (!status) lastFailure = "invalid queue status";
} else if (response.status === 401 || response.status === 403) {
// A credential problem is the caller's to see, as it would be on the model route.
return response;
Expand All @@ -432,18 +434,22 @@ export function createStepModelQueueFetch(
// cannot improve by asking again.
else if (response.status !== 429 && response.status < 500)
return await giveUp(undefined, `Queue status request failed with HTTP ${response.status}`);
else lastFailure = `HTTP ${response.status}`;
}
} catch (error) {
} catch {
if (caller.aborted) throw abortError(caller);
lastFailure = error instanceof Error ? error.message : String(error);
}
if (!status) {
if (now() - lastSuccess >= failureBudgetMs)
return await giveUp(undefined, `Queue status unavailable: ${lastFailure}`);
delay = Math.min(FIRST_POLL_BACKOFF_MS * 2 ** failures, MAX_POLL_BACKOFF_MS);
failures++;
continue;
if (now() - lastSuccess < failureBudgetMs) {
delay = Math.min(FIRST_POLL_BACKOFF_MS * 2 ** failures, MAX_POLL_BACKOFF_MS);
failures++;
continue;
}
// The status endpoint keeps failing, while the generation route may
// still answer: the server runs a request without its queue when it
// cannot keep one, and seats again a request whose place expired.
// Send again under the same id instead of ending the call; a queued
// answer starts a fresh failure budget.
status = { state: "ready", retryAfterMs: delay };
}
lastSuccess = now();
failures = 0;
Expand All @@ -463,7 +469,16 @@ export function createStepModelQueueFetch(
// The SDK's per-attempt signal joins the resend only while it is live: an
// abort it already carries is its request timeout expiring in line.
unhold();
const response = await send(attempt && !attempt.aborted ? AbortSignal.any([caller, attempt]) : caller);
let response: Response;
try {
response = await send(attempt && !attempt.aborted ? AbortSignal.any([caller, attempt]) : caller);
} catch (error) {
// A resend that failed on the way (not a stop) leaves the place at the
// front of the line, where it would hold a slot until its lease ends:
// release it, then let the retry policy see the failure.
if (!caller.aborted) await leave();
throw error;
}
if (!isQueued(response)) {
// The server closed the place on the resend (the wait bound, say): end the call, never re-enter
// the line under a new id through a retry.
Expand Down
45 changes: 38 additions & 7 deletions packages/coding-agent/test/step-model-queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -675,8 +675,10 @@ test("a Request input's own signal also reaches the resend", async () => {
await assert.rejects(h.fetchRequest(input), { name: "AbortError" });
assert.deepEqual(
h.calls.map((call) => call.method),
["POST", "GET", "POST"],
["POST", "GET", "POST", "POST"],
);
// The resend stopped on its own signal, not the caller's: the place is released, as a retry gets a new id.
assertCancel(h.calls.at(-1));
assert.equal(h.released(), 1);
assert.equal(h.states.at(-1), null);
});
Expand Down Expand Up @@ -710,17 +712,46 @@ test("backs off on poll failures without changing the id", async () => {
assert.deepEqual(polls, new Set([`${QUEUE} q-1`]));
});

test("gives up once polling has failed for the whole budget", async () => {
test("once polling has failed for the whole budget, resends under the same id instead of ending the call", async () => {
const failures: Reply[] = Array.from({ length: 4 }, () => new Response("down", { status: 502 }));
const h = harness([queued(1), ...failures, new Response("{}", { status: 200 })], { budgetMs: 10_000 });
const h = harness([queued(1), ...failures, ok()], { budgetMs: 10_000 });
const response = await h.post();
assert.equal(response.status, 410);
const body = (await response.json()) as { error: { message: string } };
assert.match(body.error.message, /HTTP 502/u);
assert.equal(response.status, 200);
// 5000 + 1000 + 2000 + 4000 >= 10000 since the last success.
assert.deepEqual(h.sleeps, [5000, 1000, 2000, 4000]);
// This side stopped waiting, so it releases the place.
const resend = h.calls.at(-1);
assert.equal(resend?.method, "POST");
assert.equal(resend?.url, CHAT);
assert.equal(resend?.headers.get("X-StepCode-Queue-ID"), "q-1");
assert.equal(text(resend?.body), BODY);
// Nothing was given up: no cancel.
assert.equal(h.calls.filter((call) => call.url === `${QUEUE}/cancel`).length, 0);
assert.equal(h.states.at(-1), null);
});

test("a resend after the failure budget that is queued again polls with a fresh budget", async () => {
const failures = (): Reply[] => Array.from({ length: 4 }, () => new Response("down", { status: 502 }));
const h = harness(
[queued(1), ...failures(), queued(2), new Response("down", { status: 502 }), status("ready"), ok()],
{
budgetMs: 10_000,
},
);
const response = await h.post();
assert.equal(response.status, 200);
// The queued resend resets the backoff and the budget: one failure, then the next poll answers.
assert.deepEqual(h.sleeps, [5000, 1000, 2000, 4000, 5000, 1000]);
assert.deepEqual(
h.calls.map((call) => call.method),
["POST", "GET", "GET", "GET", "GET", "POST", "GET", "GET", "POST"],
);
});

test("a resend that fails on the way releases the place and surfaces the failure", async () => {
const h = harness([queued(1), status("ready"), new TypeError("fetch failed"), new Response("{}", { status: 200 })]);
await assert.rejects(h.post(), { message: "fetch failed" });
assertCancel(h.calls.at(-1));
assert.equal(h.calls.filter((call) => call.url === `${QUEUE}/cancel`).length, 1);
assert.equal(h.states.at(-1), null);
});

Expand Down