Repository navigation
Description
Split out of #1010 (residual hazard 1 of 3), per the maintainer status update there. Verified present on current main @ ee4817d.
The hazard
src/OpenClaw.Shared/WebSocketClientBase.cs — CloseWebSocketAsync (L471) vs SendRawAsync (L409).
SendRawAsync serializes all sends under _sendLock (L25), held across ws.SendAsync (acquire L413, release L466). CloseWebSocketAsync doesn't take it:
protected async Task CloseWebSocketAsync()
{
var ws = _webSocket;
if (ws?.State == WebSocketState.Open)
{
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Disconnecting", System.Threading.CancellationToken.None);
}
}ClientWebSocket permits only one outstanding send-side operation, and CloseAsync counts as one — a close issued while a SendAsync is in flight throws InvalidOperationException, and the graceful close handshake never happens.
Blast radius today (honest scope)
Both live call paths catch broadly and log, so this is a spurious shutdown warning plus a non-graceful teardown — not a crash:
OpenClawGatewayClient.DisconnectAsync(L272) — catches and logsError during disconnect: …, then falls through toClearPendingRequests+ status change; the socket is later torn down hard byDispose.WindowsNodeClientpairing-approval refresh (L411) — closes the socket to force a fresh handshake after approval; an exception propagates toProcessMessageAsync's catch-all (L255ff) and is logged, skipping the graceful close on exactly the path where a clean re-handshake matters most.
Deterministic reproduction (base-red / head-green)
Follow the #1011 loopback-harness pattern: a local WebSocket endpoint that accepts the upgrade and then never reads. Park a send deterministically by writing a frame large enough that TCP backpressure keeps SendAsync in flight (a few MB is ample against a non-reading peer). While the send is parked, call CloseWebSocketAsync() from a test subclass.
- Base (red):
InvalidOperationException(invalid state / already one outstandingSendAsync) is thrown and the close handshake is skipped — the socket never reachesCloseSent. - Fixed (green): the close serializes behind the in-flight send and completes the graceful handshake (state
CloseSent/Closed), no exception, no warning log.
Fix sketch
Take _sendLock in CloseWebSocketAsync around the state-check + CloseAsync, mirroring SendRawAsync's shutdown-tolerant acquire (its OperationCanceledException/ObjectDisposedException catches). Two design points for the PR to settle explicitly:
- Which token to acquire with —
_cts.Tokenis cancelled duringDispose, butDisconnectAsyncmust still be able to close gracefully;CloseWebSocketAsynccurrently usesCancellationToken.None. - Whether the close should bound its wait so a genuinely wedged send can't hold up disconnect indefinitely.
Acceptance criteria
- Regression test proving base-red / head-green per the repro above.
- A close racing an in-flight send completes the graceful close handshake with no
InvalidOperationExceptionand no shutdown warning. - No new deadlock: close still completes promptly when the lifetime token is already cancelled (dispose path), and
DisconnectAsyncstays bounded.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Projects
- StatusShow more project fieldsChannels
Activity
clawsweeper commentedon Jul 18, 2026
Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed July 18, 2026, 5:36 PM ET / 21:36 UTC.
Summary
This remains a concrete current-main shutdown race: send operations are serialized while graceful close is not, and no merged fix in the supplied related work addresses this WebSocket lifecycle path. Keep it open for a focused lifecycle-policy decision and regression fix.
Reproducibility: yes. from source with medium confidence: a loopback WebSocket peer that stops reading can keep
SendAsyncin flight while a test subclass callsCloseWebSocketAsync. The supplied report describes the expected base failure and head behavior, but no current-head execution was available in this read-only review.Next step
A focused fix is plausible, but a maintainer must first choose the bounded-versus-unbounded close wait contract so automation does not introduce a shutdown hang.
Maintainer decision needed
_sendLock, or should it use a bounded wait and then fall back to teardown?Review details
Best possible solution:
Define a bounded, shutdown-safe close-wait policy, then serialize the socket state check and
CloseAsyncbehind the send gate with deterministic loopback coverage for both an in-flight send and an already-cancelled lifetime path.Do we have a high-confidence way to reproduce the issue?
Yes, from source with medium confidence: a loopback WebSocket peer that stops reading can keep
SendAsyncin flight while a test subclass callsCloseWebSocketAsync. The supplied report describes the expected base failure and head behavior, but no current-head execution was available in this read-only review.Is this the best way to solve the issue?
Unclear until the disconnect wait policy is chosen. Serializing close with sends is the maintainable root-cause direction, provided the implementation also proves it remains bounded and cancellation-safe.
AGENTS.md: found and applied where relevant.
Remaining risk / open question:
_sendLockwith an unbounded wait could make disconnect hang behind a stalled send; cancellation semantics must preserve graceful close where possible without creating a shutdown deadlock.Codex review notes: model internal, reasoning high; reviewed against ee4817d2c2e7.
Label changes
Label changes:
P2: The race affects connection shutdown reliability and diagnostics but the traced callers catch it, so the report does not establish a crash, data-loss, or emergency outage.impact:other: The concrete impact is skipped graceful WebSocket teardown and a misleading warning, outside the more specific owned impact classes.issue-rating: 🐚 platinum hermit: Current issue advisory state selects this label.clawsweeper:needs-live-repro: Current issue advisory state selects this label.clawsweeper:no-new-fix-pr: Current issue advisory state selects this label.clawsweeper:needs-maintainer-review: Current issue advisory state selects this label.Label justifications:
P2: The race affects connection shutdown reliability and diagnostics but the traced callers catch it, so the report does not establish a crash, data-loss, or emergency outage.impact:other: The concrete impact is skipped graceful WebSocket teardown and a misleading warning, outside the more specific owned impact classes.Evidence reviewed
What I checked:
ee4817d2c2e7b509474d0979aa746a762448cd0c,SendRawAsyncholds_sendLockacrossClientWebSocket.SendAsync, whileCloseWebSocketAsynccallsCloseAsyncwithout taking that lock; the report gives the concrete line-level current-main path. (src/OpenClaw.Shared/WebSocketClientBase.cs:409, ee4817d2c2e7)src/OpenClaw.Shared/OpenClawGatewayClient.cs:272, ee4817d2c2e7)WebSocketClientBaseclose/send serialization. (d57047e08783)Likely related people:
src/OpenClaw.Shared/WebSocketClientBase.cs,src/OpenClaw.SetupEngine/SetupSteps.cs)How this review workflow works
@clawsweeper re-reviewcomments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.@clawsweeper re-reviewor@clawsweeper re-runon an open PR or issue to request a fresh review only.@clawsweeper reviewto request a fresh review only.@clawsweeper autofix,@clawsweeper automerge,@clawsweeper fix ci, or@clawsweeper address review.@clawsweeper explainto ask for more context, or@clawsweeper stopto stop active automation.steipete commentedon Jul 19, 2026
Fixed on main by #1023 at 2779365.
The merged repair serializes graceful close behind the send gate, preserves the intended socket across the wait, and handles cancellation/disposal without a double release or shutdown warning. Exact-head Windows proof covered the full build, 2 focused loopback WebSocket serialization tests, 2,903 shared tests, and 1,823 tray tests. Current main contains the merge commit, so closing this focused report as completed.