diff --git a/scripts/test-layout/layout-combos.json b/scripts/test-layout/layout-combos.json index 0863446effc..8d16635f154 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", "combo-selection-keepalive.test.ts": "routing", 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 74a5d4f918b..689a9886f6b 100644 --- a/src/server/responses/core-combo.ts +++ b/src/server/responses/core-combo.ts @@ -1173,6 +1173,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; @@ -1182,7 +1186,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 @@ -1256,7 +1260,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?.(); }, @@ -1287,7 +1291,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?.(); }, @@ -1308,7 +1312,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; } @@ -1336,7 +1340,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") { @@ -1378,7 +1382,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); @@ -1406,7 +1410,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) { @@ -1426,7 +1430,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 289167d3f2b..6df3da03213 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1579,6 +1579,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..dd10621c6d2 --- /dev/null +++ b/tests/responses/combo-stream-attempt-timing.test.ts @@ -0,0 +1,196 @@ +/** + * 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; `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: [] } }), + ...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) { + 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); + } + 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 `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[] = []; + 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()); + } +} + +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(emitted); + }) as typeof fetch; + 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); + expect(emitted).toHaveLength(DELTAS); + expect(arrivals).toHaveLength(DELTAS); + // 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); +}); + +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 () => { + // 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(FIRST_KEY_MS); + noteProviderAttemptSend(childLog, "pool", keyed("k2"), undefined, "key-429"); + await sleep(SECOND_KEY_MS); + childReturnedAt = Date.now(); + 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"]); + // 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); +});