[GH-ISSUE #2743] [Issue]: Provider streaming readers lack abort wiring & reader.cancel(); bodyTimeout:0 lets a stalled stream hang forever #1385

Closed
opened 2026-10-21 05:32:45 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @kolacheee on GitHub (Jun 21, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2743

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The OpenAI chat() and Responses tool path register options.signal -> reader.cancel() to proactively tear down the backend TCP connection on abort, but chatComplete()'s streaming branch and chatResponses() omit this — they rely solely on undici's fetch abort. The capStreamingResponse wrapper ReadableStream defines only start() and no cancel(), so cancelling the wrapped body does not cancel the inner reader or close the per-request undici Agent. Finally, the LLM agent sets bodyTimeout: 0 with only a headersTimeout, so a stream that stalls mid-body (proxy half-open, model deadlock, token rate -> 0) has no inactivity timeout and the read loop awaits forever absent an external abort.

Sub-bug 1: OpenAI chatComplete() streaming reader has no abort wiring (MEDIUM, leak)

  • How it breaks: The chatComplete() stream branch grabs response.body.getReader() and loops with no signal.addEventListener('abort', () => reader.cancel()) and no in-loop signal.aborted check; the signal only reaches fetch. On a tool-enabled abort, the reader is not proactively cancelled and onToken can keep firing briefly (dropped at the route, which masks the symptom). Contrast chat() (978-990).
  • Trace: openai.provider.ts:1230 (reader), 1246-1358 (loop, no abort), vs chat() 983-990.

Sub-bug 2: Responses chatResponses() has no abort wiring (LOW, abort-failure)

  • How it breaks: The canonical token generator for all Responses-only models (GPT-5.x, Codex, o-series, ChatGPT-subscription) gets the reader and enters while(true) with no abort listener and no signal.aborted check — the only abort wiring on the streaming Responses path is missing. Fetch-signal abort still unwinds the loop, so this is a missing redundant safety net rather than a hard hang.
  • Trace: openai.provider.ts:1707-1812; contrast chat() 983-990 and chatCompleteResponses() 1899-1906.

Sub-bug 3: capStreamingResponse has no cancel() handler (LOW, leak)

  • How it breaks: new ReadableStream({ async start(controller){...} }) defines only start(). The default cancel algorithm is a no-op, so calling .cancel() on the wrapped body never cancels the inner source reader and never dispatcher?.close()s the per-request Agent. Today the fetch signal masks this (signal abort rejects the inner read -> catch closes the dispatcher), so only a future caller cancelling without a backing signal leaks.
  • Trace: security.ts:430-469 (wrapper, no cancel), 549-583 (per-request Agent), base-provider.ts:20-40 (llmFetch, bufferResponse:false).

Sub-bug 4: bodyTimeout:0 — stalled body hangs forever (MEDIUM, hang)

  • How it breaks: llmAgentOptions = { bodyTimeout: 0, headersTimeout: 5min }. headersTimeout only bounds time-to-headers; bodyTimeout:0 disables the inter-chunk inactivity timeout for the whole body. After headers + first byte, a stalled-but-open socket makes await reader.read() block indefinitely; the provider loops have no per-read watchdog. The main route passes a signal but it only fires on client disconnect, so a stall while the client stays connected freezes the stream with no error/timeout. An internal caller without a signal would hang until process restart.
  • Repro: Front the provider with a proxy that goes half-open after first byte; the generation streams a little then freezes permanently.
  • Trace: base-provider.ts:13-14 (options), 36 (default agentOptions); read loops openai.provider.ts:998-1004, anthropic.provider.ts:543-549, security.ts:441.

Suggested Fix

  • Add the chat() abort pattern to chatComplete()'s streaming branch and chatResponses(): bail early if options.signal?.aborted, register const onAbort = () => reader.cancel().catch(()=>{}) ({once:true}), remove it in a finally, and optionally if (options.signal?.aborted) break; at the top of the read loop.
  • Add a cancel(reason) method to the capStreamingResponse ReadableStream that await innerReader.cancel(reason) and await dispatcher?.close().
  • Replace bodyTimeout: 0 with a finite inter-chunk inactivity window (e.g. 60-120s) so a stalled body rejects with BodyTimeoutError, OR add a per-read inactivity watchdog that aborts when no bytes arrive within N seconds. (bodyTimeout is inter-chunk, not total duration, so a finite value won't kill a slow-but-healthy long stream.)

Root-cause throughline

Proactive abort/cancel was wired into the original chat() reader as defense-in-depth against undici not propagating aborts, but the later chatComplete/Responses readers and the capStreamingResponse wrapper never got the same reader.cancel()/cancel() plumbing, and the transport was tuned to never time out a body — so the system depends entirely on a single fetch-signal abort path and has no inactivity safety net for a mid-body stall.

Verification checklist (leave all UNCHECKED)

  • Manually verify: aborting a tool-enabled OpenAI generation promptly closes the backend connection (network trace)
  • Manually verify: aborting a Responses-model (GPT-5.x/o-series) generation tears down the reader
  • Manually verify: a simulated mid-body stall eventually surfaces an error/timeout instead of hanging
  • Confirm a long but healthy stream is not killed by the new finite bodyTimeout
  • Run pnpm check

Affected files

  • packages/server/src/services/llm/providers/openai.provider.ts
  • packages/server/src/utils/security.ts
  • packages/server/src/services/llm/base-provider.ts

Audit provenance

Found by a multi-agent static audit of the streaming/SSE subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged staging tree. Severity: MEDIUM.

AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.

Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2743 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The OpenAI `chat()` and Responses tool path register `options.signal -> reader.cancel()` to proactively tear down the backend TCP connection on abort, but `chatComplete()`'s streaming branch and `chatResponses()` omit this — they rely solely on undici's fetch abort. The `capStreamingResponse` wrapper `ReadableStream` defines only `start()` and no `cancel()`, so cancelling the wrapped body does not cancel the inner reader or close the per-request undici Agent. Finally, the LLM agent sets `bodyTimeout: 0` with only a `headersTimeout`, so a stream that stalls mid-body (proxy half-open, model deadlock, token rate -> 0) has no inactivity timeout and the read loop awaits forever absent an external abort. ### Sub-bug 1: OpenAI chatComplete() streaming reader has no abort wiring (MEDIUM, leak) - **How it breaks:** The `chatComplete()` stream branch grabs `response.body.getReader()` and loops with no `signal.addEventListener('abort', () => reader.cancel())` and no in-loop `signal.aborted` check; the signal only reaches `fetch`. On a tool-enabled abort, the reader is not proactively cancelled and `onToken` can keep firing briefly (dropped at the route, which masks the symptom). Contrast `chat()` (978-990). - **Trace:** `openai.provider.ts:1230` (reader), `1246-1358` (loop, no abort), vs `chat()` `983-990`. ### Sub-bug 2: Responses chatResponses() has no abort wiring (LOW, abort-failure) - **How it breaks:** The canonical token generator for all Responses-only models (GPT-5.x, Codex, o-series, ChatGPT-subscription) gets the reader and enters `while(true)` with no abort listener and no `signal.aborted` check — the only abort wiring on the streaming Responses path is missing. Fetch-signal abort still unwinds the loop, so this is a missing redundant safety net rather than a hard hang. - **Trace:** `openai.provider.ts:1707-1812`; contrast `chat()` `983-990` and `chatCompleteResponses()` `1899-1906`. ### Sub-bug 3: capStreamingResponse has no cancel() handler (LOW, leak) - **How it breaks:** `new ReadableStream({ async start(controller){...} })` defines only `start()`. The default `cancel` algorithm is a no-op, so calling `.cancel()` on the wrapped body never cancels the inner source reader and never `dispatcher?.close()`s the per-request Agent. Today the fetch signal masks this (signal abort rejects the inner read -> catch closes the dispatcher), so only a future caller cancelling without a backing signal leaks. - **Trace:** `security.ts:430-469` (wrapper, no cancel), `549-583` (per-request Agent), `base-provider.ts:20-40` (llmFetch, bufferResponse:false). ### Sub-bug 4: bodyTimeout:0 — stalled body hangs forever (MEDIUM, hang) - **How it breaks:** `llmAgentOptions = { bodyTimeout: 0, headersTimeout: 5min }`. `headersTimeout` only bounds time-to-headers; `bodyTimeout:0` disables the inter-chunk inactivity timeout for the whole body. After headers + first byte, a stalled-but-open socket makes `await reader.read()` block indefinitely; the provider loops have no per-read watchdog. The main route passes a signal but it only fires on client disconnect, so a stall while the client stays connected freezes the stream with no error/timeout. An internal caller without a signal would hang until process restart. - **Repro:** Front the provider with a proxy that goes half-open after first byte; the generation streams a little then freezes permanently. - **Trace:** `base-provider.ts:13-14` (options), `36` (default agentOptions); read loops `openai.provider.ts:998-1004`, `anthropic.provider.ts:543-549`, `security.ts:441`. ## Suggested Fix - Add the `chat()` abort pattern to `chatComplete()`'s streaming branch and `chatResponses()`: bail early if `options.signal?.aborted`, register `const onAbort = () => reader.cancel().catch(()=>{})` (`{once:true}`), remove it in a `finally`, and optionally `if (options.signal?.aborted) break;` at the top of the read loop. - Add a `cancel(reason)` method to the `capStreamingResponse` ReadableStream that `await innerReader.cancel(reason)` and `await dispatcher?.close()`. - Replace `bodyTimeout: 0` with a finite inter-chunk inactivity window (e.g. 60-120s) so a stalled body rejects with `BodyTimeoutError`, OR add a per-read inactivity watchdog that aborts when no bytes arrive within N seconds. (bodyTimeout is inter-chunk, not total duration, so a finite value won't kill a slow-but-healthy long stream.) ## Root-cause throughline Proactive abort/cancel was wired into the original `chat()` reader as defense-in-depth against undici not propagating aborts, but the later `chatComplete`/Responses readers and the `capStreamingResponse` wrapper never got the same `reader.cancel()`/`cancel()` plumbing, and the transport was tuned to never time out a body — so the system depends entirely on a single fetch-signal abort path and has no inactivity safety net for a mid-body stall. ## Verification checklist (leave all UNCHECKED) - [ ] Manually verify: aborting a tool-enabled OpenAI generation promptly closes the backend connection (network trace) - [ ] Manually verify: aborting a Responses-model (GPT-5.x/o-series) generation tears down the reader - [ ] Manually verify: a simulated mid-body stall eventually surfaces an error/timeout instead of hanging - [ ] Confirm a long but healthy stream is not killed by the new finite bodyTimeout - [ ] Run `pnpm check` --- ### Affected files - `packages/server/src/services/llm/providers/openai.provider.ts` - `packages/server/src/utils/security.ts` - `packages/server/src/services/llm/base-provider.ts` ### Audit provenance Found by a multi-agent static audit of the streaming/SSE subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged `staging` tree. Severity: **MEDIUM**. > AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.
Author
Owner

@SpicyMarinara commented on GitHub (Jun 21, 2026):

Addressed on PR #2747. OpenAI chatComplete streaming and Responses chat streaming now wire options.signal to reader.cancel() and remove abort listeners in finally; the existing Responses chatComplete listener cleanup was also made exception-safe. capStreamingResponse now implements cancel(reason) that cancels the inner reader and closes the dispatcher. The shared LLM dispatcher and embedding/local-sidecar requests now use finite body timeouts instead of bodyTimeout: 0, preventing half-open body stalls from hanging forever. Deferred full pnpm validation until the end of the issue sweep, per maintainer request.

<!-- gh-comment-id:4763245232 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Addressed on PR #2747. OpenAI chatComplete streaming and Responses chat streaming now wire options.signal to reader.cancel() and remove abort listeners in finally; the existing Responses chatComplete listener cleanup was also made exception-safe. capStreamingResponse now implements cancel(reason) that cancels the inner reader and closes the dispatcher. The shared LLM dispatcher and embedding/local-sidecar requests now use finite body timeouts instead of bodyTimeout: 0, preventing half-open body stalls from hanging forever. Deferred full pnpm validation until the end of the issue sweep, per maintainer request.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1385
No description provided.