Skip to content

Concurrency: CloseWebSocketAsync skips _sendLock — a close racing an in-flight send throws and skips the graceful close #1019

Closed

Description

@anagnorisis2peripeteia

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 logs Error during disconnect: …, then falls through to ClearPendingRequests + status change; the socket is later torn down hard by Dispose.
  • WindowsNodeClient pairing-approval refresh (L411) — closes the socket to force a fresh handshake after approval; an exception propagates to ProcessMessageAsync'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 outstanding SendAsync) is thrown and the close handshake is skipped — the socket never reaches CloseSent.
  • 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:

  1. Which token to acquire with — _cts.Token is cancelled during Dispose, but DisconnectAsync must still be able to close gracefully; CloseWebSocketAsync currently uses CancellationToken.None.
  2. 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 InvalidOperationException and no shutdown warning.
  • No new deadlock: close still completes promptly when the lifetime token is already cancelled (dispose path), and DisconnectAsync stays bounded.

Activity

  1. added
    P2
    impact:other
    issue-rating: 🐚 platinum hermit
    clawsweeper:needs-live-repro
    clawsweeper:no-new-fix-pr
    clawsweeper:needs-maintainer-review
    on Jul 18, 2026
  2. clawsweeper commented on Jul 18, 2026

    @clawsweeper

    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 SendAsync in flight while a test subclass calls CloseWebSocketAsync. 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

    • Question: For a disconnect that races a send which never completes, should graceful close wait indefinitely for _sendLock, or should it use a bounded wait and then fall back to teardown?
    • Rationale: The bug fix is narrow, but the timeout/fallback contract changes operator-visible disconnect behavior and cannot be selected safely from the current source report alone.
    • Likely owner: anagnorisis2peripeteia — They supplied the detailed lifecycle analysis and a deterministic proposed reproduction, though current-main file ownership could not be established from the available history evidence.
    • Options:
      • Use a bounded graceful-close wait (recommended): Wait briefly for an active send to drain, perform the close handshake when it does, then use the existing teardown path when it does not.
      • Always wait for the active send: Maximize graceful close completion, accepting that a stalled send may block disconnect indefinitely.
    Review details

    Best possible solution:

    Define a bounded, shutdown-safe close-wait policy, then serialize the socket state check and CloseAsync behind 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 SendAsync in flight while a test subclass calls CloseWebSocketAsync. 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:

    • Taking _sendLock with 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:

    • add 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.
    • add impact:other: The concrete impact is skipped graceful WebSocket teardown and a misleading warning, outside the more specific owned impact classes.
    • add issue-rating: 🐚 platinum hermit: Current issue advisory state selects this label.
    • add clawsweeper:needs-live-repro: Current issue advisory state selects this label.
    • add clawsweeper:no-new-fix-pr: Current issue advisory state selects this label.
    • add 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:

    • Current-main locking asymmetry: At current main ee4817d2c2e7b509474d0979aa746a762448cd0c, SendRawAsync holds _sendLock across ClientWebSocket.SendAsync, while CloseWebSocketAsync calls CloseAsync without taking that lock; the report gives the concrete line-level current-main path. (src/OpenClaw.Shared/WebSocketClientBase.cs:409, ee4817d2c2e7)
    • Affected callers handle the exception but lose graceful teardown: The report traces current callers through gateway disconnect and Windows-node pairing refresh: they broadly catch/log the failure, avoiding a process crash but leaving a spurious shutdown warning and non-graceful teardown. (src/OpenClaw.Shared/OpenClawGatewayClient.cs:272, ee4817d2c2e7)
    • Related work is distinct: The closed umbrella report split this residual WebSocket hazard from its session snapshot and setup-cancellation fixes; merged pull request 1011 addressed the separate setup-cancellation path, not WebSocketClientBase close/send serialization. (d57047e08783)

    Likely related people:

    • anagnorisis2peripeteia: Reported this isolated residual hazard after tracing the related concurrency work and previously contributed the adjacent merged setup-cancellation repair. (role: recent related concurrency contributor; confidence: low; commits: d57047e08783; files: src/OpenClaw.Shared/WebSocketClientBase.cs, src/OpenClaw.SetupEngine/SetupSteps.cs)
    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.
  3. steipete commented on Jul 19, 2026

    @steipete
    Contributor

    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.

  4. locked as resolved and limited conversation to collaborators on Jul 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2clawsweeper:needs-live-reproclawsweeper:needs-maintainer-reviewclawsweeper:no-new-fix-primpact:otherissue-rating: 🐚 platinum hermit

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions