Skip to content

fix(connection): a frozen Gateway goes unnoticed while TCP stays open - #1962

Merged
shanselman merged 1 commit into
mainfrom
openclaw/gateway-unresponsive-peer-pr
Nov 3, 2026
Merged

shanselman merged 1 commit into
mainfrom
openclaw/gateway-unresponsive-peer-pr

Conversation

@roboclaw-bot

Copy link
Copy Markdown
Contributor

Closes #1958

Prepared by @MertBasar0 (Discord: mertinGo). The Windows validation and measurements below were performed by MertBasar0 on the original candidate; this PR republishes the identical source change.

What Problem This Solves

Fixes: Companion stays connected to a Gateway that has stopped responding, for as long as its TCP connection stays open.

User Impact

User impact: when the peer stops answering, Companion reports the connection as lost and reconnects within about 60 seconds instead of waiting indefinitely.

Behavior to review, two ways a healthy connection can now be dropped:

  • The pong is handled by the ws library on the Gateway's event loop, so an event loop blocked for 30 seconds now causes a reconnect.
  • The client reads the pong in its receive loop, which awaits each message handler inline. I measured this with a shortened timeout: a handler that blocked for 6 seconds against a 1-second timeout caused a disconnect and a reconnect while the server was healthy, and a queued message was lost with that socket. In production the operator client processes messages synchronously and the node client runs invocations through Task.Run, so I expect handlers to stay well under 30 seconds. I did not measure real handler times. If a handler can block that long, the fix is to move it out of the receive loop or raise the timeout.

Why This Change Was Made

WebSocketClientBase set KeepAliveInterval and left KeepAliveTimeout unset, so .NET only sent unsolicited pongs and never expected an answer. 30 + 30 seconds matches the main repo client's limit of two 30-second ticks.

Setting the timeout alone was not enough. When the pong is missing, .NET aborts the socket and the pending receive throws OperationCanceledException, which the listen loop treated as a shutdown: it reconnected without calling OnDisconnected or reporting Disconnected. The first measurement of this change showed exactly that. The loop now separates that case from _cts cancellation and from AbortCurrentWebSocket, which keeps its silent reconnect.

Evidence

A Node server using [email protected] with automatic pongs, which blocks its event loop 75 seconds after connecting. The client is the real WebSocketClientBase with production values.

Before (a4dd026 values) After (this PR)
Pings seen before the freeze 0 2, both answered
After the freeze No change for 165 seconds, until the measurement ended Disconnected, then Connecting, 67 seconds after the freeze
End state connected=True Reconnect attempts running

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs or instructions
  • Tests or validation
  • Security hardening
  • Chore or infrastructure

Scope

  • Tray or WinUI UX
  • Windows node capability
  • Local MCP or winnode
  • Gateway, connection, or pairing
  • Setup or onboarding
  • Permissions, privacy, or security
  • Tests, CI, or docs

Required proof pools

  • windows-wsl-gateway-e2e: connection recovery changed. Not run here.

Validation

Run on a4dd026 plus this change. Windows 11 x64 build 26200, tr-TR, .NET SDK 10.0.402.

  • ./build.ps1: succeeded.
  • Shared tests: 4808 passed, 2 failed, 26 skipped. Both failures come from this host and are in code this PR does not touch: ExecReusableCommandBinderTests.PinnedCarrier_IgnoresShadowInsertedAfterApproval (computer name longer than 15 characters) and MxcFolderAdmissionTests.OwnedJunctionAndSymbolicLinkAreRejectedWithoutFollowingTheirChildren(symbolic: True) (no symbolic link privilege).
  • Tray tests, with the OPENCLAW_TRAY_* directories isolated: 4799 passed, 0 failed.
  • Connection tests: 1691 passed, 3 failed, 7 skipped. The same 3 fail on this host without this change: StoreMigrationPackagePresenceTests.DeletedReceipt_WithoutStorePackage_ReportsNoMigration(removeDirectory: False) and two MigrationRecordTests.WindowsPowerShellChecker_UsesTheSameContract cases.
  • KeepAlive_PeerStopsAnsweringPings_ReconnectsOnFreshSocket times out without KeepAliveTimeout, and fails on the missing Disconnected without the listen loop change. KeepAlive_PeerAnswersPings_KeepsTheConnection passes in all three states. AbortCurrentWebSocket_PreventsLaterMessagesOnAcceptedSocket now also asserts that a client abort stays silent.

Real Behavior Proof

  • Environment tested: Windows 11 x64 build 26200 (tr-TR), Node with [email protected] on loopback.
  • PR head or commit tested: a4dd026 plus this change. CI on the PR head is the current-head result.
  • Exact steps or command run: start the server, which freezes 75 seconds after a connection, then connect TestWebSocketClient with the production keep-alive values and log each status change with its time. Repeated with KeepAliveTimeout not set.
  • Evidence after fix:
server 22:51:28 ping 1, automatic pong
server 22:52:05 ping 2, automatic pong
server 22:52:13 freezing the event loop
client t+142,5s status Disconnected
client t+142,5s status Connecting
client t+158,8s status Error
  • Observed result: a healthy server keeps the connection through two ping rounds, and a frozen one is detected 67 seconds after the freeze.
  • Screenshot or artifact links verified? (Yes/No/N/A): N/A
  • Not verified or blocked:
    • A real Gateway. The server is a stand-in using the Gateway's WebSocket library.
    • Real sleep and wake, and a real network or Tailscale drop.
    • How often a real Gateway's event loop stalls for more than 30 seconds, and how long real message handlers block the receive loop.

Security Impact

  • New permissions or capabilities? (No)
  • Secrets or tokens handling changed? (No)
  • New or changed network calls? (No)
  • Command or tool execution surface changed? (No)
  • Data access scope changed? (No)
  • If any answer is Yes, explain the risk and mitigation:

Compatibility and Migration

  • Backward compatible? (Yes)
  • Config or environment changes? (No)
  • Migration needed? (No)
  • If yes, list the exact upgrade steps:

Review Conversations

  • I replied to or resolved every bot review conversation addressed by this PR.
  • I left unresolved only conversations that still need maintainer judgment.

Worked on by

Worked on by:
- @MertBasar0

Co-authored-by: MertBasar0 <[email protected]>
OpenClaw-Publication: 7c692efe-bf23-4b71-91ab-8beb4e088c1c
@clawsweeper

clawsweeper Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

🦞👀
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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 message-delivery 🚨 Merging this PR could drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 1, 2026
@clawsweeper

clawsweeper Bot commented Nov 1, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge.

What this changes

This PR adds WebSocket ping timeouts and reports unexpected timeout cancellation as a disconnect before reconnecting.

Example: A Gateway stops responding while its TCP connection remains open.

  • Before: The reported production-client measurement remained connected for 165 seconds after the freeze.
  • After: The supplied patched-client trace reports Disconnected and starts reconnecting 67 seconds after the freeze.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A useful, focused patch with meaningful real-transport evidence; required product-path validation is incomplete, and the failed Shared CI step cannot yet be attributed.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Companion can continue reporting a connection to an unresponsive Gateway indefinitely while TCP remains open.
Reason: The reported failure is concrete, the shared repair benefits both client roles, and the supplied maintainer-authored direction establishes the timeout choice.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a concrete liveness defect still present on main, with a focused implementation and no definite introduced code defect found.

Priority: P2
Reviewed head: 29b9ea469206289cb1f314491c6eb7fec5bb4716

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The declared windows-wsl-gateway-e2e pool and latest-stable upgrade compatibility run remain unverified; the body reports intended base-fail/head-pass transport regressions.
Agent review details

How this fits together

WebSocketClientBase owns transport lifecycle for both operator and Windows node clients, converting received frames and socket failures into message handling, connection status, cleanup, and authorized reconnect attempts.

flowchart LR
  Gateway[Gateway WebSocket peer] --> Transport[WebSocketClientBase]
  Transport --> Operator[Operator client]
  Transport --> Node[Windows node client]
  Transport --> Cleanup[Disconnect cleanup]
  Cleanup --> Recovery[Existing reconnect authorization and backoff]
Loading

Technical review

Best possible solution:

Keep bounded protocol liveness and generation-scoped disconnect cleanup in WebSocketClientBase while preserving intentional aborts and existing reconnect authorization.

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

Current-main source establishes the missing response deadline, and MertBasar0 supplies before/after real-client traces against a frozen ws peer; this read-only review ran no reproduction, build, or tests.

Is this the best way to solve the issue?

A finite protocol timeout addresses the missing liveness check in the shared owner, with generation-scoped abort tracking preserving silent intentional recovery and distinct tests supporting each changed boundary.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared keep-alive configuration changes intended behavior with a stated reason (76f7811: The shared lifecycle extraction carried a 30-second KeepAliveInterval into the base class; its stated purpose was lifecycle ownership and deduplication, with no documented decision requiring an infinite response timeout.)
  • Generation-fenced receive lifecycle keeps the original intent (17d0637: Connection-generation guards prevent stale listeners from processing messages or changing newer connection state; the new timeout cleanup retains that fence.)
  • Intentional socket abort keeps the original intent (603886a: Credential handoff failures abort only the owning socket and retain reconnect ownership; generation tracking preserves the existing silent-abort behavior.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Barbara Kudiess: Raw commit 603886a adds src/OpenClaw.Shared/WebSocketClientBase.cs:264 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 603886a81d34; files: src/OpenClaw.Shared/WebSocketClientBase.cs)

Review metrics

Metric Value Why it matters
Production and test delta Production +28/-1; tests +55/-0 The growth stays in the existing transport owner and suite, protecting silent-peer recovery, responsive-peer stability, and intentional-abort silence.

Labels

Label changes:

  • add P2: A focused connection-recovery bug has concrete source and transport evidence without evidence of a widespread urgent outage.
  • add merge-risk: 🚨 message-delivery: The maintainer-authored direction acknowledges that receive-handler or Gateway event-loop stalls exceeding the deadline can disconnect a healthy peer and discard queued messages.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: A focused connection-recovery bug has concrete source and transport evidence without evidence of a widespread urgent outage.
  • merge-risk: 🚨 message-delivery: The maintainer-authored direction acknowledges that receive-handler or Gateway event-loop stalls exceeding the deadline can disconnect a healthy peer and discard queued messages.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete the declared WSL Gateway proof and verify recovery after upgrading the latest stable installation with settings and identities retained.
  • Inspect the failed Core and CLI job results to distinguish a patch regression from an existing failure.

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 execution lanes are retired.

Reviewed October 31, 2026, 8:31 PM ET / November 1, 2026, 00:31 UTC.

@shanselman
shanselman merged commit 0cfeaeb into main Nov 3, 2026
50 of 53 checks passed
@shanselman
shanselman deleted the openclaw/gateway-unresponsive-peer-pr branch November 3, 2026 21:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 message-delivery 🚨 Merging this PR could drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

Companion stays connected when the Gateway stops responding but TCP stays open

2 participants