Skip to content

fix: recover ChatGPT turns after websocket connection expiry - #167063

Merged
steipete merged 1 commit into
mainfrom
fix/chatgpt-responses-ws-connection-limit-mid-stream
Oct 8, 2026
Merged

steipete merged 1 commit into
mainfrom
fix/chatgpt-responses-ws-connection-limit-mid-stream

Conversation

@steipete

@steipete steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Fixes #166708

What Problem This Solves

Fixes: an interactive ChatGPT Responses turn fails when its reused WebSocket reaches the connection-age limit while a reply is streaming.

User Impact

Connection expiry now reaches the existing bounded transcript recovery policy, so an interrupted turn can reconnect and finish. Existing safeguards for completed actions, visible output, cancellation, and model fallback remain in force. No configuration or migration is required.

Why This Change Was Made

The transport already rotates sockets at 55 minutes and reconnects once when expiry happens before streaming. A long response can still cross the server limit. After the bounded pre-stream reconnect, this change projects the provider's expiry error to the existing transient transport code, retaining the original error as its cause. The transport retires the failed socket and leaves continuation to the runner; it does not replay a started request.

The separate SDK Responses socket pool is unchanged. Inlining the single-use timeout-signal helper preserves its existing behavior and keeps production net negative: +18/-20 production, +48/-0 tests, +4/-0 docs.

Evidence

  • Regression/negative control: all three transport modes fail with only production reverted (3 new failures, 28 existing tests pass); restoring the fix gives 31 passes. pnpm test packages/ai/src/providers/openai-chatgpt-responses.test.ts --maxWorkers=1: 1.14 s Vitest, 1.86 s wrapper on Testbox. The new cases take milliseconds and use no real timers.
  • Owner and recovery coverage: all five ChatGPT transport files plus both runner recovery files pass: 198 tests. Linux Vitest durations: 3.21 s for transport tests, 35.81 s for runner tests including cold worker preparation; combined wrapper 41.40 s. Existing recovery tests exercise partial output, settled tools, uncertain outcomes, and replay-safe fallback.
  • Checks: pnpm tsgo:core and pnpm tsgo:core:test packages pass on Testbox. Local changed-file lint, formatting, type graphs, ratchets, dead-export, import-cycle, and storage guards pass. Capacity interruption lost the full check:changed summary; its final pairing-account guard was run separately and passed. git diff --check passes.
  • Live Gateway proof: PASS on fresh Blacksmith Testbox: baseline returns state:error for both mid-stream and aged-socket expiry with no recovery; candidate returns state:final for both, using a new socket and the transcript-continuation prompt. The client observes a partial reply before expiry. Final replies contain the prefix once; an unfinished tool call never executes. The aged case reuses a 54-minute socket and advances its clock past 60 minutes mid-stream. Complete baseline/candidate command: 233.300 s, exit 0.
  • Independent review: Codex branch review through P2: scoped-clean, no accepted/actionable findings. It confirmed bounded pre-start reconnect, unchanged non-expiry handling, no post-start transport replay, and equivalent timeout-signal composition.

Proof uses a real isolated Gateway process, native chat.send, and a local scripted Responses WebSocket server with synthetic credentials. It is not a real OpenAI service soak. A separate local probe found that HTTP chat-completions streaming can still reject its append-only terminal projection after recovery; this PR does not change that HTTP behavior. Native interactive chat recovery is the verified surface.

Commands and source identity

Candidate head: d8728b5b1f6a590f6205616ae771e086c1563ae4. Base: a06612710e674f493a3ae8fe1158f60bb56d3924; the affected transport/recovery sources were unchanged on fetched main 8a31a24302f1c. Testbox source checks verify the materialized candidate file hashes because Testbox creates a carrier commit.

