From 16f42347d696315c573dd895fdbfd4130281437e Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:24:36 -0500 Subject: [PATCH 1/3] fix(combo): time a rotated attempt from its own send, not the combo target's start A key or account rotation inside one combo target seals the earlier segment as its own attempt and moves activeAttemptStartedAt forward. The combo still finished the live segment from the target's start, so the last segment re-counted every sealed one and the request's attempt durations summed to more than the request took. Also adds a regression showing a failover combo relays the surviving target's deltas at the upstream's pace rather than in one burst. --- scripts/test-layout/layout-combos.json | 1 + src/server/responses/core-combo-native.ts | 3 +- src/server/responses/core-combo.ts | 20 +- tests/fixtures/test-layout-expected.json | 1 + .../combo-stream-attempt-timing.test.ts | 185 ++++++++++++++++++ 5 files changed, 201 insertions(+), 9 deletions(-) create mode 100644 tests/responses/combo-stream-attempt-timing.test.ts diff --git a/scripts/test-layout/layout-combos.json b/scripts/test-layout/layout-combos.json index cfd66d37241..5e3febc8c69 100644 --- a/scripts/test-layout/layout-combos.json +++ b/scripts/test-layout/layout-combos.json @@ -4,6 +4,7 @@ "server-combo-stream-send-contract.test.ts": "server", "server-combo-quota-code-provenance.test.ts": "server", "combo-codex-ws-overload-failover.test.ts": "responses", + "combo-stream-attempt-timing.test.ts": "responses", "combo-cooldown-persistence.test.ts": "routing", "server-combo-cooldown-recording.test.ts": "server" } diff --git a/src/server/responses/core-combo-native.ts b/src/server/responses/core-combo-native.ts index 2fc0268d82f..090b1f96a92 100644 --- a/src/server/responses/core-combo-native.ts +++ b/src/server/responses/core-combo-native.ts @@ -426,7 +426,8 @@ export async function dispatchNativeComboChild(input: { attempt, startedAt, seal: label => sealRequestAttemptIdentity(attempt, childLog.provider, childLog.providerAdapter ?? attempt.adapter, label), - finish: (status, usage) => finishRequestAttempt(attempt, status, Date.now() - startedAt, usage), + // A rotation inside the child seals the earlier account and moves the segment start forward. + finish: (status, usage) => finishRequestAttempt(attempt, status, Date.now() - (childLog.activeAttemptStartedAt ?? startedAt), usage), }; const child = { route: plan.route, diff --git a/src/server/responses/core-combo.ts b/src/server/responses/core-combo.ts index 61aa385cd07..14d01dd0218 100644 --- a/src/server/responses/core-combo.ts +++ b/src/server/responses/core-combo.ts @@ -1158,6 +1158,10 @@ export async function executeComboResponses( childLog.activeAttemptStartedAt = started; childLog.attempts = logCtx.attempts ??= []; childLog.attempts.push(attempt); + // A key or account rotation inside this target seals the previous segment as its own attempt + // and moves `childLog.activeAttemptStartedAt` forward (noteProviderAttemptSend). Timing the + // live segment from the target's start would count every sealed segment a second time. + const segmentStartedAt = (): number => childLog.activeAttemptStartedAt ?? started; let attemptRetained = false; const retainCancelledAttempt = (): void => { if (attemptRetained) return; @@ -1167,7 +1171,7 @@ export async function executeComboResponses( childLog.providerAdapter ?? attempt.adapter, childLog.accountLogLabel, ); - finishRequestAttempt(attempt, 499, Date.now() - started, childLog.usage); + finishRequestAttempt(attempt, 499, Date.now() - segmentStartedAt(), childLog.usage); attemptRetained = true; }; // The row is written from `logCtx`, which copies `childLog` only when the child commits. A @@ -1241,7 +1245,7 @@ export async function executeComboResponses( // Attempt-relative TTFT, recorded here for the same reason as the bridge child below. onFirstOutput: () => { if (attempt.firstOutputMs === undefined) { - attempt.firstOutputMs = Math.max(0, Date.now() - started); + attempt.firstOutputMs = Math.max(0, Date.now() - segmentStartedAt()); } options.onFirstOutput?.(); }, @@ -1272,7 +1276,7 @@ export async function executeComboResponses( // Object.assign(logCtx, childLog) would overwrite the request-relative value). onFirstOutput: () => { if (attempt.firstOutputMs === undefined) { - attempt.firstOutputMs = Math.max(0, Date.now() - started); + attempt.firstOutputMs = Math.max(0, Date.now() - segmentStartedAt()); } options.onFirstOutput?.(); }, @@ -1293,7 +1297,7 @@ export async function executeComboResponses( return clientCancelledResponse(); } jevPin?.forget(); - finishRequestAttempt(attempt, 502, Date.now() - started, childLog.usage); + finishRequestAttempt(attempt, 502, Date.now() - segmentStartedAt(), childLog.usage); throw error; } @@ -1321,7 +1325,7 @@ export async function executeComboResponses( return clientCancelledResponse(); } jevPin?.forget(); - finishRequestAttempt(attempt, 502, Date.now() - started, childLog.usage); + finishRequestAttempt(attempt, 502, Date.now() - segmentStartedAt(), childLog.usage); throw error; } if (preflight.kind === "failed") { @@ -1363,7 +1367,7 @@ export async function executeComboResponses( routeDecision: logCtx.routeDecision, attempts: logCtx.attempts, activeAttempt: attempt, - activeAttemptStartedAt: started, + activeAttemptStartedAt: segmentStartedAt(), resolvedModel: childLog.resolvedModel ?? childLog.model, }); options.onCodexAuthContextResolved?.(resolvedAuth); @@ -1391,7 +1395,7 @@ export async function executeComboResponses( return clientCancelledResponse(); } jevPin?.forget(); - finishRequestAttempt(attempt, 502, Date.now() - started, childLog.usage); + finishRequestAttempt(attempt, 502, Date.now() - segmentStartedAt(), childLog.usage); throw error; } if (options.abortSignal?.aborted) { @@ -1411,7 +1415,7 @@ export async function executeComboResponses( finishRequestAttempt( attempt, failure.response.status, - Date.now() - started, + Date.now() - segmentStartedAt(), failure.usage ?? childLog.usage, ); if (isReplayRefusalResponse(failure.response)) { diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index ebfabf37355..c2844cdc923 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1568,6 +1568,7 @@ "workflow-budget.test.ts": "lib", "ws-ambiguous-resend.test.ts": "responses", "ws-pre-output-refusal.test.ts": "responses", "responses-pool-overload-failover.test.ts": "responses", "compact-transient-alternate.test.ts": "responses", "combo-codex-ws-overload-failover.test.ts": "responses", + "combo-stream-attempt-timing.test.ts": "responses", "ws-capacity-reclamation.test.ts": "responses", "ws-capacity-tool-ownership.test.ts": "responses", "ws-endpoint.test.ts": "responses", diff --git a/tests/responses/combo-stream-attempt-timing.test.ts b/tests/responses/combo-stream-attempt-timing.test.ts new file mode 100644 index 00000000000..64f09eb94de --- /dev/null +++ b/tests/responses/combo-stream-attempt-timing.test.ts @@ -0,0 +1,185 @@ +/** + * Combo failover and attempt timing. + * + * 1. A combo that fails over still relays the surviving target's stream as it arrives: the combo + * preflight holds bytes only until the first output event, so later deltas reach the client + * at the upstream's pace instead of in one burst at the end. + * 2. A key rotation inside one combo target seals the earlier key as its own attempt. The live + * attempt is timed from the rotation, so the request's attempt durations never add up to more + * time than the request took. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { clearComboSelectionState, clearComboTargetCooldowns } from "../../src/combos"; +import { clearKeyCooldowns } from "../../src/providers/key-failover"; +import { handleComboResponses, handleResponses } from "../../src/server/responses/core"; +import { executeComboResponses } from "../../src/server/responses/core-combo"; +import { createTranslatorBudget } from "../../src/lib/translator-budget"; +import { noteProviderAttemptSend, type RequestLogContext } from "../../src/server/request-log"; +import type { OcxConfig } from "../../src/types"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; + +const originalFetch = globalThis.fetch; +let releaseSpendHome: (() => void) | undefined; +const reset = (): void => { + clearComboSelectionState(); + clearComboTargetCooldowns(); + clearKeyCooldowns(); +}; +beforeEach(() => { + reset(); + releaseSpendHome = acquireOwnedSpendHome(); +}); +afterEach(() => { + releaseSpendHome?.(); + releaseSpendHome = undefined; + globalThis.fetch = originalFetch; + reset(); +}); + +const encoder = new TextEncoder(); +const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const DELTAS = 5; +const GAP_MS = 120; + +function event(payload: Record): string { + return `event: ${String(payload.type)}\ndata: ${JSON.stringify(payload)}\n\n`; +} + +/** A Responses SSE whose text deltas are spaced GAP_MS apart. */ +function pacedResponsesStream(): Response { + const frames = [ + event({ type: "response.created", response: { id: "resp_1", status: "in_progress", output: [] } }), + event({ type: "response.output_item.added", output_index: 0, item: { id: "msg_1", type: "message", role: "assistant", content: [] } }), + ...Array.from({ length: DELTAS }, (_, i) => event({ + type: "response.output_text.delta", item_id: "msg_1", output_index: 0, content_index: 0, delta: `w${i} `, + })), + event({ + type: "response.completed", + response: { + id: "resp_1", status: "completed", + output: [{ id: "msg_1", type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text: "done", annotations: [] }] }], + usage: { input_tokens: 2, output_tokens: DELTAS, total_tokens: DELTAS + 2 }, + }, + }), + ]; + const body = new ReadableStream({ + async start(controller) { + for (const frame of frames) { + controller.enqueue(encoder.encode(frame)); + if (frame.includes("output_text.delta")) await sleep(GAP_MS); + } + controller.close(); + }, + }); + return new Response(body, { headers: { "content-type": "text/event-stream" } }); +} + +const rateLimited = () => Response.json({ error: { message: "rate limited", type: "rate_limit_error" } }, { status: 429 }); + +function provider(name: string, extra: Record = {}) { + return { + adapter: "openai-responses", + baseUrl: `https://${name}.example/v1`, + authMode: "key", + apiKey: `sk-${name}-1`, + models: [`model-${name}`], + ...extra, + }; +} + +function comboConfig(providers: Record, targets: string[]): OcxConfig { + return { + defaultProvider: targets.at(-1), + providers, + combos: { fan: { strategy: "failover", targets: targets.map(name => ({ provider: name, model: `model-${name}` })) } }, + } as unknown as OcxConfig; +} + +async function run( + config: OcxConfig, + logCtx: RequestLogContext, + dispatchers = { handleComboResponses, handleResponses }, +): Promise { + const req = new Request("http://localhost/v1/responses", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "combo/fan", stream: true, input: "hello" }), + }); + return executeComboResponses(req, await req.clone().json(), "fan", config, logCtx, { + translatorBudget: createTranslatorBudget(), + }, dispatchers); +} + +/** Read the body and return the arrival time of each chunk that carries a text delta. */ +async function deltaArrivals(response: Response, startedAt: number): Promise { + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + const arrivals: number[] = []; + for (;;) { + const next = await reader.read(); + if (next.done) return arrivals; + const text = decoder.decode(next.value, { stream: true }); + const count = text.split("\n").filter(line => line.startsWith("data:") && line.includes("\"response.output_text.delta\"")).length; + for (let i = 0; i < count; i++) arrivals.push(performance.now() - startedAt); + } +} + +describe("combo failover streaming", () => { + test("the surviving target's deltas reach the client at the upstream's pace", async () => { + globalThis.fetch = (async (input: string | URL | Request) => { + const host = new URL(input instanceof Request ? input.url : String(input)).host; + return host.startsWith("bad") ? rateLimited() : pacedResponsesStream(); + }) as typeof fetch; + const startedAt = performance.now(); + const response = await run(comboConfig({ bad: provider("bad"), good: provider("good") }, ["bad", "good"]), { model: "", provider: "" }); + expect(response.status).toBe(200); + const arrivals = await deltaArrivals(response, startedAt); + expect(arrivals).toHaveLength(DELTAS); + // A buffered relay would deliver every delta within a few ms of the last one. + expect(arrivals.at(-1)! - arrivals[0]!).toBeGreaterThanOrEqual(GAP_MS * (DELTAS - 2)); + }, 15_000); +}); + +describe("combo attempt timing across a key rotation", () => { + test("each key's attempt is timed on its own and the sum fits inside the request", async () => { + const KEY_LATENCY_MS = 150; + globalThis.fetch = (async () => pacedResponsesStream()) as typeof fetch; + const config = comboConfig({ pool: provider("pool"), good: provider("good") }, ["pool", "good"]); + const keyed = (entryId: string) => ({ + ...config.providers.pool!, + _apiKeyAttempt: { entryId, reference: `sk-pool-${entryId}` }, + }); + // The pooled target stands in for a child that rotates keys once and is refused on both: the + // rotation runs through the same request-log seam a real key or account rotation does. + const rotatingChild: typeof handleResponses = async (_req, _config, childLog) => { + noteProviderAttemptSend(childLog, "pool", keyed("k1"), undefined); + await sleep(KEY_LATENCY_MS); + noteProviderAttemptSend(childLog, "pool", keyed("k2"), undefined, "key-429"); + await sleep(KEY_LATENCY_MS); + return rateLimited(); + }; + const dispatchers = { + handleComboResponses, + handleResponses: ((req, cfg, childLog, ...rest) => childLog.provider === "pool" + ? rotatingChild(req, cfg, childLog, ...rest) + : handleResponses(req, cfg, childLog, ...rest)) as typeof handleResponses, + }; + const logCtx: RequestLogContext = { model: "", provider: "" }; + const startedAt = Date.now(); + const response = await run(config, logCtx, dispatchers); + expect(response.status).toBe(200); + await response.text(); + const elapsed = Date.now() - startedAt; + + const attempts = logCtx.attempts ?? []; + const poolAttempts = attempts.filter(attempt => attempt.provider === "pool"); + expect(poolAttempts).toHaveLength(2); + expect(poolAttempts[1]!.recoveryKinds).toEqual(["key-429"]); + for (const attempt of poolAttempts) { + // Timed from its own send: one key's latency, not the target's running total. + expect(attempt.durationMs).toBeLessThan(KEY_LATENCY_MS * 2 - 40); + } + const sum = attempts.reduce((total, attempt) => total + (attempt.durationMs ?? 0), 0); + expect(sum).toBeLessThanOrEqual(elapsed + 5); + }, 15_000); +}); From ae46dde7b62dece14cd0577ffff289ba27618ceb Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 02:39:40 -0500 Subject: [PATCH 2/3] test(combo): compare the rotated attempt with measured instants, not fixed milliseconds The rotation case asserted each attempt stayed under an absolute bound, which a heavily loaded machine exceeded with the fix in place. It now checks the second key's attempt is shorter than the child's own measured run, which the old target-start timing can never satisfy. --- .../combo-stream-attempt-timing.test.ts | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/tests/responses/combo-stream-attempt-timing.test.ts b/tests/responses/combo-stream-attempt-timing.test.ts index 64f09eb94de..2dce1b3a17f 100644 --- a/tests/responses/combo-stream-attempt-timing.test.ts +++ b/tests/responses/combo-stream-attempt-timing.test.ts @@ -142,20 +142,28 @@ describe("combo failover streaming", () => { describe("combo attempt timing across a key rotation", () => { test("each key's attempt is timed on its own and the sum fits inside the request", async () => { - const KEY_LATENCY_MS = 150; + // The first key is slow and the second fast, so the two ways of timing the live attempt differ + // by a whole first segment. The assertions compare against instants this test measures, never + // fixed milliseconds, so a loaded machine stretches both sides alike. + const FIRST_KEY_MS = 300; + const SECOND_KEY_MS = 30; globalThis.fetch = (async () => pacedResponsesStream()) as typeof fetch; const config = comboConfig({ pool: provider("pool"), good: provider("good") }, ["pool", "good"]); const keyed = (entryId: string) => ({ ...config.providers.pool!, _apiKeyAttempt: { entryId, reference: `sk-pool-${entryId}` }, }); + let childStartedAt = 0; + let childReturnedAt = 0; // The pooled target stands in for a child that rotates keys once and is refused on both: the // rotation runs through the same request-log seam a real key or account rotation does. const rotatingChild: typeof handleResponses = async (_req, _config, childLog) => { + childStartedAt = Date.now(); noteProviderAttemptSend(childLog, "pool", keyed("k1"), undefined); - await sleep(KEY_LATENCY_MS); + await sleep(FIRST_KEY_MS); noteProviderAttemptSend(childLog, "pool", keyed("k2"), undefined, "key-429"); - await sleep(KEY_LATENCY_MS); + await sleep(SECOND_KEY_MS); + childReturnedAt = Date.now(); return rateLimited(); }; const dispatchers = { @@ -175,10 +183,10 @@ describe("combo attempt timing across a key rotation", () => { const poolAttempts = attempts.filter(attempt => attempt.provider === "pool"); expect(poolAttempts).toHaveLength(2); expect(poolAttempts[1]!.recoveryKinds).toEqual(["key-429"]); - for (const attempt of poolAttempts) { - // Timed from its own send: one key's latency, not the target's running total. - expect(attempt.durationMs).toBeLessThan(KEY_LATENCY_MS * 2 - 40); - } + // Timed from the target's start, the second key's attempt would cover the whole child, so it + // could never be shorter than the child's own measured run. Timed from its own send it covers + // only the fast second segment plus the combo's failure handling. + expect(poolAttempts[1]!.durationMs).toBeLessThan(childReturnedAt - childStartedAt); const sum = attempts.reduce((total, attempt) => total + (attempt.durationMs ?? 0), 0); expect(sum).toBeLessThanOrEqual(elapsed + 5); }, 15_000); From 180caac769021512a46f932f0c5d79163cba1034 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Tue, 17 Nov 2026 02:11:08 -0500 Subject: [PATCH 3/3] test(combo): compare the first delta with the upstream's last send, not client-side gaps --- .../combo-stream-attempt-timing.test.ts | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/tests/responses/combo-stream-attempt-timing.test.ts b/tests/responses/combo-stream-attempt-timing.test.ts index 2dce1b3a17f..dd10621c6d2 100644 --- a/tests/responses/combo-stream-attempt-timing.test.ts +++ b/tests/responses/combo-stream-attempt-timing.test.ts @@ -45,8 +45,8 @@ function event(payload: Record): string { return `event: ${String(payload.type)}\ndata: ${JSON.stringify(payload)}\n\n`; } -/** A Responses SSE whose text deltas are spaced GAP_MS apart. */ -function pacedResponsesStream(): Response { +/** A Responses SSE whose text deltas are spaced GAP_MS apart; `emitted` records when each delta is enqueued. */ +function pacedResponsesStream(emitted: number[] = []): Response { const frames = [ event({ type: "response.created", response: { id: "resp_1", status: "in_progress", output: [] } }), event({ type: "response.output_item.added", output_index: 0, item: { id: "msg_1", type: "message", role: "assistant", content: [] } }), @@ -65,6 +65,7 @@ function pacedResponsesStream(): Response { const body = new ReadableStream({ async start(controller) { for (const frame of frames) { + if (frame.includes("output_text.delta")) emitted.push(performance.now()); controller.enqueue(encoder.encode(frame)); if (frame.includes("output_text.delta")) await sleep(GAP_MS); } @@ -110,8 +111,8 @@ async function run( }, dispatchers); } -/** Read the body and return the arrival time of each chunk that carries a text delta. */ -async function deltaArrivals(response: Response, startedAt: number): Promise { +/** Read the body and return the `performance.now()` arrival time of each text delta. */ +async function deltaArrivals(response: Response): Promise { const reader = response.body!.getReader(); const decoder = new TextDecoder(); const arrivals: number[] = []; @@ -120,23 +121,25 @@ async function deltaArrivals(response: Response, startedAt: number): Promise line.startsWith("data:") && line.includes("\"response.output_text.delta\"")).length; - for (let i = 0; i < count; i++) arrivals.push(performance.now() - startedAt); + for (let i = 0; i < count; i++) arrivals.push(performance.now()); } } describe("combo failover streaming", () => { test("the surviving target's deltas reach the client at the upstream's pace", async () => { + const emitted: number[] = []; globalThis.fetch = (async (input: string | URL | Request) => { const host = new URL(input instanceof Request ? input.url : String(input)).host; - return host.startsWith("bad") ? rateLimited() : pacedResponsesStream(); + return host.startsWith("bad") ? rateLimited() : pacedResponsesStream(emitted); }) as typeof fetch; - const startedAt = performance.now(); const response = await run(comboConfig({ bad: provider("bad"), good: provider("good") }, ["bad", "good"]), { model: "", provider: "" }); expect(response.status).toBe(200); - const arrivals = await deltaArrivals(response, startedAt); + const arrivals = await deltaArrivals(response); + expect(emitted).toHaveLength(DELTAS); expect(arrivals).toHaveLength(DELTAS); - // A buffered relay would deliver every delta within a few ms of the last one. - expect(arrivals.at(-1)! - arrivals[0]!).toBeGreaterThanOrEqual(GAP_MS * (DELTAS - 2)); + // A buffered relay holds the first delta until the upstream has sent the last one. Comparing + // with the upstream's own send instant leaves (DELTAS - 1) * GAP_MS of slack for a slow machine. + expect(arrivals[0]!).toBeLessThan(emitted.at(-1)!); }, 15_000); });