Skip to content

fix: add stream idle timeout for hung proxy connections - #31558

Closed
neonsecret wants to merge 1 commit into
openclaw:mainfrom
neonsecret:fix/stream-idle-timeout
Closed

neonsecret wants to merge 1 commit into
openclaw:mainfrom
neonsecret:fix/stream-idle-timeout

Conversation

@neonsecret

@neonsecret neonsecret commented Mar 2, 2026 •

Copy link
Copy Markdown

Summary

  • Adds a 120-second idle timeout to the openai-completions streaming loop via a pnpm patch on @mariozechner/pi-ai
  • Prevents subagent sessions from hanging indefinitely when a proxy (e.g. LiteLLM) accepts a request (HTTP 200) but the backend stalls and never sends SSE events
  • The timer resets on every received SSE chunk, so active long-running streams are unaffected

Problem

When using OpenClaw with a proxy like LiteLLM in front of Vertex AI:

  1. The proxy responds with HTTP 200 headers immediately
  2. The OpenAI SDK's 10-minute fetch timeout is cleared (headers received)
  3. If the backend stalls, the SSE stream hangs silently — no timeout fires
  4. Only the session-level runTimeoutSeconds (default 600s, configurable up to hours) can kill it

This caused subagent sessions to hang for hours with no output.

Fix

The patch wraps the for await (const chunk of openaiStream) loop with an idle timer:

  • Timer starts when streaming begins (after HTTP 200 headers)
  • Resets on every SSE chunk received
  • If 120 seconds pass with no chunk, aborts the stream via openaiStream.controller.abort()
  • The error propagates through the agent loop for retry or failure reporting

Test plan

  • Verify normal streaming responses still work (timer resets on each chunk)
  • Verify long-running responses with extended thinking (>2min between tool calls) still work — thinking tokens reset the timer
  • Simulate a hung proxy connection — should abort after 120s instead of hanging

🤖 Generated with Claude Code

When a proxy (e.g. LiteLLM) accepts an API request and returns HTTP 200
headers but the backend (e.g. Vertex AI) stalls, the SSE stream hangs
indefinitely. The OpenAI SDK's 10-minute timeout only covers the initial
fetch — once headers arrive, it's cleared.

This patch adds a 120-second idle timeout to the openai-completions
streaming loop. The timer resets on every SSE chunk. If no chunk arrives
within 120s, the stream's AbortController fires, killing the hung
connection. The agent loop then handles the error (retry or report).

This does not affect the overall session timeout (configurable via
agents.defaults.timeoutSeconds) — active streams where chunks keep
flowing are unaffected.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 61a4f73fa2

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

}
}
}
+ clearTimeout(_idleTimer);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear idle timer in a finally block

The new idle timeout is only cleared on the normal end-of-stream path, but for await (const chunk of openaiStream) can exit via throw (for example user-initiated aborts or stream/parsing errors). In those cases _idleTimer remains scheduled for up to 120 seconds, which retains references and can keep one-off Node processes alive unexpectedly; wrapping the loop in try { ... } finally { clearTimeout(_idleTimer) } avoids this leak across all exit paths.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR addresses a real and well-described problem: proxies like LiteLLM can return HTTP 200 immediately, causing the OpenAI SDK's fetch timeout to clear before any SSE data arrives, leaving the streaming loop to hang silently. The fix wraps the for await loop with a 120-second idle timer that resets on each received chunk and aborts the stream if no data arrives within the window. The approach is sound and the package.json wiring is correct.

Key observations:

  • The idle timer reset logic (clearTimeout + new setTimeout on each chunk) is the correct pattern for this kind of activity-based timeout.
  • The timer is cleared after the loop completes normally (line added after the for block).
  • Minor gap: If an exception is thrown during chunk processing inside the loop body, the active _idleTimer is never cleared. A dangling timer will then fire 120s later and call openaiStream.controller.abort() on an already-closed/errored stream. Wrapping the loop in a try/finally would fix this cleanly.
  • The patch uses placeholder blob indices (1111111..2222222), which is cosmetically unusual but functionally harmless since pnpm patch applies by context lines, not blob hashes.