node scripts/run-vitest.mjs \
  packages/ai/src/providers/openai-chatgpt-responses.test.ts \
  packages/ai/src/providers/openai-chatgpt-responses.cache.test.ts \
  packages/ai/src/providers/openai-chatgpt-responses-streaming.test.ts \
  packages/ai/src/providers/openai-chatgpt-responses-limits.test.ts \
  packages/ai/src/providers/openai-chatgpt-responses-protocol.test.ts \
  src/agents/embedded-agent-runner/run/attempt-recovery.test.ts \
  src/agents/embedded-agent-runner/run/assistant-failure.test.ts --maxWorkers=1
pnpm tsgo:core
pnpm tsgo:core:test packages
node scripts/crabbox-wrapper.mjs run \
  --id tbx_01m4d82s9r2z02nd754kyfyah3 --label rel6-wslimit --timing-json \
  -- bash .wslimit-proof/run-live-testbox.sh

The task-owned live harness invokes pnpm openclaw gateway run with isolated home/state and ephemeral loopback ports. In one synced invocation it runs baseline production, restores the candidate, and runs the same scenarios again. Proof scratch is not part of the product diff. Lease: tbx_01m4d82s9r2z02nd754kyfyah3 (Blacksmith Testbox); hydration run. Wrapper command exit codes are the proof outcome; the lease has been stopped and is absent from the active lease list.

The initial baseline live assertion expected the historical “Agent run failed” wording; current main instead returned “OpenClaw couldn’t finish this reply.” The fixture now asserts the terminal error and absence of recovery requests, retaining its requirement to observe partial output before injection.

The first remote attempt stopped before tests because a source check expected the original HEAD rather than Testbox's carrier commit; the corrected check verified the wrapper's recorded source and exact file hashes. No product failure was hidden by that correction.

@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 8, 2026
@steipete
steipete marked this pull request as ready for review October 8, 2026 08:39
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 4:45 AM ET / 08:45 UTC.

ClawSweeper review

What this changes

The branch classifies ChatGPT WebSocket connection expiry as a transient transport failure so existing transcript recovery can finish interrupted turns.

Example: A ChatGPT reply streams past the WebSocket connection-age limit.

  • Before: The Gateway returns state:error after partial output without recovering.
  • After: The Gateway continues the transcript and returns state:final, with the partial prefix appearing once.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, worthwhile repair with supplied Gateway before/after proof and no actionable correctness or security findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied after-fix observations exercise the changed ChatGPT transport through a real isolated Gateway, native chat.send, and real WebSocket client with injected mid-stream and aged-socket expiry. Both recover to state:final with one prefix and no unfinished-tool execution; no persistent data contract changes require migration.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A long ChatGPT turn stops after partial output when its reused connection expires, leaving the user without a completed reply.
Reason: The change restores documented bounded recovery for a concrete provider failure without adding configuration or a competing retry owner. Prior area history establishes owner direction.

Merge readiness

✅ Ready for maintainer review

This PR fixes a remaining recovery gap on current main. The supplied Gateway proof covers interrupted replies and aged sockets, and source review found no actionable defect.

Priority: P1
Reviewed head: d8728b5b1f6a590f6205616ae771e086c1563ae4

Before merge

None.

Findings

None.

Agent review details

How this fits together

The ChatGPT subscription transport sends agent requests and converts streamed provider events into assistant messages. Its error metadata tells the agent runner whether to continue the saved conversation, change models, or stop.

flowchart TD
  A[Agent request and transcript] --> B[ChatGPT WebSocket transport]
  B --> C[Streamed reply or connection expiry]
  C --> D[Transient error projection]
  D --> E[Existing bounded recovery policy]
  E --> F[Continue saved transcript]
  F --> G[Completed reply or terminal error]
Loading

Technical review

Best possible solution:

Keep connection-expiry classification in the transport and continuation, cancellation, and replay-safety decisions in the existing runner.

Do we have a high-confidence way to reproduce the issue?

Yes: a normal streamed response followed by websocket_connection_limit_reached reaches the current-main classification gap; supplied baseline Gateway observations corroborate it. This read-only review did not execute the scenario.

Is this the best way to solve the issue?

