Skip to content

Bound WebSocket reconnect attempts - #1352

Merged
shanselman merged 2 commits into
mainfrom
pr/1344
Sep 7, 2026
Merged

shanselman merged 2 commits into
mainfrom
pr/1344

Conversation

@shanselman

@shanselman shanselman commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Fixes #1344.

A gateway peer can accept TCP but never complete the WebSocket HTTP upgrade. WebSocketClientBase.ConnectAsync previously awaited ClientWebSocket.ConnectAsync with only the client lifetime token, so one stalled attempt could block the single reconnect loop forever and leave node mode stuck at Connecting until the tray process was force-killed.

Fix

  • bound each WebSocket HTTP upgrade attempt to 15 seconds using a token linked to the client lifetime
  • abort and dispose a timed-out socket, classify it as a network timeout, raise the existing Error status, and continue the existing backoff loop
  • keep shutdown cancellation distinct from an attempt timeout, so disposal does not surface a false error or schedule reconnect
  • bind reconnect work to its socket and generation instead of starting an ownerless retry
  • atomically validate reconnect ownership when publishing a replacement socket
  • re-check ownership after asynchronous endpoint authorization, including denied results, so stale authorization cannot overwrite a newer healthy connection
  • preserve the existing single-flight handoff where the active loop may adopt a newer null or closing transport, while a newer open socket remains authoritative
  • continue the active reconnect loop when a newer manual attempt supersedes an in-flight retry but also fails and cannot acquire the single-flight gate itself

Required proof pools

  • windows-wsl-gateway-e2e: verified on current head by real Gateway stop/start recovery and three repeated Gateway restart recoveries.

Validation

Current head: 8134a76e.

  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore --filter "FullyQualifiedName~WebSocketClientBaseTests": 35 passed per run, repeated 5 consecutive times
  • .\build.ps1: passed
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore: 3,943 passed, 32 skipped
  • dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore: 2,860 passed
  • dotnet test .\tests\OpenClaw.Connection.Tests\OpenClaw.Connection.Tests.csproj --no-restore: 718 passed
  • git diff --check: passed
  • GitHub run 34133976203: CI Gate, setup/connect E2E, network recovery E2E, revocation recovery E2E, core/CLI, tray/setup/integration, UI/accessibility, CodeQL, and security checks passed
  • the initial broad tray/setup run hit the unrelated CommandRunnerTests.RunAsync_ReturnsWhenDescendantKeepsOutputPipesOpen timing flake at 5.81 seconds against a 5-second assertion; the failed job rerun passed
  • required rubber-duck review completed; concrete reconnect-ownership races were accepted and fixed
  • final python .agents\skills\autoreview\scripts\autoreview --mode local --stream-engine-output: clean, no accepted/actionable findings
  • ClawSweeper current-head review: ready for maintainer review, no findings, proof sufficient

Real behavior proof

The focused suite uses a real loopback TCP peer, not a mocked ClientWebSocket:

  • the peer accepts the TCP connection and reads the complete WebSocket upgrade request, but deliberately sends no HTTP response
  • the client reaches its test-scoped attempt deadline, aborts the socket, and the peer observes that first client close
  • the reconnect loop advances through backoff and the peer receives a second complete upgrade request
  • disposing during the same stalled upgrade produces no timeout, Error status, or reconnect
  • a manual connection that succeeds while the timed-out retry is in backoff remains open and receives a message after the stale retry wakes
  • the same newer-socket protection is proven while reconnect authorization is blocked, for both allowed and denied authorization results
  • a four-attempt sequence proves recovery is not abandoned when retry A stalls, newer manual attempt B supersedes it and fails, B cannot acquire the occupied single-flight gate, and A must continue to a final successful upgrade
  • all 35 transport tests passed in five consecutive runs

Current-head GitHub Network recovery E2E passed both real WSL Gateway scenarios:

  • GatewayStopAndStart_TrayLeavesReadyThenRecovers: passed in 25 seconds
  • RepeatedGatewayRestart_TrayAndNodeRecoverEachTime: passed in 55 seconds, covering three consecutive Gateway restarts
  • complete network recovery shard: 2 passed

The original intermittent remote-LAN incident and reporter dump were not independently reproduced. The deterministic peer directly reproduces the source-level failure mode shown by the dump: TCP is accepted while ClientWebSocket waits indefinitely for the HTTP upgrade response.