Confidence Score: 4/5

  • Safe to merge; the fix correctly solves the hung-connection problem with only a minor cleanup gap on the error path.
  • The core timeout logic is correct and well-reasoned. The only issue is a missing try/finally that could leave a dangling timer firing on an already-closed stream when an exception escapes the loop body — this is low-severity since calling abort() on a done stream is generally benign, but it is a code-quality gap worth addressing before merging.
  • patches/@[email protected] — the try/finally cleanup improvement.

Last reviewed commit: 61a4f73

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment on lines +13 to +24
+ let _idleTimer = setTimeout(() => openaiStream.controller.abort(), _IDLE_MS);
for await (const chunk of openaiStream) {
+ clearTimeout(_idleTimer);
+ _idleTimer = setTimeout(() => openaiStream.controller.abort(), _IDLE_MS);
if (chunk.usage) {
const cachedTokens = chunk.usage.prompt_tokens_details?.cached_tokens || 0;
const reasoningTokens = chunk.usage.completion_tokens_details?.reasoning_tokens || 0;
@@ -241,6 +248,7 @@
}
}
}
+ clearTimeout(_idleTimer);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing clearTimeout on exception path

If an exception is thrown during chunk processing (inside the for await loop body, after _idleTimer is reset but before the loop iterates again), the clearTimeout(_idleTimer) at the bottom is never reached. This leaves a dangling 120s timer that will eventually call openaiStream.controller.abort() on an already-errored or garbage-collectable stream.

A try/finally block would guarantee cleanup on all exit paths — normal completion, early return, and thrown exceptions:

const _IDLE_MS = 120000;
let _idleTimer = setTimeout(() => openaiStream.controller.abort(), _IDLE_MS);
try {
    for await (const chunk of openaiStream) {
        clearTimeout(_idleTimer);
        _idleTimer = setTimeout(() => openaiStream.controller.abort(), _IDLE_MS);
        // ... rest of chunk processing
    }
} finally {
    clearTimeout(_idleTimer);
}
finishCurrentBlock(currentBlock);

This also handles the case where openaiStream.controller.abort() fires (the intended timeout path): the finally block runs after the AbortError propagates out of the loop, and clearTimeout on an already-fired timer is harmless.

Prompt To Fix With AI
This is a comment left during a code review.
Path: patches/@[email protected]
Line: 13-24

Comment:
**Missing `clearTimeout` on exception path**

If an exception is thrown during chunk processing (inside the `for await` loop body, after `_idleTimer` is reset but before the loop iterates again), the `clearTimeout(_idleTimer)` at the bottom is never reached. This leaves a dangling 120s timer that will eventually call `openaiStream.controller.abort()` on an already-errored or garbage-collectable stream.

A `try/finally` block would guarantee cleanup on all exit paths — normal completion, early return, and thrown exceptions:

```javascript
const _IDLE_MS = 120000;
let _idleTimer = setTimeout(() => openaiStream.controller.abort(), _IDLE_MS);
try {
    for await (const chunk of openaiStream) {
        clearTimeout(_idleTimer);
        _idleTimer = setTimeout(() => openaiStream.controller.abort(), _IDLE_MS);
        // ... rest of chunk processing
    }
} finally {
    clearTimeout(_idleTimer);
}
finishCurrentBlock(currentBlock);
```

This also handles the case where `openaiStream.controller.abort()` fires (the intended timeout path): the `finally` block runs after the `AbortError` propagates out of the loop, and `clearTimeout` on an already-fired timer is harmless.

How can I resolve this? If you propose a fix, please make it concise.

@obviyus

obviyus commented Mar 30, 2026

Copy link
Copy Markdown
Collaborator

Closing as duplicate; this was superseded by #55072.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants