Repository navigation
fix: silent model WebSocket streams hang past the idle timeout - #140335
Conversation
The LLM idle watchdog armed its gap timer only while the consumer sat inside next() and cleared it as soon as an event was delivered, so a provider that went silent while the consumer was parked between next() calls was never aborted. Keep the watchdog armed from the first next() until the producer settles or the iterator closes, re-armed by delivered events, provider activity, and tool heartbeats. Report ChatGPT WebSocket stream progress on the caller's signal so that activity reaches the watchdog like the SSE path.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 6, 2026, 3:12 PM ET / 19:12 UTC. ClawSweeper reviewWhat this changesKeeps the model idle watchdog active while native stream consumers pause, forwards WebSocket progress to it, and observes producer completion without prematurely clearing argument-repair state. Merge readiness✅ Ready for maintainer review The fix remains necessary: current main and the latest release retain the parked-consumer watchdog gap. The previous argument-repair finding is addressed, and no new blocking correctness finding was identified. Priority: P1 Review scores
Verification
How this fits togetherThe embedded agent runner consumes model events through stream decorators that normalize responses and enforce timeouts. Provider activity keeps requests alive; sustained silence aborts the request and returns control to the runner. flowchart TD
A[Model request] --> B[WebSocket provider]
B --> C[Response event stream]
C --> D[Argument repair]
D --> E[Agent consumer]
B --> F[Idle watchdog]
C -->|Producer completed| F
F -->|Silence exceeds budget| G[Abort request]
F -->|Activity| F
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +31, Tests +647. Total +678 across 7 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep producer completion separate from consumer cleanup while enforcing the existing silence budget and preserving structural-stream compatibility. Do we have a high-confidence way to reproduce the issue? Yes, source establishes the gap: pause consumption after the first event while the provider remains silent, and current main clears its timer. The supplied regression exercises this scenario; this review did not execute it. Is this the best way to solve the issue? Yes. Observing the native producer promise avoids consumer-owned cleanup, and forwarding WebSocket activity prevents healthy paused consumers from timing out without adding another timeout policy. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against e70faf754007. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (2 earlier review cycles) |
llm-idle-timeout.test.ts sits at the max-lines lint limit; keep the new coverage in a sibling file.
…esults Keep native EventStream completion independent of consumer result decorators, and retain historical pending-read guards for structural streams. Cover producer completion between malformed argument fragments and parked structural consumers. Worked on by: - @VACInc Co-authored-by: VACInc <[email protected]>
|
@clawsweeper re-review Updated existing PR head: Red/green evidence and the implementation tradeoff are now in the PR description. Final local result: 177 tests across 7 files passed, targeted lint and both ratchets passed, fresh autoreview scoped-clean through P2. Clean-install build/type proof is being followed through updated-head CI; local package-manager/shared-install safeguards were not bypassed. Review only; do not merge. |
|
🦞🧹 I asked ClawSweeper to review this item again. |
…rol-ui * origin/main: docs: remove the empty release-sections nav group (#140427) fix(tooling): omit Codex machine squash credit (#140420) chore(ui): refresh control ui locales (#140384) refactor(plugin-sdk): reuse native approval input contracts (#140415) fix: silent model WebSocket streams hang past the idle timeout (#140335) perf(ai): avoid unused text extraction for image results (#140409) fix(ui): distinguish failed GitHub status checks from disconnected accounts (#140333) refactor(cron): share runtime feedback schema fields (#140408) fix: avoid duplicate cloud worker teardown during recovery (#140377) fix(cli): show executable approval scope (#138386) refactor(ui): reuse shared requirement records (#140407) test(gateway): table-drive device token lifecycle checks (#140403) fix(chat): fence delayed history at terminal retirement (#140379) test(skills): compare large upload bytes natively (#140402) refactor(delivery): reuse the canonical rendered batch plan type (#140386) docs(start): repair the first-run path from landing page to first channel (#140390) # Conflicts: # docs/.i18n/glossary.zh-CN.json
…ig-ref * origin/main: (31 commits) docs(web): split the Control UI page into task pages (#140437) fix: tool_search rejects calls that send both query and queries (#140310) fix(update): preserve rollback and truthful serving reports (#140419) fix: restore context when CLI recovery starts a fresh session (#140294) refactor(tests): retain transport-driven auth dismissal coverage (#140430) fix: stop unfinished subagents before resetting a conversation (#140417) fix(models): cap configured output at the final context window (#140436) refactor(mcp): reuse transport config normalization (#140439) test(gateway): preserve saved config in auth reload fixture (#140433) fix(plugins): inherit active config for embedded agent runs (#140435) refactor(tui): remove test-only shutdown timer hooks (#140432) fix(agents): preserve channel silent-reply guidance (#138345) fix(tasks): cancel resumed yielded subagent tasks (#140410) refactor(doctor): share compaction config traversal (#140330) fix(doctor): restore LINE and Mattermost account promotion (#136045) docs: remove the empty release-sections nav group (#140427) fix(tooling): omit Codex machine squash credit (#140420) chore(ui): refresh control ui locales (#140384) refactor(plugin-sdk): reuse native approval input contracts (#140415) fix: silent model WebSocket streams hang past the idle timeout (#140335) ... # Conflicts: # docs/web/control-ui.md
…law#140335) * fix(agents): abort silent model streams while the consumer is parked The LLM idle watchdog armed its gap timer only while the consumer sat inside next() and cleared it as soon as an event was delivered, so a provider that went silent while the consumer was parked between next() calls was never aborted. Keep the watchdog armed from the first next() until the producer settles or the iterator closes, re-armed by delivered events, provider activity, and tool heartbeats. Report ChatGPT WebSocket stream progress on the caller's signal so that activity reaches the watchdog like the SSE path. * test(agents): move parked-consumer watchdog tests to their own file llm-idle-timeout.test.ts sits at the max-lines lint limit; keep the new coverage in a sibling file. * fix(agents): observe producer completion without consuming repaired results Keep native EventStream completion independent of consumer result decorators, and retain historical pending-read guards for structural streams. Cover producer completion between malformed argument fragments and parked structural consumers. Worked on by: - @VACInc Co-authored-by: VACInc <[email protected]> --------- Co-authored-by: VACInc <[email protected]> Co-authored-by: roboclaw-bot <[email protected]>
|
Related transcript-state repair #138984 has now merged as b0ae5b6. It addresses atomic history publication, reset-crossing amplification, and selected-reader context. It does not replace the WebSocket liveness or final-answer recovery work tracked here. Similar visible stalls or stale answers can have different owners; these fixes remain complementary. |
Related: #138985 (companion fix: classifies the WebSocket failure once it surfaces so the turn retries; this PR shortens how long a dead socket goes unnoticed. Both are needed.)
Related: #91882 (history search places the consumer-position arming of the watchdog,
waitingForProvider/stopWaiting, in this change)Related: #140310 (tool_search validation errors that preceded the stalled request in the same incident; independent defect)
What Problem This Solves
Fixes an issue where an agent turn on a native Codex/OpenAI WebSocket route (
openai-chatgpt-responses, transportauto) would hang for many minutes when the socket went silent, even though the cloud model idle watchdog is 120 s. In one live Telegram turn the request sat 7 min 52 s before the socket errored on its own; the same gateway also logged a 38.5 min silent WebSocket request and a 342 s one that only ended by user abort. The idle watchdog never fired in two days of logs.High Level TLDR
The idle watchdog only counted silence while the consumer was actively waiting inside
next(), and reset as soon as an event was delivered. If the consumer was parked betweennext()calls (for example awaiting an event handler after the firststartevent), a dead provider connection was never aborted. The watchdog now measures provider silence itself: it stays armed from the firstnext()until the producer finishes or the iterator closes, and every delivered event, provider progress notification, or tool heartbeat restores the budget. The ChatGPT WebSocket path also now reports progress on the caller's signal, so its activity reaches the watchdog the way the SSE path already did.Why This Change Was Made
streamWithIdleTimeoutinsrc/agents/embedded-agent-runner/run/llm-idle-timeout.tsis the runner's only silence guard after the first provider event. Its timer was armed innext()and cleared bystopWaiting()on delivery, so it policed consumer position rather than provider liveness. The fix keeps one timer running across deliveries, re-armed by delivered events,notifyLlmRequestActivity, and run-scoped tool activity, and disarms when the producer-owned completion promise settles or the iterator closes. Completion is obtained throughgetEventStreamCompletion, not decoratedstream.result(): argument-repair buffers remain owned by the consumer until queued fragments drain. Custom structural streams without native completion preserve their historical pending-next()-only watchdog rather than guessing producer completion from consumer-result decorators. Firing still aborts the provider signal, callsonIdleTimeout(which the runner maps toabortRun), and rejects a pendingnext().On the WebSocket path
processWebSocketStreampassed its provider-internal request-abort composite assignaltoprocessResponsesStream, so per-eventnotifyLlmRequestActivitywent to a signal nothing observed; the SSE path passes the caller's signal. A newactivitySignalparameter carries the caller's signal for the WebSocket path. Without it, a slow consumer with a live WebSocket would now be aborted falsely (proved by the chain test "F").Not changed: tool heartbeats (
wrapEmbeddedAttemptToolWithActivity, 60 s while a tool executes) still re-arm the watchdog. A tool that never finishes would keep a silent socket alive; that is a separate invariant and is left as a follow-up.Root Cause
providerAccepted: true(provider_stream_opened), thenmodel.completedat +471,997 ms withtimedOut=false,idleTimedOut=false,failureKind: "transport",rawError: "WebSocket error". The provider loggedcaller-abortnever; had the 120 s timer fired,abortStreamwould have aborted the socket and the provider would have loggedfailureKind: "caller-abort"at ~120 s.agents.defaults.timeoutSeconds: 3600, no providertimeoutSeconds, cloud base URL.resolveLlmIdleTimeoutMs/resolveLlmFirstEventTimeoutMsboth return 120,000 ms for that model.main@9d20f0b07acplus overlays fix: OpenCode Go/Zen requests are missing the required x-opencode-session header #137464, fix(sessions): publish complete rewrites without reset amplification #138984, fix: recover final answers after WebSocket disconnects #138985; none touches the watchdog chain, signals, or options (ruled out as causal; fix: recover final answers after WebSocket disconnects #138985 is what produced the successful retry after the socket error).llm-idle-timeout.tsarmTimer()returned early unlesswaitingForProvider, andstopWaiting()cleared the timer on every delivered event. The full runner wrapper chain around the real provider with a mocked WebSocket reproduces the live signature: a consumer parked afterstartsees no abort for 472 s and the run ends only when the socket errors (chain test "D" fails onmain).User Impact
A model request whose WebSocket goes silent is now aborted after the configured idle window (cloud 120 s by default) and handed to the existing retry/failover path, instead of waiting for the socket to die on its own. Healthy slow streams are unaffected: provider progress on both SSE and WebSocket paths keeps the watchdog alive, and a finished response is never aborted.
Evidence
Completion-observer repair (September 6, 2026)
Addressed ClawSweeper’s completion/argument-repair finding and its rank-up move.
EventStreamrecords its original final-result promise in a weakly keyed producer-owned registry; the watchdog observes it through the existing AI internal-runtime facade without calling consumer-result decorators. No changes to repair heuristics, timeouts, provider activity forwarding, or tool heartbeats.EventStream→ argument repair → watchdog regression on8af0f675d7fee6a01933063b187a559d8d1f49adfailed as intended: after producer completion between malformed argument fragments,toolcall_end.argumentswas{}rather than{ path: "safe.txt" }(1 failed, 3 passed).end(result), and rejection on bareend().git diff --check, max-lines ratchet, and assertion-safety ratchet pass.codex-rs/core/src/client.rscompletion forwarding at revisionddf04ad26789d040f9ef6a96736f76602e35a6cc; this patch changes the built-in OpenClaw Responses route, not native Codex deadlines.Earlier-revision behavior proof (retained context)
Chain regression test
src/agents/embedded-agent-runner/run/llm-idle-timeout.codex-ws-chain.test.tsassembles the real runner wrappers exactly asattempt-stream.tsdoes (resolveEmbeddedAgentStreamwith strategyopenclaw-native-codex-responses, tool-call wrappers,streamWithIdleTimeout, first-event injection, diagnostic model-call wrapper, Code Mode wrapper) around the realstreamOpenAICodexResponseswith a controlled WebSocket, consumed likeagent-stream-response.ts, under fake timers:onIdleTimeoutcalled once, socket closed.emit()afterstart, socket silent): aborted at 120 s. Fails onmain(no abort in 472 s; run ends only on socket error).response.in_progressevery 60 s for 300 s): no abort, completes normally. Fails with the watchdog change alone (proves the WebSocket activity-signal fix is required).Unit tests in
llm-idle-timeout.parked-consumer.test.ts: parked consumer + silent provider aborts; provider activity keeps a parked consumer alive; a settled producer is never aborted. The first two fail onmain.What was not tested
Earlier-revision verification (retained context)
oxfmton changed files,git diff --check,node --import tsx scripts/run-oxlint-shards.mts --only=core --split-core --core-stripe=2/5(the CI stripe that flagged max-lines on revision 1) passestsgo -p tsconfig.core.json --noEmit(direct)$autoreview --mode local --base origin/main: scoped-clean, no P0 findingsWorked on by: