From 3fc3eeb5e88ae86ea3b7c0a48d7fb428e2736f43 Mon Sep 17 00:00:00 2001 From: Sachin Sharma Date: Thu, 26 Nov 2026 16:09:54 +0530 Subject: [PATCH] fix(litellm): add an absolute per-step ceiling to the SSE generate wire On the SSE wire generate() re-arms the per-step timeout on every raw chunk, so a stream that keeps sending keep-alive frames was never bounded per model call; only the whole-turn turnTimeoutMs stopped it. Keep the idle re-arm and add a never-reset ceiling of 3x the per-step timeout, so one step can no longer outlive it. --- .github/workflows/ci.yml | 1 + docs/api/type-aliases/GenerateOptions.md | 6 + package.json | 1 + .../providers/openaiChatCompletionsBase.ts | 29 ++- src/lib/types/generate.ts | 6 + src/lib/utils/timeout.ts | 23 +++ ...tinuous-test-suite-litellm-sse-step-cap.ts | 178 ++++++++++++++++++ 7 files changed, 240 insertions(+), 4 deletions(-) create mode 100644 test/continuous-test-suite-litellm-sse-step-cap.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7ea01fb21..aabd1c7b8b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1302,6 +1302,7 @@ jobs: test:decide-catalog-schema@20 test:provider-descriptors@17 test:openai-compat-streaming-retry@16 + test:litellm-sse-step-cap@10 test:servers@16 test:agent-input-guard@17 test:proxy-image-input@40 diff --git a/docs/api/type-aliases/GenerateOptions.md b/docs/api/type-aliases/GenerateOptions.md index efca165d53..ef9eff3b36 100644 --- a/docs/api/type-aliases/GenerateOptions.md +++ b/docs/api/type-aliases/GenerateOptions.md @@ -651,6 +651,12 @@ value bounds each model call and `turnTimeoutMs` bounds the turn. With `turnTimeoutMs` unset, this value bounds the WHOLE turn there (the pre-existing defensive behavior, kept for backward compatibility). +On the SSE wire that `generate()` uses for LiteLLM, this value is an IDLE +window (every received byte re-arms it, so a slow-but-alive completion +survives proxy idle limits) and each model call additionally has an +absolute wall-clock ceiling of 3x this value, so a stream that keeps +sending keep-alive frames can no longer run until `turnTimeoutMs`. + When set explicitly, a step timeout is surfaced immediately instead of burning internal retries/fallbacks that would re-run the same provider+model with the same doomed budget. diff --git a/package.json b/package.json index 5fe2045593..a285786a3b 100644 --- a/package.json +++ b/package.json @@ -108,6 +108,7 @@ "test:multimodal-text-content-fold": "pnpm exec tsx test/continuous-test-suite-multimodal-text-content-fold.ts", "test:proxy-sharing": "pnpm run build && pnpm exec tsx test/continuous-test-suite-proxy-sharing.ts", "test:openai-compat-streaming-retry": "pnpm exec tsx test/continuous-test-suite-openai-compat-streaming-retry.ts", + "test:litellm-sse-step-cap": "pnpm exec tsx test/continuous-test-suite-litellm-sse-step-cap.ts", "test:openai-compat-stream-truncation": "pnpm exec tsx test/continuous-test-suite-openai-compat-stream-truncation.ts", "test:openai-compat-stream-cancel": "pnpm exec tsx test/continuous-test-suite-openai-compat-stream-cancel.ts", "test:anthropic-streaming-retry": "pnpm exec tsx test/continuous-test-suite-anthropic-streaming-retry.ts", diff --git a/src/lib/providers/openaiChatCompletionsBase.ts b/src/lib/providers/openaiChatCompletionsBase.ts index 8c12a83df0..1e242f85f6 100644 --- a/src/lib/providers/openaiChatCompletionsBase.ts +++ b/src/lib/providers/openaiChatCompletionsBase.ts @@ -89,6 +89,7 @@ import { import { composeAbortSignalsScoped, createTimeoutController, + getStepHardCapTimeout, getStreamLifetimeTimeout, mergeAbortSignals, monitorStreamActivity, @@ -910,13 +911,26 @@ export abstract class OpenAIChatCompletionsProvider extends BaseProvider { | { neurolink?: { timeoutMs?: number } } | undefined )?.neurolink?.timeoutMs; - const timeoutController = createTimeoutController( + const stepTimeout = typeof nlStepTimeoutMs === "number" ? nlStepTimeoutMs - : getTimeoutForOptions(options), + : getTimeoutForOptions(options); + const timeoutController = createTimeoutController( + stepTimeout, providerName, "generate", ); + // On the SSE wire the controller above is an IDLE timer (every chunk + // re-arms it), so it cannot bound a stream that keeps sending bytes. + // This second, never-reset controller is the step's absolute + // wall-clock ceiling. + const stepCapController = sseWire + ? createTimeoutController( + getStepHardCapTimeout(stepTimeout), + providerName, + "generate", + ) + : null; // Scoped composition: a plain AbortSignal.any per step accumulates // registrations on the long-lived generate-call signal for the whole // turn (MaxListenersExceededWarning at 10+ steps); dispose() detaches @@ -924,7 +938,12 @@ export abstract class OpenAIChatCompletionsProvider extends BaseProvider { const { signal: composedSignal, dispose: disposeComposedSignal } = composeAbortSignalsScoped( options.abortSignal, - timeoutController?.controller.signal, + stepCapController + ? mergeAbortSignals([ + timeoutController?.controller.signal, + stepCapController.controller.signal, + ]).signal + : timeoutController?.controller.signal, ); let json: OpenAICompatChatResponse; // Whether the response we end up consuming is SSE. Starts as the @@ -1018,7 +1037,8 @@ export abstract class OpenAIChatCompletionsProvider extends BaseProvider { // Idle-timeout semantics: every raw chunk re-arms the timeout, // so the configured window bounds silence, not total duration — // the whole point of the SSE wire is that a slow-but-alive - // completion keeps the connection (and the timer) fed. + // completion keeps the connection (and the timer) fed. Total + // duration is bounded separately by `stepCapController`. const monitored = timeoutController ? monitorStreamActivity(res.body, timeoutController.reset) : res.body; @@ -1060,6 +1080,7 @@ export abstract class OpenAIChatCompletionsProvider extends BaseProvider { } } finally { timeoutController?.cleanup(); + stepCapController?.cleanup(); disposeComposedSignal(); } const choice = json.choices?.[0]; diff --git a/src/lib/types/generate.ts b/src/lib/types/generate.ts index 752d26799b..51f7e799ab 100644 --- a/src/lib/types/generate.ts +++ b/src/lib/types/generate.ts @@ -486,6 +486,12 @@ export type GenerateOptions = { * `turnTimeoutMs` unset, this value bounds the WHOLE turn there (the * pre-existing defensive behavior, kept for backward compatibility). * + * On the SSE wire that `generate()` uses for LiteLLM, this value is an IDLE + * window (every received byte re-arms it, so a slow-but-alive completion + * survives proxy idle limits) and each model call additionally has an + * absolute wall-clock ceiling of 3x this value, so a stream that keeps + * sending keep-alive frames can no longer run until `turnTimeoutMs`. + * * When set explicitly, a step timeout is surfaced immediately instead of * burning internal retries/fallbacks that would re-run the same * provider+model with the same doomed budget. diff --git a/src/lib/utils/timeout.ts b/src/lib/utils/timeout.ts index ffc4f3f3ea..2892b15efe 100644 --- a/src/lib/utils/timeout.ts +++ b/src/lib/utils/timeout.ts @@ -525,6 +525,29 @@ export function createTimeoutController( return { controller, cleanup, reset, timeoutMs }; } +/** + * How many times the per-step idle window a single streamed model call may + * last in total. The idle window re-arms on every received byte, so on its + * own a stream that keeps delivering keep-alive frames (or a model emitting + * one token a minute) is never bounded per call; this multiple is the + * absolute wall-clock ceiling that closes that gap. + */ +export const STEP_HARD_CAP_MULTIPLIER = 3; + +/** + * Absolute wall-clock ceiling (ms) for ONE streamed model call, derived from + * its idle window: `STEP_HARD_CAP_MULTIPLIER` x the window. A slow-but-alive + * completion still gets several idle windows of room, but can never outlive + * the cap, so the whole-turn deadline is no longer the only thing that stops + * a runaway step. + */ +export function getStepHardCapTimeout( + idleTimeout: number | string | undefined, +): number | undefined { + const idleMs = parseTimeout(idleTimeout); + return idleMs ? idleMs * STEP_HARD_CAP_MULTIPLIER : undefined; +} + /** Keep a stream's idle deadline alive for every received wire chunk. */ export function monitorStreamActivity( body: ReadableStream, diff --git a/test/continuous-test-suite-litellm-sse-step-cap.ts b/test/continuous-test-suite-litellm-sse-step-cap.ts new file mode 100644 index 0000000000..bedefe5429 --- /dev/null +++ b/test/continuous-test-suite-litellm-sse-step-cap.ts @@ -0,0 +1,178 @@ +#!/usr/bin/env tsx +import "dotenv/config"; + +/** + * Continuous Test Suite — LiteLLM generate() on the SSE wire: per-step + * idle window plus absolute wall-clock ceiling. + * + * generate() rides the SSE wire for LiteLLM, and every raw chunk re-arms the + * per-step timeout (idle semantics, so a slow-but-alive completion survives + * proxy idle limits). Before the ceiling existed a stream that kept sending + * keep-alive frames was bounded by nothing but the whole-turn deadline: one + * model call ran the full turn even though the caller asked for a much + * shorter per-call `timeout`. + * + * ALL-DIST module graph (rule 15): everything is driven through + * `new NeuroLink().generate()` imported from `../dist/index.js` against a + * local HTTP server. No API keys. + * + * Run: npx tsx test/continuous-test-suite-litellm-sse-step-cap.ts + * pnpm run test:litellm-sse-step-cap + */ + +import { createServer, type ServerResponse } from "node:http"; +import { defineSuite, assert } from "./helpers/harness.js"; +import "./helpers/requireFreshDist.js"; + +const { test, runSuite, section } = defineSuite("LiteLLM SSE step ceiling", { + offline: true, +}); + +const TOUCHED_ENV_VARS = ["LITELLM_BASE_URL", "LITELLM_API_KEY"] as const; + +const contentChunk = (text: string): string => + `data: ${JSON.stringify({ + choices: [{ delta: { content: text }, finish_reason: null }], + })}\n\n`; + +const finishChunk = `data: ${JSON.stringify({ + choices: [{ delta: {}, finish_reason: "stop" }], +})}\n\n`; + +async function withServer( + handler: (res: ServerResponse) => void, + run: () => Promise, +): Promise { + const prior: Record = {}; + for (const key of TOUCHED_ENV_VARS) { + prior[key] = process.env[key]; + } + const open = new Set(); + const server = createServer((_req, res) => { + open.add(res); + res.on("close", () => open.delete(res)); + res.writeHead(200, { "content-type": "text/event-stream" }); + handler(res); + }); + await new Promise((resolve) => server.listen(0, resolve)); + const address = server.address(); + const port = typeof address === "object" && address ? address.port : 0; + try { + process.env.LITELLM_BASE_URL = `http://127.0.0.1:${port}`; + process.env.LITELLM_API_KEY = "test-key"; + await run(); + } finally { + for (const res of open) { + res.destroy(); + } + server.close(); + for (const key of TOUCHED_ENV_VARS) { + if (prior[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = prior[key]; + } + } + } +} + +void runSuite(async () => { + const { NeuroLink, ProviderRegistry } = await import("../dist/index.js"); + await ProviderRegistry.registerAllProviders(); + + const generate = (timeout: number, turnTimeoutMs: number) => + new NeuroLink({ conversationMemory: { enabled: false } }).generate({ + provider: "litellm", + model: "gpt-4o-mini", + input: { text: "hi" }, + maxSteps: 1, + timeout, + turnTimeoutMs, + disableTools: true, + disableInternalFallback: true, + }); + + section("absolute per-step ceiling"); + + await test("a keep-alive-only stream is cut off by the per-call timeout, not the turn timeout", async () => { + const TURN_TIMEOUT_MS = 120_000; + await withServer( + (res) => { + // Comment frames forever, never a data frame and never [DONE]. + const timer = setInterval(() => res.write(": ping\n\n"), 50); + res.on("close", () => clearInterval(timer)); + }, + async () => { + const started = Date.now(); + let error: unknown; + try { + await generate(300, TURN_TIMEOUT_MS); + } catch (e) { + error = e; + } + const elapsed = Date.now() - started; + assert( + error !== undefined, + "generate() resolved instead of timing out", + ); + assert( + /timed out/i.test(String((error as Error)?.message ?? error)), + `expected a timeout error, got: ${String(error)}`, + ); + assert( + elapsed < 30_000, + `the step ran ${elapsed}ms; the ceiling did not bound it`, + ); + }, + ); + }); + + section("idle semantics are kept"); + + await test("a slow-but-alive stream longer than the idle window but under the ceiling completes", async () => { + await withServer( + (res) => { + // 6 content frames 100ms apart: ~600ms total, beyond the 300ms idle + // window, and no 300ms gap anywhere. + let n = 0; + const timer = setInterval(() => { + n++; + if (n <= 6) { + res.write(contentChunk(`part${n} `)); + } else { + clearInterval(timer); + res.write(finishChunk); + res.end("data: [DONE]\n\n"); + } + }, 100); + res.on("close", () => clearInterval(timer)); + }, + async () => { + const result = await generate(300, 60_000); + assert( + result.content.includes("part1") && result.content.includes("part6"), + `unexpected content: ${result.content}`, + ); + }, + ); + }); + + await test("a stream that goes silent is still cut off by the idle window", async () => { + await withServer( + (res) => { + res.write(contentChunk("hello")); + }, + async () => { + const started = Date.now(); + let error: unknown; + try { + await generate(300, 60_000); + } catch (e) { + error = e; + } + assert(error !== undefined, "a silent stream did not time out"); + assert(Date.now() - started < 30_000, "the idle window did not fire"); + }, + ); + }); +});