Yes: the patch supplies the missing transient error fact to the existing recovery owner while preserving bounded pre-stream reconnect and avoiding post-stream request replay.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against e86387d3b267.

Provenance checked

  • packages/ai/src/providers/openai-chatgpt-responses.ts: connection-limit handling keeps the original intent (fix: improve agent runtime correctness from upstream Pi #99949: Align the ChatGPT transport with Codex through connection-limit reconnect and proactive socket rotation.)
  • packages/ai/src/providers/openai-chatgpt-responses.ts: request timeout signal keeps the original intent (c20a055: The recorded commit subject states that Codex response timeouts must be honored; its older blob could not be fetched during this review.)

Testing

Proof path: shipped entry point. Added test files: 1.

Security

None.

Evidence

What I checked:

  • Introduced recovery repair: The introduced delta wraps only the structured connection-limit error with ERR_WEBSOCKET_TRANSPORT, retains its cause, preserves the bounded pre-stream reconnect, and throws after streaming rather than replaying the request. (packages/ai/src/providers/openai-chatgpt-responses.ts:403, d8728b5b1f6a)
  • Still necessary on current main: The three touched files have no changes between the merge base and fetched current main, so main retains the reported classification gap. Raw test-merge parents match the pinned base and head, and its delta contains only the intended three files. (packages/ai/src/providers/openai-chatgpt-responses.ts:412, e86387d3b267)
  • Socket retirement and recovery safeguards: The transport clears cached continuation and releases failed sockets. The runner continues the existing transcript only after its cancellation, terminal-state, tool-settlement, and retry-budget checks; fallback eligibility remains tied to replay safety. (src/agents/embedded-agent-runner/run/attempt-recovery.ts:386, d8728b5b1f6a)
  • After-fix production-boundary proof: The captured PR body, source revision 4ae1fb55070ab5cddb89bc80e4fd4d46e4e3a50be3022b74274d0703dfd28782, records native chat.send through an isolated Gateway and real WebSocket transport against a scripted local server. Baseline returned state:error; the candidate returned state:final for mid-stream and aged-socket expiry, preserved the prefix once, and never executed an unfinished tool call. The run took 233.300 seconds and exited zero. This is injected-fault Gateway proof, not an OpenAI service soak; no execution was performed during this review. (d8728b5b1f6a)
  • Regression coverage: The added table exercises auto, websocket, and websocket-cached modes with visible text followed by connection expiry. It checks retained output, transient classification, socket retirement, and absence of transport replay. The PR reports three failures with production reverted and 31 passes with the fix, plus 198 transport/recovery tests passing. (packages/ai/src/providers/openai-chatgpt-responses.test.ts:253, d8728b5b1f6a)
  • Existing owner intent: fix: improve agent runtime correctness from upstream Pi #99949 explicitly adopted Codex connection-limit reconnect and proactive rotation at OpenClaw's existing transport owner. Main-line blame, feature history, and shortlog establish prior area involvement by Peter Steinberger; this patch retains bounded reconnect and adds the missing post-start recovery classification. (packages/ai/src/providers/openai-chatgpt-responses.ts:394, 5ea80c8d80fd)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

PR surface

Source -2, Tests +48, Docs +4. Total +50 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 18 20 -2
Tests 1 48 0 +48
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 70 20 +50

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #166708
Summary: This PR directly repairs the subscription WebSocket expiry classification gap described by the linked issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P1: A reported long-running ChatGPT agent turn terminates without completing its reply despite an existing recovery contract.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P1: A reported long-running ChatGPT agent turn terminates without completing its reply despite an existing recovery contract.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

@steipete
steipete merged commit 2095264 into main Oct 8, 2026
167 checks passed
@steipete
steipete deleted the fix/chatgpt-responses-ws-connection-limit-mid-stream branch October 8, 2026 08:56
@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

Labels

docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: ChatGPT Responses websocket hits the 60-minute connection limit mid-stream; turn fails with no reconnect or model fallback

1 participant