Review notes

ClawSweeper identified a lost-recovery handoff when a newer manual attempt superseded an in-flight retry and also failed. That finding was accepted and fixed with the four-attempt real-loopback regression above. Its current-head review reports no findings and marks the PR ready for maintainer review.

An earlier autoreview TOCTOU finding was rejected after tracing the locked state transition. It assumed disposing a newer closing socket would make atomic publication reject the retry and leave the client disconnected. The implementation intentionally permits the active single-flight loop to adopt a null or closing transport; only a newer open or connecting socket blocks publication. Existing and new tests prove both the closing-socket handoff and newer-open-socket preservation. The final structured autoreview is clean.

Security impact

No credential or endpoint-authorization policy changes. Authorization still runs before every client-owned reconnect. The change only bounds transport establishment and prevents stale retry or authorization work from replacing a newer healthy socket.

Add a per-attempt HTTP upgrade deadline, abort timed-out sockets, and preserve reconnect ownership across manual connection and authorization races.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 4f97b3a3-def7-4f33-b7d5-ece171b4fd0b
@clawsweeper

clawsweeper Bot commented Sep 7, 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.

@shanselman shanselman added the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Sep 7, 2026
@clawsweeper clawsweeper Bot added P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 7, 2026
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed September 7, 2026, 10:41 AM ET / 14:41 UTC.

ClawSweeper review

What this changes

Bounds WebSocket connection attempts to 15 seconds, preserves retry ownership across concurrent connections, and adds real-loopback regression coverage.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: main and the latest release still allow an unbounded WebSocket upgrade wait. The previous lost-recovery finding is addressed, and no remaining blocking code defect was found.

Priority: P0
Reviewed head: 8134a76e89d9e5e00281ff0b2840f023bfcd4751

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused transport proof and the repaired recovery handoff support normal good patch quality; pending CI is separate from that assessment.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied current-head results exercise WebSocketClientBase with the real ClientWebSocket against a controlled TCP peer, observing timeout closure, subsequent upgrade requests, and message delivery after recovery. This supports the internal transport change; the separately declared gateway recovery E2E remains pending in the captured context.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied current-head results exercise WebSocketClientBase with the real ClientWebSocket against a controlled TCP peer, observing timeout closure, subsequent upgrade requests, and message delivery after recovery. This supports the internal transport change; the separately declared gateway recovery E2E remains pending in the captured context.
Evidence reviewed 8 items Main still needs the fix: The fetched main implementation awaits ClientWebSocket.ConnectAsync with only the client lifetime token. The existing backoff cannot advance while that await remains stalled.
Latest release also lacks the deadline: Source at the supplied latest release, v2026.7.1-4, likewise passes only the lifetime token to the WebSocket upgrade.
Previous recovery blocker addressed: When an attempted reconnect returns null, the active loop now continues if the current transport is eligible for recovery. The new four-attempt regression covers stalled initial connection, stalled retry, failed superseding manual connection, and successful recovery with message receipt. This addresses the concrete previous-review scenario. Direct comparison with the earlier head was unavailable because its source blob was missing locally.
Findings None None.
Security None None.

How this fits together

The shared WebSocket transport connects Windows Companion’s operator and node clients to a gateway. It establishes the connection, delivers incoming messages, and retries unexpected connection failures.

flowchart TD
  A[Operator and node clients] --> B[WebSocket connection attempt]
  B --> C{Upgrade completes within deadline?}
  C -->|Yes| D[Receive gateway messages]
  C -->|No| E[Dispose socket and report timeout]
  E --> F[Backoff and endpoint authorization]
  F --> G{Retry still owns recovery?}
  G -->|Yes| B
  G -->|No| D
Loading

Before merge

None.

Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production and test growth production +127 net lines; tests +461 lines Production growth implements bounded attempts and recovery ownership; six new transport regressions and their TCP harness provide focused coverage.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #1344
Summary: This PR is the explicit implementation candidate for the reported stalled WebSocket upgrade.

Members:

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

Technical review

Best possible solution:

Keep automatic recovery bounded at transport establishment while preserving shutdown cancellation, endpoint authorization, and newer healthy connections.

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

Yes: a TCP peer that accepts the upgrade request but withholds its HTTP response reaches the unbounded await on main. The inspected loopback harness exercises that mechanism; this review did not execute it or independently reproduce the original LAN incident.

