diff --git a/changelog.d/fixes/19713-keepalive-nonsse-body-deadline.md b/changelog.d/fixes/19713-keepalive-nonsse-body-deadline.md new file mode 100644 index 000000000000..dbd31e309f58 --- /dev/null +++ b/changelog.d/fixes/19713-keepalive-nonsse-body-deadline.md @@ -0,0 +1 @@ +- **fix(sse):** a chat stream that already sent its keepalive no longer hangs when the upstream sends a non-event-stream body that never ends. The slow-path deadline now covers that body read and cancels it. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/fixes/19713-sse-coalesce-terminate-flush.md b/changelog.d/fixes/19713-sse-coalesce-terminate-flush.md new file mode 100644 index 000000000000..749ad341e092 --- /dev/null +++ b/changelog.d/fixes/19713-sse-coalesce-terminate-flush.md @@ -0,0 +1 @@ +- **fix(sse):** with `SSE_FRAME_COALESCE_MS` on, a stream that ends on an upstream failure now still delivers the last queued content frame and the real error frame to the client. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/fixes/19713-stream-readiness-pre-signal-budget.md b/changelog.d/fixes/19713-stream-readiness-pre-signal-budget.md new file mode 100644 index 000000000000..c2ed45608a6f --- /dev/null +++ b/changelog.d/fixes/19713-stream-readiness-pre-signal-budget.md @@ -0,0 +1 @@ +- **fix(sse):** a streaming upstream that sends only comment lines or invalid data now fails readiness after 1 MiB, instead of filling gateway memory until the readiness deadline. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/fixes/19713-stream-watchdog-cleared-on-transform-error.md b/changelog.d/fixes/19713-stream-watchdog-cleared-on-transform-error.md new file mode 100644 index 000000000000..3062bf3ac3d8 --- /dev/null +++ b/changelog.d/fixes/19713-stream-watchdog-cleared-on-transform-error.md @@ -0,0 +1 @@ +- **fix(sse):** a translated stream that fails inside its transform no longer leaves its idle-timeout timer running until the idle timeout. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/maintenance/19713-stream-content-watcher-inert.md b/changelog.d/maintenance/19713-stream-content-watcher-inert.md new file mode 100644 index 000000000000..b16a69dc75fa --- /dev/null +++ b/changelog.d/maintenance/19713-stream-content-watcher-inert.md @@ -0,0 +1 @@ +- **perf(sse):** the client stream content check stops parsing frames once the first content is seen, which saves about 4 ms of CPU for a 2,000-event stream. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/maintenance/19713-token-estimate-single-pass.md b/changelog.d/maintenance/19713-token-estimate-single-pass.md new file mode 100644 index 000000000000..18f2eab86099 --- /dev/null +++ b/changelog.d/maintenance/19713-token-estimate-single-pass.md @@ -0,0 +1 @@ +- **perf(usage):** the fallback input-token estimate for responses without provider usage counts in one pass, so a 3 MiB request no longer allocates tens of MiB of temporary arrays. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/open-sse/utils/earlyStreamKeepalive.ts b/open-sse/utils/earlyStreamKeepalive.ts index a18c1955d6e0..ed664bca41c0 100644 --- a/open-sse/utils/earlyStreamKeepalive.ts +++ b/open-sse/utils/earlyStreamKeepalive.ts @@ -632,6 +632,7 @@ export async function withEarlyStreamKeepalive( aborted = true; stopDeadline(); stopKeepalive(); + upstreamReader?.cancel().catch(() => {}); try { deadlineController?.abort(); } catch { @@ -674,7 +675,7 @@ export async function withEarlyStreamKeepalive( try { const result = await settled; - stopDeadline(); + // The deadline stays armed here: a non-SSE body is read below and must be bound too. stopKeepalive(); if (aborted) { // The synthetic keepalive response can be cancelled before the handler resolves. @@ -695,7 +696,9 @@ export async function withEarlyStreamKeepalive( const isSse = contentType.includes("text/event-stream"); if (response.body && isSse) { - // Real SSE stream — forward it verbatim. + // Real SSE stream — forward it verbatim. The deadline guards only the + // handler wait and the non-SSE body read, never a long-lived stream. + stopDeadline(); upstreamReader = response.body.getReader(); let bytesForwarded = 0; // Last four forwarded bytes. A finished SSE event ends in \n\n (or \r\n\r\n). @@ -750,7 +753,24 @@ export async function withEarlyStreamKeepalive( // committed to a 200 event-stream, so the HTTP status can no longer // change. Frame the (already-sanitized) body as an in-band error event // instead of forwarding raw JSON, which would be malformed SSE. - const text = response.body ? await response.text().catch(() => "") : ""; + // Read through upstreamReader so the deadline, abort and cancel paths can + // cancel a body that trickles forever. + let text = ""; + if (response.body) { + upstreamReader = response.body.getReader(); + const decoder = new TextDecoder(); + try { + while (true) { + const { done, value } = await upstreamReader.read(); + if (done) break; + if (value) text += decoder.decode(value, { stream: true }); + } + text += decoder.decode(); + } catch { + text = ""; + } + } + if (aborted) return; const dataLine = errorFrameFormat === "responses" ? buildResponsesErrorDataLine(text, { diff --git a/open-sse/utils/sseOutputSink.ts b/open-sse/utils/sseOutputSink.ts index dfa8d28b3bf6..3714c2798bd4 100644 --- a/open-sse/utils/sseOutputSink.ts +++ b/open-sse/utils/sseOutputSink.ts @@ -163,10 +163,32 @@ export function createSSEOutputSink( const wrap = >(transformer: T): T => { if (!deltaStage && frameWindowMs <= 0) return transformer; + const originalTransform = transformer.transform; const originalFlush = transformer.flush; const originalCancel = (transformer as CancelableTransformer).cancel; + // A preserved stream failure ends the stream with `controller.terminate()` from inside + // `transform()`. `flush()` never runs after that, so drain the queued delta and the failure + // frame (they may be held in the batch) right before the readable side closes. + let drainingController: OutputController | null = null; + const withDrainOnTerminate = (controller: OutputController): OutputController => + (drainingController ??= { + get desiredSize() { + return controller.desiredSize; + }, + enqueue: (chunk) => controller.enqueue(chunk), + error: (reason) => controller.error(reason), + terminate: () => { + drain(controller); + dispose(); + controller.terminate(); + }, + }); return { ...transformer, + transform: originalTransform + ? (chunk: Uint8Array, controller: OutputController) => + originalTransform.call(transformer, chunk, withDrainOnTerminate(controller)) + : undefined, async flush(controller: OutputController) { try { await originalFlush?.call(transformer, controller); diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.ts index 9959cdfb0558..280626db5d56 100644 --- a/open-sse/utils/stream.ts +++ b/open-sse/utils/stream.ts @@ -74,7 +74,7 @@ import { projectStreamFailureEvent, type StreamFailurePayload, } from "./streamErrorFormat.ts"; -import { createStreamFailureAborter } from "./streamFailureBoundary.ts"; +import { createStreamFailureAborter, clearIdleTimerOnError } from "./streamFailureBoundary.ts"; import { buildStreamFailureSnapshot } from "./streamFailureSnapshot.ts"; import { nativeFinishFailure, readPassthroughChatId } from "./streamPassthroughFinish.ts"; import { createReasoningStreamObserver } from "./responsesReasoningObservation.ts"; @@ -1669,7 +1669,7 @@ export function createSSEStream(options: StreamOptions = {}) { } }, - transform(chunk, controller) { + transform: clearIdleTimerOnError(clearIdleTimer, (chunk, controller) => { if (streamTimedOut) return; const now = Date.now(); timing.markByte(); @@ -2951,7 +2951,7 @@ export function createSSEStream(options: StreamOptions = {}) { deferredCompletionTimer.unref?.(); } } - }, + }), async flush(controller) { flushing = true; diff --git a/open-sse/utils/streamFailureBoundary.ts b/open-sse/utils/streamFailureBoundary.ts index f864170a8f79..592b5b817ca6 100644 --- a/open-sse/utils/streamFailureBoundary.ts +++ b/open-sse/utils/streamFailureBoundary.ts @@ -91,3 +91,22 @@ export function createStreamFailureAborter(context: AborterContext) { } }; } + +/** + * An exception thrown while translating errors both stream sides without running flush() or + * cancel(): clear the idle watchdog here, or its interval keeps the failed stream alive until + * the idle timeout. + */ +export function clearIdleTimerOnError( + clearIdleTimer: () => void, + transform: (chunk: Uint8Array, controller: TransformStreamDefaultController) => void +) { + return (chunk: Uint8Array, controller: TransformStreamDefaultController): void => { + try { + transform(chunk, controller); + } catch (error) { + clearIdleTimer(); + throw error; + } + }; +} diff --git a/open-sse/utils/streamReadiness.ts b/open-sse/utils/streamReadiness.ts index 19855d94f57f..415657e5cfe6 100644 --- a/open-sse/utils/streamReadiness.ts +++ b/open-sse/utils/streamReadiness.ts @@ -499,7 +499,8 @@ export type StreamContentWatcher = { /** * True once a terminal frame declared a NORMAL stop (finish_reason "stop", * stop_reason "end_turn"/"stop_sequence") — the upstream's own verdict that - * the turn is complete, even when no content followed (#16072). + * the turn is complete, even when no content followed (#16072). Not updated once + * content is seen: the verdict only matters for a stream that carried no content. */ sawNormalStopTerminal: () => boolean; /** @@ -574,13 +575,20 @@ export function createStreamContentWatcher( return { note(text: string): void { - if (!text) return; + // Once content is proven every reader is satisfied (each tests `!sawContent()` or ORs + // it with the other flags), so later frames are not parsed or buffered and the + // other flags keep the value they had at that point. + if (!text || content) return; pending += text; for (;;) { const boundary = pending.search(/\r?\n\r?\n/); if (boundary === -1) break; inspect(pending.slice(0, boundary)); pending = pending.slice(boundary).replace(/^\r?\n\r?\n/, ""); + if (content) { + pending = ""; + return; + } } if (pending.length > MAX_BUFFERED) { inspect(pending); @@ -588,7 +596,7 @@ export function createStreamContentWatcher( } }, finish(): void { - inspect(pending); + if (!content) inspect(pending); pending = ""; }, sawContent: () => content, @@ -864,6 +872,11 @@ export function prependBufferedChunks( }); } +// Ceiling on bytes held before the first readiness signal. Comment-only or non-JSON bodies +// never signal readiness, so without it they grow with upstream rate x deadline. Kept far +// above one real first frame (a Responses `response.created` echoes instructions and tools). +const PRE_SIGNAL_MAX_BYTES = 1024 * 1024; + function isDeadlineAbortReason(reason: unknown): boolean { return ( reason instanceof Error && @@ -1291,6 +1304,31 @@ export async function ensureStreamReadiness( response: buildReadyResponse(), }; } + + if (bufferedBytes > PRE_SIGNAL_MAX_BYTES) { + const reason = `Stream sent ${bufferedBytes} bytes without a non-ping SSE event (limit=${PRE_SIGNAL_MAX_BYTES})`; + options.log?.warn?.( + "STREAM", + `${reason} (${options.provider || "provider"}/${options.model || "unknown"})` + ); + await reader.cancel(reason).catch(() => {}); + return { + ok: false, + reason, + classificationReason: reason, + code: "STREAM_READINESS_TIMEOUT", + type: "stream_timeout", + anyByteAt: lastChunkAt, + response: createErrorResponse( + HTTP_STATUS.GATEWAY_TIMEOUT, + reason, + "STREAM_READINESS_TIMEOUT", + "stream_timeout", + undefined, + buildAnyByteAtHeader(lastChunkAt) + ), + }; + } } } finally { if (!handedOffReader) { diff --git a/open-sse/utils/usageEstimation.ts b/open-sse/utils/usageEstimation.ts index 9a4ddccbfd4d..6dfdcb17e0b7 100644 --- a/open-sse/utils/usageEstimation.ts +++ b/open-sse/utils/usageEstimation.ts @@ -1,6 +1,46 @@ // Heuristic token estimation constants const CHARS_PER_TOKEN_SCHEMA = 6; // ~6 chars/token for JSON schemas (more verbose per token) +// Same set as the regex \s (and String.trim) in V8. +export function isSpaceCode(c: number) { + return ( + c === 32 || + (c >= 9 && c <= 13) || + c === 0xa0 || + c === 0x1680 || + (c >= 0x2000 && c <= 0x200a) || + c === 0x2028 || + c === 0x2029 || + c === 0x202f || + c === 0x205f || + c === 0x3000 || + c === 0xfeff + ); +} + +const CHAR_CJK = 0; +const CHAR_SPACE = 1; +const CHAR_LOWER = 2; +const CHAR_UPPER = 3; +const CHAR_WORD = 4; // digit or underscore +const CHAR_OTHER = 5; + +function charKind(c: number) { + if ((c >= 0x3000 && c <= 0x9fff) || (c >= 0xf900 && c <= 0xfaff)) return CHAR_CJK; + if (isSpaceCode(c)) return CHAR_SPACE; + if (c >= 97 && c <= 122) return CHAR_LOWER; + if (c >= 65 && c <= 90) return CHAR_UPPER; + if ((c >= 48 && c <= 57) || c === 95) return CHAR_WORD; + return CHAR_OTHER; +} + +// 1 when the high surrogate at `i` starts an astral CJK code point, else 0. +function astralCjkAt(text: string, i: number, c: number) { + if (c < 0xd800 || c > 0xdbff) return 0; + const cp = text.codePointAt(i)!; + return cp >= 0x20000 && cp <= 0x2fa1f ? 1 : 0; +} + /** * Improved token estimation heuristic (no dependency). * Splits text on common token boundaries (whitespace, punctuation, camelCase) @@ -15,23 +55,36 @@ const CHARS_PER_TOKEN_SCHEMA = 6; // ~6 chars/token for JSON schemas (more verbo function estimateTokenCount(text: unknown) { if (!text || typeof text !== "string") return 0; - // Count CJK ideographs separately — each is roughly 1 token - const cjkMatches = text.match(/[\u3000-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}]/gu); - const cjkCount = cjkMatches ? cjkMatches.length : 0; - - // Remove CJK chars for the remaining estimation - const nonCJK = text.replace(/[\u3000-\u9fff\uf900-\ufaff]/g, " "); - - // Split on token boundaries: whitespace, punctuation, camelCase transitions - const tokens = nonCJK - .split(/(\s+|[^\w\s]|(?<=[a-z])(?=[A-Z]))/) - .filter((t) => t && t.trim().length > 0); + // One pass, no split/filter arrays (a 3 MiB body used to leave ~45 MiB of garbage). + // Token boundaries: a run of [A-Za-z0-9_] (cut at each lower->UPPER step), or any other + // non-space UTF-16 unit on its own. A BMP CJK unit counts 1 and acts as a space; an astral + // CJK code point counts 1 and its two surrogate units still count as punctuation tokens. + let cjkCount = 0; + let tokens = 0; + let inWord = false; + let prevLower = false; + for (let i = 0; i < text.length; i++) { + const c = text.charCodeAt(i); + const kind = charKind(c); + if (kind === CHAR_CJK) { + cjkCount++; + inWord = false; + } else if (kind === CHAR_SPACE) { + inWord = false; + } else if (kind === CHAR_OTHER) { + cjkCount += astralCjkAt(text, i, c); + tokens++; + inWord = false; + } else { + if (!inWord || (prevLower && kind === CHAR_UPPER)) tokens++; + inWord = true; + } + prevLower = kind === CHAR_LOWER; + } // Apply sub-word correction: BPE tokenizers often split long words // into sub-word pieces, so raw token count underestimates slightly - const estimatedNonCJK = Math.ceil(tokens.length * 1.3); - - return cjkCount + estimatedNonCJK; + return cjkCount + Math.ceil(tokens * 1.3); } /** diff --git a/tests/unit/early-stream-keepalive-nonsse-body-deadline.test.ts b/tests/unit/early-stream-keepalive-nonsse-body-deadline.test.ts new file mode 100644 index 000000000000..774a265ac055 --- /dev/null +++ b/tests/unit/early-stream-keepalive-nonsse-body-deadline.test.ts @@ -0,0 +1,112 @@ +/** + * @file early-stream-keepalive-nonsse-body-deadline.test.ts + * @description The slow-path deadline must keep running while a non-SSE handler body is read, + * and the in-flight body read must be cancelled when the deadline fires. + */ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { + OPENAI_CHAT_ERROR_FRAME, + withDeadlineSignal, + withEarlyStreamKeepalive, +} from "../../open-sse/utils/earlyStreamKeepalive.ts"; + +async function readAll(response: Response): Promise { + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + let out = ""; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value) out += decoder.decode(value, { stream: true }); + } + return out; +} + +function newDeadlineController() { + return withDeadlineSignal( + new Request("http://localhost/v1/chat/completions", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ model: "m", stream: true }), + }) + ).deadlineController; +} + +test("a text/plain body that trickles forever hits the slow-path deadline and is cancelled", async () => { + const deadlineController = newDeadlineController(); + const encoder = new TextEncoder(); + let sourceCancelled = false; + let trickle: ReturnType | undefined; + const trickling = new ReadableStream({ + start(controller) { + trickle = setInterval(() => controller.enqueue(encoder.encode("x")), 10); + }, + cancel() { + sourceCancelled = true; + clearInterval(trickle); + }, + }); + const handler = new Promise((resolve) => { + setTimeout( + () => + resolve( + new Response(trickling, { status: 200, headers: { "Content-Type": "text/plain" } }) + ), + 30 + ); + }); + + try { + const result = await withEarlyStreamKeepalive(handler, { + thresholdMs: 10, + intervalMs: 250, + slowPathDeadlineMs: 200, + deadlineController, + errorFrame: OPENAI_CHAT_ERROR_FRAME, + }); + const outcome = await Promise.race([ + readAll(result).then((body) => ({ body })), + new Promise<{ body: null }>((resolve) => setTimeout(() => resolve({ body: null }), 1500)), + ]); + + assert.notEqual(outcome.body, null, "client stream must end once the deadline expires"); + assert.match(outcome.body!, /"error":/, "deadline must emit the route error frame"); + assert.equal(deadlineController.signal.aborted, true, "deadline must abort the controller"); + assert.equal(sourceCancelled, true, "the in-flight body read must be cancelled"); + } finally { + clearInterval(trickle); + } +}); + +test("a non-SSE error body that finishes in time is still framed as one error event", async () => { + const deadlineController = newDeadlineController(); + const handler = new Promise((resolve) => { + setTimeout( + () => + resolve( + new Response( + JSON.stringify({ error: { message: "upstream_busy", type: "rate_limit" } }), + { + status: 429, + headers: { "Content-Type": "application/json" }, + } + ) + ), + 30 + ); + }); + + const result = await withEarlyStreamKeepalive(handler, { + thresholdMs: 10, + intervalMs: 250, + slowPathDeadlineMs: 5000, + deadlineController, + errorFrame: OPENAI_CHAT_ERROR_FRAME, + }); + const body = await readAll(result); + + assert.match(body, /data: \{"error":\{"message":"upstream_busy","type":"rate_limit"\}\}\n\n/); + assert.equal(deadlineController.signal.aborted, false, "no abort when the body ends in time"); +}); diff --git a/tests/unit/sse-output-coalescing-terminate-flush.test.ts b/tests/unit/sse-output-coalescing-terminate-flush.test.ts new file mode 100644 index 000000000000..80de0ba45208 --- /dev/null +++ b/tests/unit/sse-output-coalescing-terminate-flush.test.ts @@ -0,0 +1,94 @@ +/** + * Opt-in SSE frame batching (SSE_FRAME_COALESCE_MS) must not eat the tail of a failed stream: + * when a preserved upstream failure terminates the transform, flush() never runs, so the + * sink has to drain the queued delta and the failure frame itself. + */ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-sse-coalesce-terminate-")); +process.env.DATA_DIR = TEST_DATA_DIR; +const core = await import("../../src/lib/db/core.ts"); + +const { createSSEStream } = await import("../../open-sse/utils/stream.ts"); +const { FORMATS } = await import("../../open-sse/translator/formats.ts"); + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +const chunk = (delta: Record) => + `data: ${JSON.stringify({ + id: "chatcmpl-abcdefgh1", + object: "chat.completion.chunk", + created: 1, + model: "m", + choices: [{ index: 0, delta, finish_reason: null }], + })}\n\n`; +// A bare OpenAI error envelope: no `event: error` line, no `"type":"error"` marker. +const BARE_ERROR = `data: ${JSON.stringify({ + error: { message: "upstream exploded", type: "server_error", code: "500" }, +})}\n\n`; + +async function run(frameCoalesceMs: string | undefined) { + const saved = process.env.SSE_FRAME_COALESCE_MS; + if (frameCoalesceMs === undefined) delete process.env.SSE_FRAME_COALESCE_MS; + else process.env.SSE_FRAME_COALESCE_MS = frameCoalesceMs; + try { + const stream = createSSEStream({ + mode: "passthrough", + provider: "openai", + model: "m", + clientResponseFormat: FORMATS.OPENAI, + body: { messages: [{ role: "user", content: "hi" }] }, + }); + const frames = [ + chunk({ role: "assistant", content: "A" }), + chunk({ content: "B" }), + BARE_ERROR, + ]; + const source = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(frames.join(""))); + controller.close(); + }, + }); + const reader = source.pipeThrough(stream).getReader(); + let out = ""; + let error: unknown = null; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + out += decoder.decode(value); + } + } catch (err) { + error = err; + } + return { out, error }; + } finally { + if (saved === undefined) delete process.env.SSE_FRAME_COALESCE_MS; + else process.env.SSE_FRAME_COALESCE_MS = saved; + } +} + +test.after(() => { + core.resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); +}); + +test("unbatched stream delivers the queued delta and the upstream failure frame", async () => { + const { out } = await run(undefined); + assert.ok(out.includes('"content":"B"'), "queued delta B reaches the client"); + assert.ok(out.includes("upstream exploded"), "upstream failure frame reaches the client"); +}); + +test("batched stream delivers the queued delta and the upstream failure frame on terminate", async () => { + const plain = await run(undefined); + const batched = await run("200"); + assert.ok(batched.out.includes('"content":"B"'), "queued delta B survives the terminate"); + assert.ok(batched.out.includes("upstream exploded"), "upstream failure frame survives"); + assert.equal(batched.out, plain.out, "batching changes enqueue grouping, not bytes"); +}); diff --git a/tests/unit/stream-content-watcher-inert-after-content.test.ts b/tests/unit/stream-content-watcher-inert-after-content.test.ts new file mode 100644 index 000000000000..33f6b869bce9 --- /dev/null +++ b/tests/unit/stream-content-watcher-inert-after-content.test.ts @@ -0,0 +1,83 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "or9r-content-watcher-")); + +const { createStreamContentWatcher } = await import("../../open-sse/utils/streamReadiness.ts"); + +const contentFrame = (text: string) => + `data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\n`; + +// Count JSON.parse calls made while `run` executes (the watcher parses every data line). +function countParses(run: () => void): number { + const original = JSON.parse; + let calls = 0; + JSON.parse = ((...args: Parameters) => { + calls += 1; + return original(...args); + }) as typeof JSON.parse; + try { + run(); + } finally { + JSON.parse = original; + } + return calls; +} + +test("content watcher stops parsing frames once content is proven", () => { + const watcher = createStreamContentWatcher(); + watcher.note(contentFrame("first")); + assert.equal(watcher.sawContent(), true); + + const parses = countParses(() => { + for (let i = 0; i < 500; i += 1) watcher.note(contentFrame(`token ${i}`)); + watcher.finish(); + }); + + assert.equal(parses, 0, "no frame is parsed after content is seen"); + assert.equal(watcher.sawContent(), true); +}); + +test("content watcher keeps scanning every frame while content is absent", () => { + const watcher = createStreamContentWatcher(); + const parses = countParses(() => { + for (let i = 0; i < 50; i += 1) watcher.note(`data: ${JSON.stringify({ choices: [] })}\n\n`); + }); + assert.ok(parses >= 50, `every frame is parsed while content is absent, got ${parses}`); + assert.equal(watcher.sawContent(), false); + assert.equal(watcher.sawSseFrame(), true); +}); + +test("pre-content flags still work: error frame, legit empty terminal, reasoning progress", () => { + const errored = createStreamContentWatcher(); + errored.note('data: {"type":"error","error":{"type":"overloaded_error","message":"busy"}}\n\n'); + assert.equal(errored.sawError(), true); + assert.equal(errored.sawContent(), false); + + const empty = createStreamContentWatcher(); + empty.note('data: {"choices":[{"delta":{},"finish_reason":"length"}]}\n\n'); + assert.equal(empty.sawLegitEmptyTerminal(), true); + assert.equal(empty.sawContent(), false); + + const thinking = createStreamContentWatcher(); + thinking.note( + 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":""}}\n\n' + ); + thinking.note( + 'event: content_block_delta\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}\n\n' + ); + assert.equal(thinking.sawContent(), false); + assert.equal(thinking.reasoningProgress(), 2); +}); + +test("a content frame split across chunks is still detected", () => { + const watcher = createStreamContentWatcher(); + const frame = contentFrame("split"); + watcher.note(frame.slice(0, 12)); + assert.equal(watcher.sawContent(), false); + watcher.note(frame.slice(12)); + assert.equal(watcher.sawContent(), true); +}); diff --git a/tests/unit/stream-readiness-pre-signal-byte-budget.test.ts b/tests/unit/stream-readiness-pre-signal-byte-budget.test.ts new file mode 100644 index 000000000000..00d491c8782f --- /dev/null +++ b/tests/unit/stream-readiness-pre-signal-byte-budget.test.ts @@ -0,0 +1,98 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "or9r-readiness-budget-")); + +const { ensureStreamReadiness } = await import("../../open-sse/utils/streamReadiness.ts"); + +const encoder = new TextEncoder(); +const CHUNK_BYTES = 16 * 1024; +const READY_FRAME = 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\n'; + +// Pull-driven source: `junk` chunks first, then one real frame, then close. +function junkThenReady(junk: () => string, junkChunks: number) { + const state = { pulled: 0, cancelled: false }; + const body = new ReadableStream({ + pull(controller) { + state.pulled += 1; + if (state.pulled <= junkChunks) controller.enqueue(encoder.encode(junk())); + else if (state.pulled === junkChunks + 1) controller.enqueue(encoder.encode(READY_FRAME)); + else controller.close(); + }, + cancel() { + state.cancelled = true; + }, + }); + return { + state, + response: new Response(body, { headers: { "Content-Type": "text/event-stream" } }), + }; +} + +const commentChunk = () => `:${"x".repeat(CHUNK_BYTES)}\n\n`; +const invalidDataChunk = () => `data: ${"y".repeat(CHUNK_BYTES)}\n\n`; + +for (const [name, junk] of [ + ["comment-only", commentChunk], + ["invalid-data", invalidDataChunk], +] as const) { + test(`${name} body is rejected once the pre-signal byte budget is spent`, async () => { + const { state, response } = junkThenReady(junk, 200); + const result = await ensureStreamReadiness(response, { timeoutMs: 5000 }); + + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.code, "STREAM_READINESS_TIMEOUT"); + assert.equal(result.response.status, 504); + assert.equal(typeof result.anyByteAt, "number"); + assert.equal(state.cancelled, true, "upstream reader is cancelled"); + assert.ok(state.pulled < 100, `stopped reading early, pulled ${state.pulled} chunks`); + }); +} + +test("a few heartbeat comments before the first real frame still pass", async () => { + const { response } = junkThenReady(commentChunk, 5); + const result = await ensureStreamReadiness(response, { timeoutMs: 5000 }); + assert.equal(result.ok, true); +}); + +// A Responses `response.created` frame echoes instructions and tools, so a real first +// frame can pass 64 KiB. The budget must stay well above that. +test("one large first frame split over many chunks still passes", async () => { + const big = `data: {"choices":[{"delta":{"content":"${"z".repeat(100 * 1024)}"}}]}\n\n`; + const parts: string[] = []; + for (let i = 0; i < big.length; i += CHUNK_BYTES) parts.push(big.slice(i, i + CHUNK_BYTES)); + const body = new ReadableStream({ + pull(controller) { + const next = parts.shift(); + if (next === undefined) controller.close(); + else controller.enqueue(encoder.encode(next)); + }, + }); + const result = await ensureStreamReadiness(new Response(body), { timeoutMs: 5000 }); + assert.equal(result.ok, true); +}); + +test("a single unterminated line cannot grow without bound before the first signal", async () => { + const state = { pulled: 0, cancelled: false }; + const body = new ReadableStream({ + pull(controller) { + state.pulled += 1; + if (state.pulled <= 300) controller.enqueue(encoder.encode("y".repeat(CHUNK_BYTES))); + else if (state.pulled === 301) controller.enqueue(encoder.encode(`\n\n${READY_FRAME}`)); + else controller.close(); + }, + cancel() { + state.cancelled = true; + }, + }); + const result = await ensureStreamReadiness(new Response(body), { timeoutMs: 5000 }); + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.code, "STREAM_READINESS_TIMEOUT"); + assert.equal(state.cancelled, true); + assert.ok(state.pulled < 100, `stopped reading early, pulled ${state.pulled} chunks`); +}); diff --git a/tests/unit/stream-watchdog-cleared-on-transform-error.test.ts b/tests/unit/stream-watchdog-cleared-on-transform-error.test.ts new file mode 100644 index 000000000000..b3de86e326a5 --- /dev/null +++ b/tests/unit/stream-watchdog-cleared-on-transform-error.test.ts @@ -0,0 +1,99 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-watchdog-")); +process.env.DATA_DIR = TEST_DATA_DIR; +const core = await import("../../src/lib/db/core.ts"); +const { createSSEStream } = await import("../../open-sse/utils/stream.ts"); +const { FORMATS } = await import("../../open-sse/translator/formats.ts"); + +const textEncoder = new TextEncoder(); + +type Handle = ReturnType; + +const frame = (choice: Record) => + `data: ${JSON.stringify({ + id: "c1", + object: "chat.completion.chunk", + model: "m", + choices: [{ index: 0, ...choice }], + })}\n\n`; + +/** Run `fn` while counting the setInterval handles it leaves live. */ +async function withIntervalCount(fn: (liveCount: () => number) => Promise): Promise { + const realSet = globalThis.setInterval; + const realClear = globalThis.clearInterval; + const live = new Set(); + globalThis.setInterval = ((...args: Parameters) => { + const handle = realSet(...args); + live.add(handle); + return handle; + }) as typeof setInterval; + globalThis.clearInterval = ((handle: Handle) => { + live.delete(handle); + return realClear(handle); + }) as typeof clearInterval; + try { + return await fn(() => live.size); + } finally { + for (const handle of live) realClear(handle); + globalThis.setInterval = realSet; + globalThis.clearInterval = realClear; + } +} + +function translateStream() { + return createSSEStream({ + mode: "translate", + targetFormat: FORMATS.OPENAI, + sourceFormat: FORMATS.CLAUDE, + provider: "test", + model: "m", + body: { messages: [{ role: "user", content: "hi" }] }, + } as never); +} + +test.after(() => { + core.resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); +}); + +test("a transform that throws leaves no live idle watchdog interval", async () => { + await withIntervalCount(async (liveCount) => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue( + textEncoder.encode(frame({ delta: { role: "assistant", content: "hi" } })) + ); + // A malformed frame makes the translator throw inside transform(). + controller.enqueue(textEncoder.encode(frame({ delta: { tool_calls: [null] } }))); + controller.close(); + }, + }); + await assert.rejects(new Response(source.pipeThrough(translateStream())).text()); + assert.equal(liveCount(), 0, "the idle watchdog must be cleared once the stream failed"); + }); +}); + +test("a stream that is still running keeps its idle watchdog armed", async () => { + await withIntervalCount(async (liveCount) => { + let finish: () => void = () => {}; + const source = new ReadableStream({ + start(controller) { + controller.enqueue( + textEncoder.encode(frame({ delta: { role: "assistant", content: "hi" } })) + ); + finish = () => controller.close(); + }, + }); + const reader = source.pipeThrough(translateStream()).getReader(); + await reader.read(); + assert.equal(liveCount(), 1, "a live stream needs its watchdog"); + finish(); + while (!(await reader.read()).done); + assert.equal(liveCount(), 0, "a completed stream clears it"); + }); +}); diff --git a/tests/unit/usage-tracking-token-estimate-single-pass.test.ts b/tests/unit/usage-tracking-token-estimate-single-pass.test.ts new file mode 100644 index 000000000000..063edef70969 --- /dev/null +++ b/tests/unit/usage-tracking-token-estimate-single-pass.test.ts @@ -0,0 +1,125 @@ +// The fallback input-token estimate runs when a provider sends no usage. It used to split the +// whole serialized request into arrays just to read `.length`. It must now count in one pass, +// with exactly the same numbers as before (CJK, astral CJK, camelCase, punctuation, whitespace). +import test from "node:test"; +import assert from "node:assert/strict"; + +const { estimateInputTokens } = await import("../../open-sse/utils/usageTracking.ts"); + +// Frozen copy of the previous split/filter implementation: the parity oracle. +function referenceEstimate(text: unknown) { + if (!text || typeof text !== "string") return 0; + const cjkMatches = text.match(/[\u3000-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}]/gu); + const cjkCount = cjkMatches ? cjkMatches.length : 0; + const nonCJK = text.replace(/[\u3000-\u9fff\uf900-\ufaff]/g, " "); + const tokens = nonCJK + .split(/(\s+|[^\w\s]|(?<=[a-z])(?=[A-Z]))/) + .filter((t) => t && t.trim().length > 0); + return cjkCount + Math.ceil(tokens.length * 1.3); +} + +const FIXTURES = [ + "", + "hello world", + "camelCaseIdentifier and snake_case_name", + "XMLHttpRequest parseJSON getHTTPResponse", + "a,b;c.d!e?f (g) [h] {i} \"j\" 'k'", + "tabs\tand\nnewlines\r\nand\u00a0nbsp\u2003em\u2028ls\ufeffbom", + "你好,世界。こんにちは 안녕하세요 한글", + "mixed你好World好camelCase世界", + "astral \u{20000}\u{2a6d6}\u{2fa1f} cjk and emoji \u{1f600}\u{1f4a9} end", + "accents café naïve Ünïcödé", + "lone \ud800 high and \udc00 low surrogates", + "\u3000ideographic\u3000space\u3000", + "ABC DEF aBC abC a1B2 _Under_Score", +]; + +function* randomTexts(count: number) { + const alphabet = [ + ..."abcxyzABCXYZ019_", + ..." \t\n,.;:!?()[]{}\"'\\/-+=<>@#$%^&*|~`", + ..."\u3000\u4e00\u9fff\uf900\ufaff\u00e9\u00a0\u2003\ufeff", + "\u{20000}", + "\u{2fa1f}", + "\u{1f600}", + "\ud800", + "\udc00", + ]; + let seed = 123456789; + const next = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff); + for (let i = 0; i < count; i++) { + const length = next() % 60; + let out = ""; + for (let j = 0; j < length; j++) out += alphabet[next() % alphabet.length]; + yield out; + } +} + +// The body is serialized first, so the oracle runs on the same JSON text as production. +function expected(body: Record) { + return referenceEstimate(JSON.stringify(body)); +} + +test("estimateInputTokens keeps the exact previous numbers on fixtures", () => { + for (const text of FIXTURES) { + assert.equal(estimateInputTokens({ a: text }), expected({ a: text }), JSON.stringify(text)); + } + assert.equal(estimateInputTokens(undefined), 0); + assert.equal(estimateInputTokens("text"), 0); +}); + +test("estimateInputTokens keeps the exact previous numbers for every UTF-16 code unit", () => { + for (let code = 0; code <= 0xffff; code++) { + const text = `aB${String.fromCharCode(code)}cD${String.fromCharCode(code)}`; + assert.equal(estimateInputTokens({ a: text }), expected({ a: text }), `U+${code.toString(16)}`); + } +}); + +test("estimateInputTokens keeps the exact previous numbers on 3000 random texts", () => { + for (const text of randomTexts(3000)) { + assert.equal(estimateInputTokens({ a: text }), expected({ a: text }), JSON.stringify(text)); + } +}); + +test("estimateInputTokens counts without split or filter arrays", () => { + const body = { + model: "m", + messages: [{ role: "user", content: "parse the HTTPResponse now, 你好 world ".repeat(2000) }], + tools: [{ type: "function", function: { name: "getThing", parameters: { type: "object" } } }], + }; + const { tools, ...withoutTools } = body; + const want = expected(withoutTools) + Math.ceil(JSON.stringify(tools).length / 6); + + const origSplit = String.prototype.split; + const origFilter = Array.prototype.filter; + let splitCalls = 0; + let filterCalls = 0; + String.prototype.split = function (this: string, ...args: unknown[]) { + splitCalls++; + return Reflect.apply(origSplit, this, args); + } as typeof String.prototype.split; + Array.prototype.filter = function (this: unknown[], ...args: unknown[]) { + filterCalls++; + return Reflect.apply(origFilter, this, args); + } as typeof Array.prototype.filter; + let actual: number; + try { + actual = estimateInputTokens(body); + } finally { + String.prototype.split = origSplit; + Array.prototype.filter = origFilter; + } + + assert.equal(actual, want); + assert.equal(splitCalls, 0, "no String.split on the request text"); + assert.equal(filterCalls, 0, "no Array.filter over a token array"); +}); + +test("isSpaceCode matches /\\s/ on every UTF-16 code unit", async () => { + const { isSpaceCode } = await import("../../open-sse/utils/usageEstimation.ts"); + const wrong: string[] = []; + for (let c = 0; c <= 0xffff; c++) { + if (isSpaceCode(c) !== /\s/.test(String.fromCharCode(c))) wrong.push(c.toString(16)); + } + assert.deepEqual(wrong, []); +});