diff --git a/bin/opencode-route-proxy.mjs b/bin/opencode-route-proxy.mjs index b6f70f1ab3..9f48b9a143 100755 --- a/bin/opencode-route-proxy.mjs +++ b/bin/opencode-route-proxy.mjs @@ -122,6 +122,14 @@ const ADVERTISED_MODELS = [ const MAX_ATTEMPTS = 6; const DEMOTE_WINDOW_MS = 4 * 60 * 60 * 1000; const DEMOTE_THRESHOLD = 3; +const STREAM_FIRST_CONTENT_WINDOW_MS = 250; +const STREAM_PREFACE_MAX_BYTES = 64 * 1024; +// Hard ceiling for a single in-progress data event in the relay: the +// preface window (above) rejects non-content prefaces, but one valid +// content event may be larger than the window, so its enforcement is +// deferred until the event completes (see relayStream). This ceiling +// still bounds a never-ending event. +const STREAM_EVENT_HARD_MAX_BYTES = 16 * 1024 * 1024; // ---------------------------------------------------------------- config @@ -858,6 +866,247 @@ const classifyHttp = (status, headers, bodyText) => { }); }; +const classifyStreamError = (providerError, headers) => { + const details = + typeof providerError === "object" && providerError !== null + ? providerError + : { message: String(providerError) }; + const message = + typeof details.message === "string" + ? details.message + : JSON.stringify(details); + const status = Number(details.status ?? details.status_code); + const type = typeof details.type === "string" ? details.type : ""; + const code = typeof details.code === "string" ? details.code : null; + const quotaFailure = + status === 429 || /rate.?limit|quota|insufficient_quota/i.test( + `${type} ${code || ""} ${message}`, + ); + if (quotaFailure) { + const err = classifyHttp(429, headers, message); + err.status = 429; + err.code = code; + let quota = {}; + try { + quota = JSON.parse(err.quota || "{}"); + } catch {} + err.quota = JSON.stringify({ + ...quota, + status: 429, + ...(type ? { type } : {}), + ...(code ? { code } : {}), + }); + return err; + } + return new LeafError(message, { + tag: "ProviderInternal", + status: Number.isFinite(status) ? status : null, + code, + }); +}; + +const streamPayloadHasContent = (payload) => { + if (!Array.isArray(payload?.choices)) return false; + return payload.choices.some((choice) => { + if (typeof choice?.text === "string" && choice.text.length > 0) + return true; + const delta = choice?.delta; + if (!delta || typeof delta !== "object" || Array.isArray(delta)) + return false; + return Object.entries(delta).some(([key, value]) => { + if (key === "role" || value == null || value === "") return false; + return !Array.isArray(value) || value.length > 0; + }); + }); +}; + +const newSseState = (started) => ({ + decoder: new TextDecoder(), + tail: "", + contentStarted: false, + started, + firstTokenMs: null, + usage: null, + done: false, + streamError: null, +}); + +const inspectSseEvent = (event, state, headers) => { + const data = event + .split(/\r?\n/) + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).replace(/^ /, "")) + .join("\n") + .trim(); + if (!data) return; + if (data === "[DONE]") { + state.done = true; + return; + } + let payload; + try { + payload = JSON.parse(data); + } catch { + // Preserve compatibility with providers that send non-JSON data events. + if (!state.contentStarted) { + state.contentStarted = true; + state.firstTokenMs ??= Date.now() - state.started; + } + return; + } + if (payload?.usage) state.usage = payload.usage; + if (payload?.error) { + if (!state.streamError) + state.streamError = { + error: classifyStreamError(payload.error, headers), + beforeContent: !state.contentStarted, + }; + return; + } + if (streamPayloadHasContent(payload) && !state.contentStarted) { + state.contentStarted = true; + state.firstTokenMs = Date.now() - state.started; + } +}; + +const inspectSseBytes = (value, state, headers, flush = false) => { + const decoded = flush + ? state.decoder.decode() + : state.decoder.decode(value, { stream: true }); + state.tail += decoded; + // Parse every complete event BEFORE bounding the buffer: trimming + // first would cut the head off an event larger than the preface + // window (a large tool-call argument delta is a single event), + // removing its data: prefix so it is never recognised as content + // (Codex P2 on PR #5558). + const separator = /\r?\n\r?\n/g; + let match; + let start = 0; + while ((match = separator.exec(state.tail))) { + inspectSseEvent(state.tail.slice(start, match.index), state, headers); + start = separator.lastIndex; + } + state.tail = state.tail.slice(start); + if (state.tail.length > STREAM_PREFACE_MAX_BYTES) { + // The tail is now a single partial event. Distinguish a large + // content event from a non-content preface: everything from the + // event's first data: line on is its payload and stays whole, + // however large — the preface limits are enforced on raw bytes + // by the callers (prepare/relay byte counts), not by mangling + // this buffer. With no data: line yet, nothing here can be + // recognised as content, so keep only the newest window. + const dataStart = state.tail.search(/^data:/m); + state.tail = + dataStart === -1 + ? state.tail.slice(-STREAM_PREFACE_MAX_BYTES) + : state.tail.slice(dataStart); + } + if (flush && state.tail.trim()) { + inspectSseEvent(state.tail, state, headers); + state.tail = ""; + } +}; + +const streamTransportError = (err) => + new LeafError(`leaf stream transport error: ${err?.message || err}`, { + tag: "Transport", + code: err?.cause?.code || err?.code || null, + }); + +const readWithinWindow = async (pendingRead, ms, signal) => { + if (signal.aborted) return { kind: "aborted", error: signal.reason }; + let timer; + let abortHandler; + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve({ kind: "timeout" }), ms); + }); + const aborted = new Promise((resolve) => { + abortHandler = () => resolve({ kind: "aborted", error: signal.reason }); + signal.addEventListener("abort", abortHandler, { once: true }); + }); + try { + return await Promise.race([pendingRead, timeout, aborted]); + } finally { + clearTimeout(timer); + signal.removeEventListener("abort", abortHandler); + } +}; + +const prepareStream = async (leafRes, signal, started) => { + if (!leafRes.body) + return { + error: new LeafError("leaf stream has no body", { tag: "Transport" }), + }; + const reader = leafRes.body.getReader(); + const state = newSseState(started); + const buffered = []; + let bufferedBytes = 0; + let pendingRead = null; + const deadline = Date.now() + STREAM_FIRST_CONTENT_WINDOW_MS; + const cancel = (reason) => { + try { + void reader.cancel(reason).catch(() => {}); + } catch {} + }; + const prepared = (ended = false) => ({ + reader, + state, + buffered, + pendingRead, + ended, + }); + + for (;;) { + if (state.streamError?.beforeContent) { + cancel(state.streamError.error); + return { error: state.streamError.error }; + } + if (state.contentStarted) return prepared(); + if (state.done) + return { + error: new LeafError("leaf stream ended before content", { + tag: "ProviderInternal", + }), + }; + if (bufferedBytes >= STREAM_PREFACE_MAX_BYTES) return prepared(); + const remaining = deadline - Date.now(); + if (remaining <= 0) return prepared(); + if (signal.aborted) { + cancel(signal.reason); + return { error: streamTransportError(signal.reason) }; + } + + pendingRead = reader.read().then( + (result) => ({ kind: "read", result }), + (error) => ({ kind: "error", error }), + ); + const result = await readWithinWindow(pendingRead, remaining, signal); + if (result.kind === "timeout") return prepared(); + pendingRead = null; + if (result.kind === "aborted") { + cancel(result.error); + return { error: streamTransportError(result.error) }; + } + if (result.kind === "error") return { error: streamTransportError(result.error) }; + if (result.result.done) { + inspectSseBytes(null, state, leafRes.headers, true); + if (state.streamError?.beforeContent) + return { error: state.streamError.error }; + if (!state.contentStarted) + return { + error: new LeafError("leaf stream ended before content", { + tag: "ProviderInternal", + }), + }; + return prepared(true); + } + const value = result.result.value; + buffered.push(value); + bufferedBytes += value.byteLength; + inspectSseBytes(value, state, leafRes.headers); + } +}; + // One plain chat-completions call to a leaf provider. Returns the fetch // Response (unchecked status handled by the caller for failover). const callLeaf = async (cfg, leaf, body, wantStream, signal, sessionLabel) => { @@ -931,10 +1180,10 @@ const usageFields = (usage) => { // ---------------------------------------------------------------- core -// Run one completion through the route's candidates. Streaming is -// two-phase: candidates are tried until one returns a 2xx (nothing has -// been sent to the client yet), then onStream(res) takes over the -// response and this returns the collected stream stats. +// Run one completion through the route's candidates. For streaming, a +// 2xx candidate is inspected through its first content delta (or a +// bounded preface window); pre-content failures continue the walk, then +// onStream takes over and returns the collected stream stats. const runCompletion = async (routeId, body, clientSignal, hooks = {}) => { const cfg = loadConfig(); if (!cfg.routes[routeId]) @@ -1050,8 +1299,60 @@ const runCompletion = async (routeId, body, clientSignal, hooks = {}) => { } // Success path. if (wantStream) { - const stats = await hooks.onStream(res); + const prepared = await prepareStream(res, signal, started); + if (prepared.error) { + const ended = Date.now(); + const err = prepared.error; + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: signal.aborted ? "timeout" : "failure", + errorTag: err.tag || "ProviderInternal", + errorCode: err.code ?? null, + errorStatus: err.status, + errorMessage: String(err.message || err).slice(0, 500), + retryable: err.retryable ?? 1, + outputStarted: false, + failedOverTo, + responseMs: ended - started, + quota: err.quota ?? null, + }); + lastErr = err; + if (signal.aborted) throw err; + continue; + } + const stats = await hooks.onStream(res, prepared); + if (stats?.precommitError) { + const ended = Date.now(); + const err = stats.precommitError; + recordAttempt({ + started, + ended, + routeId, + providerId: leaf.providerId, + modelId: leaf.modelKey, + variant: leaf.variant, + outcome: signal.aborted ? "timeout" : "failure", + errorTag: err.tag || "ProviderInternal", + errorCode: err.code ?? null, + errorStatus: err.status, + errorMessage: String(err.message || err).slice(0, 500), + retryable: err.retryable ?? 1, + outputStarted: false, + failedOverTo, + responseMs: ended - started, + quota: err.quota ?? null, + }); + lastErr = err; + if (signal.aborted) throw err; + continue; + } const ended = Date.now(); + const err = stats?.errorDetails ?? null; recordAttempt({ started, ended, @@ -1060,11 +1361,15 @@ const runCompletion = async (routeId, body, clientSignal, hooks = {}) => { modelId: leaf.modelKey, variant: leaf.variant, outcome: stats?.error ? "failure" : "success", - errorTag: stats?.error ? "ProviderInternal" : null, + errorTag: err?.tag ?? (stats?.error ? "ProviderInternal" : null), + errorCode: err?.code ?? null, + errorStatus: err?.status ?? null, errorMessage: stats?.error ? String(stats.error).slice(0, 500) : null, - outputStarted: true, + retryable: err?.retryable, + outputStarted: stats?.contentStarted ?? false, + quota: err?.quota ?? null, firstTokenMs: stats?.firstTokenMs ?? null, responseMs: ended - started, ...(stats?.usage ? usageFields(stats.usage) : {}), @@ -1122,39 +1427,112 @@ const parseRouteModel = (raw) => { : { routeId: id, variant: null }; }; -// Relay a leaf SSE stream verbatim to the client while collecting the -// final usage block and timing. Returns { usage, firstTokenMs, error }. -const relayStream = async (leafRes, res) => { - const started = Date.now(); - let firstTokenMs = null; - let usage = null; - let error = null; - const reader = leafRes.body.getReader(); - const decoder = new TextDecoder(); - let tail = ""; - try { - for (;;) { - const { done, value } = await reader.read(); - if (done) break; - if (firstTokenMs === null) firstTokenMs = Date.now() - started; - if (!res.destroyed && !res.writableEnded) res.write(value); - // Keep only the tail: usage rides in the final chunk(s). - tail = (tail + decoder.decode(value, { stream: true })).slice(-8192); +// Relay the already-inspected preface and the rest of the SSE stream. +// A failure before a content delta is still a candidate failure; after a +// content delta has reached the client, retrying would splice responses. +const relayStream = async (prepared, res, headers) => { + const { reader, state, buffered } = prepared; + let pendingRead = prepared.pendingRead; + let errorDetails = state.streamError?.error ?? null; + let preContent = state.contentStarted ? [] : [...buffered]; + let preContentBytes = preContent.reduce((n, value) => n + value.byteLength, 0); + const precommitFailure = (err) => ({ + usage: state.usage, + firstTokenMs: state.firstTokenMs, + contentStarted: false, + precommitError: err, + }); + const write = (value) => { + if (!res.destroyed && !res.writableEnded) res.write(value); + }; + + if (state.contentStarted) + for (const value of buffered) write(value); + while (!prepared.ended) { + const next = pendingRead + ? await pendingRead + : await reader.read().then( + (result) => ({ kind: "read", result }), + (err) => ({ kind: "error", error: err }), + ); + pendingRead = null; + if (next.kind === "error") { + const err = streamTransportError(next.error); + if (!state.contentStarted) { + try { + void reader.cancel(err).catch(() => {}); + } catch {} + return precommitFailure(err); + } + errorDetails = err; + break; } - } catch (err) { - error = err?.message || String(err); - } - for (const line of tail.split("\n")) { - if (!line.startsWith("data:")) continue; - const data = line.slice(5).trim(); - if (!data || data === "[DONE]") continue; - try { - const parsed = JSON.parse(data); - if (parsed.usage) usage = parsed.usage; - if (parsed.error) error = parsed.error.message || JSON.stringify(parsed.error); - } catch {} + if (next.result.done) { + inspectSseBytes(null, state, headers, true); + if (state.streamError) errorDetails = state.streamError.error; + if (!state.contentStarted) + return precommitFailure( + errorDetails || + new LeafError("leaf stream ended before content", { + tag: "ProviderInternal", + }), + ); + break; + } + + const value = next.result.value; + inspectSseBytes(value, state, headers); + if (state.streamError?.beforeContent && !state.contentStarted) { + try { + void reader.cancel(state.streamError.error).catch(() => {}); + } catch {} + return precommitFailure(state.streamError.error); + } + if (!state.contentStarted) { + preContent.push(value); + preContentBytes += value.byteLength; + if (preContentBytes > STREAM_PREFACE_MAX_BYTES) { + // Distinguish a large content event from a non-content + // preface (Codex P2 on PR #5558): while the inspector's + // partial event already carries a data: payload, the event + // has not been judged yet — defer the limit until it + // completes. This matters when the prepare window expired + // mid-event, so the relay's byte count restarted part-way + // through one valid event. A hard ceiling still bounds a + // never-ending event. + if ( + state.tail.includes("data:") && + preContentBytes <= STREAM_EVENT_HARD_MAX_BYTES + ) + continue; + const err = new LeafError( + "leaf stream preface exceeded the pre-content limit", + { tag: "ProviderInternal" }, + ); + // Cancel the rejected upstream before failing over (Codex + // P2 on PR #5558): without this, a successful replacement + // clears the shared deadline timer and the rejected response + // is left generating with no cancellation path — the + // adjacent pre-content SSE-error path above already cancels. + try { + void reader.cancel(err).catch(() => {}); + } catch {} + return precommitFailure(err); + } + continue; + } + for (const chunk of preContent) write(chunk); + preContent = []; + write(value); + if (state.streamError) errorDetails = state.streamError.error; } - return { usage, firstTokenMs, error }; + return { + usage: state.usage, + firstTokenMs: state.firstTokenMs, + contentStarted: state.contentStarted, + error: errorDetails?.message ?? null, + errorDetails, + }; }; const handleChatCompletions = async (req, res, body) => { @@ -1177,18 +1555,19 @@ const handleChatCompletions = async (req, res, body) => { try { await runCompletion(routeId, body, clientCtl.signal, { variantIn: reqVariant, - onStream: async (leafRes) => { - res.writeHead(200, { - "content-type": "text/event-stream", - "cache-control": "no-cache", - connection: "keep-alive", - }); - headersSent = true; - const stats = await relayStream(leafRes, res); - if (!res.destroyed && !res.writableEnded) res.end(); - return stats; + onStream: async (leafRes, prepared) => { + if (!headersSent) { + res.writeHead(200, { + "content-type": "text/event-stream", + "cache-control": "no-cache", + connection: "keep-alive", + }); + headersSent = true; + } + return relayStream(prepared, res, leafRes.headers); }, }); + if (!res.destroyed && !res.writableEnded) res.end(); } catch (err) { if (!headersSent) { return sendError(res, 502, String(err?.message || err)); diff --git a/bin/opencode-route-proxy.test.mjs b/bin/opencode-route-proxy.test.mjs index c24bdce824..10f9215b4c 100644 --- a/bin/opencode-route-proxy.test.mjs +++ b/bin/opencode-route-proxy.test.mjs @@ -33,7 +33,7 @@ const freePort = () => const makeLeaf = (name, expectedKey) => { const leaf = { name, - mode: "ok", // ok | rate | auth + mode: "ok", // ok | rate | auth | sse-rate | delayed-sse-rate | stream-break | late-sse-rate | delayed-stream | big-first-event | preface-flood last: null, hits: 0, server: null, @@ -67,6 +67,46 @@ const makeLeaf = (name, expectedKey) => { }); return res.end(JSON.stringify({ error: { message: "quota" } })); } + if (leaf.mode === "sse-rate") { + res.writeHead(200, { + "content-type": "text/event-stream", + "retry-after": "30", + }); + const error = JSON.stringify({ + error: { + message: "quota exhausted", + type: "rate_limit_error", + code: "insufficient_quota", + status: 429, + }, + }); + res.write(`data: ${error.slice(0, 14)}`); + return setTimeout(() => res.end(`${error.slice(14)}\n\n`), 10); + } + if (leaf.mode === "delayed-sse-rate") { + res.writeHead(200, { + "content-type": "text/event-stream", + "retry-after": "30", + }); + res.write(": heartbeat\n\n"); + const error = JSON.stringify({ + error: { + message: "quota exhausted", + type: "rate_limit_error", + code: "insufficient_quota", + status: 429, + }, + }); + return setTimeout(() => { + res.write(`data: ${error.slice(0, 14)}`); + setTimeout(() => res.end(`${error.slice(14)}\n\n`), 10); + }, 300); + } + if (leaf.mode === "stream-break") { + res.writeHead(200, { "content-type": "text/event-stream" }); + res.write(": heartbeat\n\n"); + return setTimeout(() => res.destroy(), 10); + } if (body.stream) { res.writeHead(200, { "content-type": "text/event-stream" }); const chunk = (delta, usage) => @@ -84,7 +124,87 @@ const makeLeaf = (name, expectedKey) => { ], ...(usage ? { usage } : {}), })}\n\n`; - res.write(chunk({ role: "assistant", content: name })); + if (leaf.mode === "big-first-event") { + // One valid first content event larger than the relay's + // 64 KiB preface window, delivered in slices so the parser + // buffer crosses the window mid-event (#5558 Codex P2). + const big = "A".repeat(96 * 1024); + const event = `data: ${JSON.stringify({ + id: "chatcmpl-x", + object: "chat.completion.chunk", + created: 1, + model: body.model, + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { index: 0, function: { name: "f", arguments: big } }, + ], + }, + finish_reason: null, + }, + ], + })}\n\n`; + let off = 0; + const step = () => { + if (off < event.length) { + res.write(event.slice(off, off + 8192)); + off += 8192; + return setTimeout(step, 1); + } + res.write( + chunk({}, { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 }), + ); + return res.end("data: [DONE]\n\n"); + }; + return step(); + } + if (leaf.mode === "preface-flood") { + // A non-content preface past the relay's pre-content + // limit, then the response stays open: the relay must + // fail over AND cancel this stream (#5558 Codex P2). + // Cancellation is observable here as the socket closing + // before the response ever ended. + leaf.prefaceAborted = false; + res.on("close", () => { + if (!res.writableEnded) leaf.prefaceAborted = true; + }); + res.write(": preface\n\n"); + let sent = 0; + const step = () => { + if (res.destroyed || res.writableEnded) return; + res.write(`: ${"p".repeat(4096)}\n\n`); + sent += 4096; + if (sent < 192 * 1024) return setTimeout(step, 1); + // Hold the response open; only the relay's cancel ends it. + }; + return step(); + } + if (leaf.mode === "delayed-stream") { + res.write(chunk({ role: "assistant" })); + return setTimeout(() => { + res.write(chunk({ content: name })); + res.write( + chunk({}, { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 }), + ); + res.end("data: [DONE]\n\n"); + }, 350); + } + res.write(chunk({ role: "assistant" })); + res.write(chunk({ content: name })); + if (leaf.mode === "late-sse-rate") { + return res.end( + `data: ${JSON.stringify({ + error: { + message: "late quota exhausted", + type: "rate_limit_error", + code: "insufficient_quota", + status: 429, + }, + })}\n\n`, + ); + } res.write( chunk({}, { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 }), ); @@ -271,7 +391,7 @@ const startProxy = async (arg = {}) => { const ro = new DatabaseSync(dbPath, { readOnly: true }); const rows = ro .prepare( - "SELECT route_id, provider_id, model_id, variant, outcome, error_tag, error_status, quota, session_id, failed_over_to, output_started FROM route_attempt ORDER BY id", + "SELECT route_id, provider_id, model_id, variant, outcome, error_tag, error_status, error_message, quota, session_id, failed_over_to, output_started, first_token_ms FROM route_attempt ORDER BY id", ) .all(); ro.close(); @@ -296,6 +416,18 @@ const MSGS = [ { role: "user", content: "hello" }, ]; +const waitForAttempts = async (p, count) => { + let rows = []; + for (let i = 0; i < 20; i++) { + try { + rows = p.attempts(); + } catch {} + if (rows.length >= count) break; + await new Promise((r) => setTimeout(r, 100)); + } + return rows; +}; + test("invalid timeout exits at startup with a useful diagnostic", () => { for (const raw of ["0", "-1", "1.5", "1e3", "0x10", " 100", "2147483648", "3000000000", "abc", "nope"]) { const result = spawnSync(process.execPath, [path.join(binDir, "opencode-route-proxy.mjs")], { @@ -401,7 +533,7 @@ test("429 on the first leaf fails over; both attempts recorded", async () => { // leafB has no static key in config: it must be served by the // credential-store key, which the leaf verifies. assert.equal(p.leafB.last.headers.authorization, "Bearer key-b"); - const rows = p.attempts(); + const rows = await waitForAttempts(p, 2); assert.equal(rows.length, 2); assert.equal(rows[0].outcome, "failure"); assert.equal(rows[0].error_tag, "RateLimit"); @@ -511,7 +643,7 @@ test("variant remap reaches the leaf as reasoning_effort", async () => { }); assert.equal(res.status, 200); assert.equal(p.leafA.last.body.reasoning_effort, "high"); - const rows = p.attempts(); + const rows = await waitForAttempts(p, 1); assert.equal(rows[0].variant, "high"); } finally { await p.cleanup(); @@ -562,6 +694,179 @@ test("streaming relays SSE and records a success attempt", async () => { } }); +test("first-token timing includes delay past the pre-content window", async () => { + const p = await startProxy(); + try { + p.leafA.mode = "delayed-stream"; + const res = await p.post({ + model: "opencode-route/t-ordered", + messages: MSGS, + stream: true, + }); + assert.equal(res.status, 200); + assert.ok((await res.text()).includes("LEAF-A")); + const rows = await waitForAttempts(p, 1); + assert.equal(rows.length, 1); + assert.equal(rows[0].outcome, "success"); + assert.ok(rows[0].first_token_ms > 200, `first_token_ms=${rows[0].first_token_ms}`); + } finally { + await p.cleanup(); + } +}); + +test("pre-content SSE quota error fails over to the next stream", async () => { + const p = await startProxy(); + try { + p.leafA.mode = "sse-rate"; + const res = await p.post({ + model: "opencode-route/t-ordered", + messages: MSGS, + stream: true, + }); + assert.equal(res.status, 200); + const text = await res.text(); + assert.ok(text.includes("LEAF-B"), text); + assert.ok(!text.includes("quota exhausted"), text); + const rows = await waitForAttempts(p, 2); + assert.equal(rows.length, 2); + assert.equal(rows[0].outcome, "failure"); + assert.equal(rows[0].error_tag, "RateLimit"); + assert.equal(rows[0].error_status, 429); + assert.equal(rows[0].failed_over_to, "leafB/m-b"); + assert.equal(rows[0].output_started, 0); + assert.equal(JSON.parse(rows[0].quota).retryAfterMs, 30_000); + assert.equal(rows[1].outcome, "success"); + assert.equal(rows[1].provider_id, "leafB"); + assert.equal(rows[1].output_started, 1); + } finally { + await p.cleanup(); + } +}); + +test("pre-content SSE error after the buffer window still fails over cleanly", async () => { + const p = await startProxy(); + try { + p.leafA.mode = "delayed-sse-rate"; + const res = await p.post({ + model: "opencode-route/t-ordered", + messages: MSGS, + stream: true, + }); + assert.equal(res.status, 200); + const text = await res.text(); + assert.ok(text.includes("LEAF-B"), text); + assert.ok(!text.includes("quota exhausted"), text); + assert.ok(!text.includes("heartbeat"), text); + const rows = await waitForAttempts(p, 2); + assert.equal(rows.length, 2); + assert.equal(rows[0].outcome, "failure"); + assert.equal(rows[0].error_tag, "RateLimit"); + assert.equal(rows[0].failed_over_to, "leafB/m-b"); + assert.equal(rows[0].output_started, 0); + assert.equal(JSON.parse(rows[0].quota).retryAfterMs, 30_000); + assert.equal(rows[1].outcome, "success"); + } finally { + await p.cleanup(); + } +}); + +test("pre-content transport break fails over without committing the heartbeat", async () => { + const p = await startProxy(); + try { + p.leafA.mode = "stream-break"; + const res = await p.post({ + model: "opencode-route/t-ordered", + messages: MSGS, + stream: true, + }); + assert.equal(res.status, 200); + const text = await res.text(); + assert.ok(text.includes("LEAF-B"), text); + assert.ok(!text.includes("heartbeat"), text); + const rows = await waitForAttempts(p, 2); + assert.equal(rows.length, 2); + assert.equal(rows[0].outcome, "failure"); + assert.equal(rows[0].error_tag, "Transport"); + assert.equal(rows[0].failed_over_to, "leafB/m-b"); + assert.equal(rows[0].output_started, 0); + assert.equal(rows[1].outcome, "success"); + } finally { + await p.cleanup(); + } +}); + +test("stream errors after content do not fail over", async () => { + const p = await startProxy(); + try { + p.leafA.mode = "late-sse-rate"; + const res = await p.post({ + model: "opencode-route/t-ordered", + messages: MSGS, + stream: true, + }); + assert.equal(res.status, 200); + const text = await res.text(); + assert.ok(text.includes("LEAF-A"), text); + assert.ok(text.includes("late quota exhausted"), text); + assert.equal(p.leafB.hits, 0); + const rows = await waitForAttempts(p, 1); + assert.equal(rows.length, 1); + assert.equal(rows[0].outcome, "failure"); + assert.equal(rows[0].output_started, 1); + } finally { + await p.cleanup(); + } +}); + +test("a first content event larger than the preface window is relayed, not rejected (#5558)", async () => { + const p = await startProxy(); + try { + p.leafA.mode = "big-first-event"; + const res = await p.post({ + model: "opencode-route/t-ordered", + messages: MSGS, + stream: true, + }); + assert.equal(res.status, 200); + const text = await res.text(); + assert.ok(text.includes("A".repeat(1024)), "large first event must reach the client"); + assert.ok(text.includes("[DONE]")); + assert.equal(p.leafB.hits, 0); + const rows = await waitForAttempts(p, 1); + assert.equal(rows.length, 1); + assert.equal(rows[0].outcome, "success"); + assert.equal(rows[0].output_started, 1); + } finally { + await p.cleanup(); + } +}); + +test("pre-content preface overflow fails over and cancels the rejected stream (#5558)", async () => { + const p = await startProxy(); + try { + p.leafA.mode = "preface-flood"; + const res = await p.post({ + model: "opencode-route/t-ordered", + messages: MSGS, + stream: true, + }); + assert.equal(res.status, 200); + const text = await res.text(); + assert.ok(text.includes("LEAF-B"), text); + const rows = await waitForAttempts(p, 2); + assert.equal(rows.length, 2); + assert.equal(rows[0].outcome, "failure"); + assert.equal(rows[0].output_started, 0); + assert.equal(rows[1].outcome, "success"); + // The rejected leaf's stream was cancelled, not left generating. + for (let i = 0; i < 50 && !p.leafA.prefaceAborted; i++) + await new Promise((r) => setTimeout(r, 100)); + assert.equal(p.leafA.prefaceAborted, true); + } finally { + await p.cleanup(); + } +}); + test("unknown route and malformed bodies are rejected", async () => { const p = await startProxy(); try {