Is this the best way to solve the issue?

Yes: the deadline belongs in the shared transport, and the revised ownership handoff addresses the prior finding without adding another reconnect mechanism or changing stored settings.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied current-head results exercise WebSocketClientBase with the real ClientWebSocket against a controlled TCP peer, observing timeout closure, subsequent upgrade requests, and message delivery after recovery. This supports the internal transport change; the separately declared gateway recovery E2E remains pending in the captured context.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.
  • remove merge-risk: 🚨 availability: Current PR review selected no merge-risk labels.

Label justifications:

  • P0: The linked official-release report describes indefinitely blocked gateway recovery requiring process termination, leaving node mode unusable.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied current-head results exercise WebSocketClientBase with the real ClientWebSocket against a controlled TCP peer, observing timeout closure, subsequent upgrade requests, and message delivery after recovery. This supports the internal transport change; the separately declared gateway recovery E2E remains pending in the captured context.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied current-head results exercise WebSocketClientBase with the real ClientWebSocket against a controlled TCP peer, observing timeout closure, subsequent upgrade requests, and message delivery after recovery. This supports the internal transport change; the separately declared gateway recovery E2E remains pending in the captured context.

Evidence

What I checked:

  • Main still needs the fix: The fetched main implementation awaits ClientWebSocket.ConnectAsync with only the client lifetime token. The existing backoff cannot advance while that await remains stalled. (src/OpenClaw.Shared/WebSocketClientBase.cs:262, 2bdcfc253310)
  • Latest release also lacks the deadline: Source at the supplied latest release, v2026.7.1-4, likewise passes only the lifetime token to the WebSocket upgrade. (src/OpenClaw.Shared/WebSocketClientBase.cs, c7c6fb06be03)
  • Previous recovery blocker addressed: When an attempted reconnect returns null, the active loop now continues if the current transport is eligible for recovery. The new four-attempt regression covers stalled initial connection, stalled retry, failed superseding manual connection, and successful recovery with message receipt. This addresses the concrete previous-review scenario. Direct comparison with the earlier head was unavailable because its source blob was missing locally. (src/OpenClaw.Shared/WebSocketClientBase.cs:659, 8134a76e89d9)
  • Production transport exercised through a real TCP peer: The inspected harness reads actual HTTP upgrade requests, deliberately stalls or closes connections, completes a real WebSocket upgrade, and sends a message through the recovered socket. The supplied PR body reports all 35 transport tests passing five times on this head, including shutdown cancellation and preservation of newer connections during backoff and authorization. (tests/OpenClaw.Shared.Tests/WebSocketClientBaseTests.cs:522, 8134a76e89d9)
  • Validation and proof continuity: The captured body at sourceRevision 7cc17c95af11fac63da263256d066693611520625cbf5760b0b72e4c8a7df0fe reports a passing build, Shared tests (3,943 passed, 32 skipped), Tray tests (2,860 passed), and Connection tests (718 passed). It explicitly records current-head Network recovery E2E as pending and distinguishes the previous head’s successful gateway restart scenarios. Live GitHub refresh failed because the API was unreachable; no newer result is claimed. No builds, tests, or bundled review helpers were executed during this read-only review. (8134a76e89d9)
  • Related report establishes user impact: Windows Companion can hang forever in ClientWebSocket.ConnectAsync after gateway restart; node mode never reconnects #1344 reports the official released Companion remaining stuck after gateway restart, with a dump awaiting the HTTP upgrade and recovery requiring process termination. This PR explicitly owns that repair; the issue remains open.

Likely related people:

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

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-07T14:02:04.892Z sha 87dd17f :: blocked before merge. :: [P2] Retain recovery when a newer failed connection supersedes a retry

Keep the active reconnect loop running when a newer manual connection supersedes it but also fails, while still yielding to newer open sockets.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 4f97b3a3-def7-4f33-b7d5-ece171b4fd0b
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. labels Sep 7, 2026
@shanselman
shanselman merged commit d4707db into main Sep 7, 2026
25 checks passed
@shanselman
shanselman deleted the pr/1344 branch September 7, 2026 15:00
@shanselman shanselman removed the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

Windows Companion can hang forever in ClientWebSocket.ConnectAsync after gateway restart; node mode never reconnects

1 participant