Skip to content

fix: avoid disconnect warnings during active WebSocket sends - #1023

Merged
shanselman merged 2 commits into
mainfrom
shanselman-serialize-websocket-close
Jul 18, 2026
Merged

shanselman merged 2 commits into
mainfrom
shanselman-serialize-websocket-close

Conversation

@shanselman

@shanselman shanselman commented Jul 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #1010

Additional instructions

MUST: Keep Allow edits from maintainers enabled for this PR so maintainers
can help update the branch when needed.

What Problem This Solves

Fixes an issue where users disconnecting a gateway, or a node refreshing its connection after pairing approval, could see a spurious shutdown warning when graceful WebSocket close raced an active send or when disposal canceled a close queued behind that send.

Why This Change Was Made

Graceful close now uses the existing send semaphore, captures the intended socket before waiting, and rechecks that socket's state after entering the critical section. Acquisition mirrors SendRawAsync: lifetime cancellation or disposal returns quietly before lock ownership, while the release finally is reachable only after a successful acquire.

The actual CloseAsync retains CancellationToken.None to preserve the existing graceful handshake during normal disconnect. Concurrent disposal still bounds an in-progress close by disposing the captured socket; any resulting mid-close failure remains on the pre-existing caller-contained path rather than broadening this PR into close-operation error policy.

User Impact

Gateway disconnect and pairing-refresh shutdown can now finish without ClientWebSocket rejecting a close that overlaps an active send, and routine disposal no longer turns a queued close-lock wait into a warning/error. No protocol, configuration, or public API changes.

Evidence

  • A deterministic loopback test holds the real send critical section, queues SendRawAsync, starts graceful close, and proves the close cannot overtake the send. The server must observe a text frame before the close frame.
  • A second test disposes the client while send and close are queued, then requires both tasks to complete within two seconds and the close task to be IsCompletedSuccessfully.
  • Red/green cancellation proof: without the acquire guard, CloseWebSocketAsync_DisposeCompletesQueuedCloseWithoutException fails with OperationCanceledException from SemaphoreSlim.WaitAsync; with the guard, both focused tests pass.
  • Follow-up rubber-duck review found no blocking issue; its comment-accuracy suggestion was addressed. Final read-only code review found no significant issue.
  • Structured autoreview bundle generation succeeded, but Codex CLI 0.137 produced no review result because its PATH hardening rejects the helper's isolated temporary CODEX_HOME; this is recorded as a tooling blocker rather than a clean autoreview claim.

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

Validation

  • .\build.ps1 — passed; 5/5 projects built.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --filter "FullyQualifiedName~WebSocketCloseSerializationTests" --no-restore --logger "console;verbosity=minimal" — passed 2, failed 0, skipped 0.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore --logger "console;verbosity=minimal" — passed 2,903, failed 0, skipped 31.
  • dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore --logger "console;verbosity=minimal" — passed 1,823, failed 0, skipped 0.
  • git diff --check — passed.

Real Behavior Proof

  • Environment tested: Windows 11, .NET SDK 10.0.302, loopback HttpListener/WebSocket transport.
  • PR head or commit tested: 5059a920abf34bfaa7c29b944d69606f391f3b38.
  • Exact steps or command run: focused WebSocketCloseSerializationTests command listed above.
  • Evidence after fix: 2/2 focused tests pass; the live loopback server observes the queued text frame before acknowledging graceful close, and disposal completes both queued operations successfully within the bounded timeout.
  • Observed result: close no longer overtakes an in-flight send; canceled/disposed semaphore acquisition returns quietly without deadlock, warning-shaped exception, or double-release.
  • Screenshot or artifact links verified? (Yes/No/N/A): N/A.
  • Not verified or blocked: Codex autoreview blocked by Codex CLI 0.137 rejecting autoreview's isolated temporary CODEX_HOME; no UI, MCP, or gateway runtime proof is applicable to this transport-level race.

Security Impact

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

Compatibility and Migration

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

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.

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

Copilot-Session: 92e601e0-3207-42f8-878a-5fc7efae1479
@clawsweeper clawsweeper Bot added 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. P2 Normal priority bug or improvement with limited blast radius. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed July 18, 2026, 6:15 PM ET / 22:15 UTC.

Summary
The branch serializes CloseWebSocketAsync with active sends, handles cancellation while waiting for the send semaphore, and adds two loopback regression tests for ordering and disposal.

Reproducibility: yes. from source and deterministic coverage: a SendRawAsync holding _sendLock can overlap the prior unguarded close path, and the new loopback tests exercise that ordering and disposal path. I did not execute the tests in this read-only review environment.

Review metrics: 2 noteworthy metrics.

  • Patch surface: 2 files affected; 177 additions, 2 deletions. The change is tightly scoped to one transport lifecycle method and one focused regression-test file.
  • Regression cases: 2 loopback tests added. They cover both send-before-close ordering and disposal while close waits for the shared semaphore.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P2] Wait for the remaining required CI checks and ordinary maintainer review on the current head.

Next step before merge

  • [P2] No discrete repair is required; maintainers should review the current head once the in-progress required checks finish.

Security
Cleared: The diff changes only WebSocket shutdown synchronization and test code; it adds no dependencies, permissions, secrets handling, artifact execution, or supply-chain surface.

Review details

Best possible solution:

Merge the focused shared-lock fix after ordinary maintainer review and the remaining required checks complete, retaining the two regression tests as the contract for close/send ordering and shutdown cancellation.

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

Yes, from source and deterministic coverage: a SendRawAsync holding _sendLock can overlap the prior unguarded close path, and the new loopback tests exercise that ordering and disposal path. I did not execute the tests in this read-only review environment.

Is this the best way to solve the issue?

Yes. Reusing the existing send semaphore is the narrowest maintainable fix because it preserves the established send serialization contract without adding protocol, configuration, or public API surface.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 9b5ce4bcc4f6.

Label changes

Label justifications:

  • P2: This fixes spurious disconnect warnings in a bounded gateway shutdown race without evidence of data loss, security impact, or core-runtime unavailability.
  • 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 PR provides current-head Windows loopback WebSocket evidence for both observed failure modes, including ordering at the server and successful completion during concurrent disposal.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR provides current-head Windows loopback WebSocket evidence for both observed failure modes, including ordering at the server and successful completion during concurrent disposal.
Evidence reviewed

What I checked:

Likely related people:

  • shanselman: The PR author also appears in merged project history for node-pairing safety work, and this change targets the gateway/pairing disconnect path; current-main ownership could not be further resolved because the read-only shell inspection was unavailable. (role: adjacent area contributor; confidence: low; commits: 5059a920abf3, 4377f32df366; files: src/OpenClaw.Shared/WebSocketClientBase.cs, tests/OpenClaw.Shared.Tests/WebSocketCloseSerializationTests.cs)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (1 earlier review cycle)
  • reviewed 2026-07-18T21:40:48.504Z sha 4377f32 :: needs maintainer review before merge. :: none

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

Copilot-Session: 92e601e0-3207-42f8-878a-5fc7efae1479
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. 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.

1 participant