Skip to content

Concurrency: SessionsUpdated snapshot aliases live state, and node-setup cancel logs a spurious failure + retry (+3 minor hazards) #1010

Closed

Description

@anagnorisis2peripeteia

Two concurrency-related bugs in the node's cross-platform code (OpenClaw.Shared / OpenClaw.SetupEngine / OpenClaw.Connection) — a SessionInfo data race and a setup-cancellation handling issue — each with a fix + regression test in a linked PR, plus three lower-severity hazards worth tracking. Separate from the disposal audit in #1003.

1. Cancelling node setup logs a spurious "connection failed" + burns a retry before it cancels

src/OpenClaw.SetupEngine/SetupSteps.cs — WaitForNodeConnection + PairNodeStep.ExecuteAsync. → fixed in #1011

WaitForNodeConnection links the caller's token with an internal CancelAfter(timeout), then catches every OperationCanceledException as a timeout:

using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(timeout);
return await tcs.Task.WaitAsync(cts.Token);
...
catch (OperationCanceledException)   // caller-cancel and internal-timeout are indistinguishable here
{
    return new NodeConnectionResult(NodeConnectionOutcome.Timeout);
}

and the live caller PairNodeStep.ExecuteAsync wraps the whole thing in a catch-all that re-swallows the cancellation:

catch (Exception ex)
{
    return StepResult.Fail($"Node pairing failed: {ex.Message}", ex);
}

So a user abort is turned into a StepResult.Fail, which PairNodeStep's retry policy (MaxAttempts: 3) then retries — and only the retry's Task.Delay(..., ct) tripping on the cancelled token gets the pipeline to Cancelled. Honest scope (traced end-to-end): the final outcome is Cancelled/exit 3 either way — the retry masks it. What's wrong is the path: on cancel the node step logs a misleading [Warn] Step 'pair-node' failed (attempt 1/3), retrying in 3s: Node connection failed: Timeout and wastes a retry delay before cancelling, and the journal records a connection "failure" that never happened. (My first read of this overstated it as a Failed-vs-Cancelled outcome bug; driving the real pipeline showed the outcome is unchanged — corrected here and in #1011.)

Repro + fix (#1011): a loopback WebSocket that completes the upgrade then stays silent parks WaitForNodeConnection in its wait; cancelling the caller token 300 ms in, base logs the spurious failure + retry then cancels, HEAD cancels immediately. The two-layer fix guards the timeout mapping with when (!ct.IsCancellationRequested) and adds the file's existing cancel-rethrow idiom (SetupSteps.cs:1725, :2044) to PairNodeStep, with paired red→green tests + the real-pipeline log capture.

2. The SessionsUpdated snapshot aliases live, lock-protected SessionInfo state

src/OpenClaw.Shared/OpenClawGatewayClient.cs — GetSessionListInternal. → fixed in #1012 (low severity — see below)

The snapshot copies the array but hands out the same SessionInfo references the map holds:

var arr = new SessionInfo[_sessions.Count];
_sessions.Values.CopyTo(arr, 0);   // elements are the live tracked objects

UpdateTrackedSession then mutates those same objects in place under _sessionsLock (session.CurrentActivity = ...; session.LastSeen = ...), while SessionsUpdated subscribers read the snapshot's fields with no lock. A delivered snapshot is a live alias of state another thread keeps mutating — a data race on CurrentActivity/LastSeen/Status, so a consumer (the tray's session views) can observe torn/shifting values.

Repro + fix (incoming): deterministic, no threads — capture a SessionInfo from one GetSessionList() snapshot, issue a second update for the same key, and the captured object's CurrentActivity flips from "compiling" to "running-tool" under the holder. Fix hands out a defensive copy (arr[i] = arr[i].Clone(), a SessionInfo.Clone() via MemberwiseClone).

Lower-severity hazards (tracking, not yet fixed)

  • WebSocketClientBase.CloseWebSocketAsync isn't mutually exclusive with sends — src/OpenClaw.Shared/WebSocketClientBase.cs (CloseWebSocketAsync vs SendRawAsync). SendRawAsync holds _sendLock across ws.SendAsync; CloseWebSocketAsync skips it. ClientWebSocket forbids a CloseAsync while a SendAsync is outstanding, so a shutdown racing an in-flight send throws InvalidOperationException and skips the graceful close. Both callers (DisconnectAsync, the node's pairing-reconnect path) currently catch + log it → a spurious shutdown warning today, not a crash. Fix: take _sendLock in CloseWebSocketAsync.
  • NodeConnector.ForwardIfCurrent raises events while holding _clientLifecycleLock — src/OpenClaw.Connection/NodeConnector.cs. Subscriber delegates (StatusChanged, PairingStatusChanged, …) are invoked inside the same lock every lifecycle op (Connect/Dispose/DisconnectIfCurrent) takes; a slow or re-entrant subscriber would stall lifecycle transitions. Handlers are fast today. Fix: snapshot-and-raise outside the lock.
  • Wizard-request timeout is bound to the client-lifetime token — src/OpenClaw.Shared/OpenClawGatewayClient.cs, SendWizardRequestAsync. Task.Delay(timeoutMs, _cts.Token) means a dispose-during-request can surface as TimeoutException rather than a cancellation. Largely mitigated by ClearPendingRequests faulting the pending completion with OperationCanceledException; a dedicated per-request timeout CTS would close the window.
Other sites reviewed — no change needed

These came up while tracing the above and were checked and left as-is:

Site Considered Why it's safe
NodeConnector client swap use-after-close Generation counter + DisconnectIfCurrent on cancel + ThrowIfNotCurrent under lock before ClientCreated.
NodeConnector._client getters data race Reference reads are atomic; worst case is a slightly-stale reference, which is intended.
GatewayConnectionManager.StartNodeConnectionAsync unsafe cutover A failed previous-node disconnect sets preStartBlocker and surfaces via BlockNodeStartAsync — reported, not silently swallowed; generation guards retry.
OpenClawGatewayClient mode flags (_operatorReadScopeUnavailable, _usageStatusUnsupported, _authFailed) data race Atomic bool reads; benign eventual consistency (at worst one extra request).
WindowsNodeClient.SendNodeEventAsync connected-check TOCTOU Inherent network TOCTOU; a send on a just-closed socket throws and is handled.
WindowsNodeClient bool state fields data race Atomic bool reads; same benign eventual consistency.
McpHttpServer stop/drain use-after-close A handler registered just after the drain snapshot is born from a linked CTS off the already-cancelled _cts, so it self-cancels immediately.
McpHttpServer.Start IsListening check TOCTOU Not concurrently reachable (single lifecycle owner); the guard is idempotent.
RecordAppliedTargetAsync install-state RMW data race Runs in the sequential setup pipeline; AtomicFile makes the write atomic. Only concurrent setup processes would race, which isn't the model.
StartKeepaliveStep existing-keepalive check TOCTOU Setup step runs single-threaded; no concurrent actor.

Activity

  1. anagnorisis2peripeteia commented on Jul 17, 2026

    @anagnorisis2peripeteia
    ContributorAuthor

    Fix PRs: #1011 for item 1 (setup-cancel cleanliness — corrected scope: it removes a spurious "connection failed" warning + a wasted retry on user-cancel; the final outcome was Cancelled either way, which I over-stated in the first draft and fixed after driving the real pipeline). The item-2 fix (SessionsUpdated snapshot defensive copy) is up next as a separate small PR.

  2. changed the title [-]Concurrency audit of the cross-platform node: 2 proven races + 3 latent hazards; 10 candidates cleared[/-] [+]Concurrency: node-setup cancel misreported as Timeout/Failed, and the SessionsUpdated snapshot aliases live state (+3 minor hazards)[/+] on Jul 17, 2026
  3. added
    P2
    impact:session-state
    impact:ux-friction
    issue-rating: 🦞 diamond lobster
    clawsweeper:source-repro
    on Jul 17, 2026
  4. clawsweeper commented on Jul 17, 2026

    @clawsweeper

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed July 17, 2026, 11:57 AM ET / 15:57 UTC.

    Summary
    Keep this issue open: both central bugs remain on the reviewed main SHA and are owned by open focused PRs, while three distinct lower-severity hazards remain unresolved.

    Likely related people

    • sytone — high confidence from prior substantial work on the shared gateway and WebSocket client.
    • Scott Hanselman — low-confidence adjacent routing candidate for the cross-cutting Windows setup and connection surfaces.

    Reproducibility: yes. at source level for the two central bugs: exact current-main paths and deterministic base-red/head-green checks are supplied by the linked PRs. The three additional hazards do not yet have equally strong reproduction evidence.

    Root-cause cluster
    Relationship: canonical
    Canonical: #1010
    Summary: This umbrella is the canonical report for two proven bugs and three adjacent hazards; each open PR is a candidate fix for one proven subproblem.

    Members:

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

    Next step
    Do not dispatch a single repair from this umbrella: two open PRs already own the proven bugs, and the remaining hazards need separate reproduction and scope.

    Review details

    Best possible solution:

    Land or close the two focused candidate PRs independently, then convert each still-valid minor hazard into a separate narrowly evidenced issue and close this umbrella only after those relationships are explicit.

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

    Yes at source level for the two central bugs: exact current-main paths and deterministic base-red/head-green checks are supplied by the linked PRs. The three additional hazards do not yet have equally strong reproduction evidence.

    Is this the best way to solve the issue?

    Yes for the two proven bugs: separate focused PRs are the narrowest maintainable fixes and match repository policy. The three hazards should not be silently bundled into either PR without independent proof and scope.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • The WebSocket close/send, NodeConnector event-under-lock, and wizard-timeout items are plausible source hazards but lack the deterministic current-main reproduction supplied for the two central bugs.
    • Keeping all five topics permanently in one umbrella could obscure whether the three remaining hazards are accepted, separately fixed, or intentionally left unchanged.

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

    Label changes

    Label justifications:

    • P2: Two bounded existing-behavior bugs have limited blast radius, while the remaining hazards are lower severity and not demonstrated as urgent regressions.
    • impact:session-state: The delivered SessionsUpdated objects can continue changing after snapshot capture, exposing mixed or stale session fields to consumers.
    • impact:ux-friction: A user cancellation during setup is logged as a connection failure and takes an unnecessary retry path before cancellation completes.
    Evidence reviewed

    What I checked:

    Likely related people:

    • sytone: Historical merged work substantially expanded OpenClawGatewayClient and WebSocketClientBase, directly overlapping the session and close/send paths in this report. (role: shared gateway feature contributor; confidence: high; commits: 98f48c2ef966; files: src/OpenClaw.Shared/OpenClawGatewayClient.cs, src/OpenClaw.Shared/WebSocketClientBase.cs)
    • Scott Hanselman: Repository and release history connect Scott Hanselman to the Windows companion project; evidence is weaker for these exact methods but supports escalation for behavior spanning setup and connection components. (role: adjacent repository owner; confidence: low; files: src/OpenClaw.SetupEngine/SetupSteps.cs, src/OpenClaw.Connection/NodeConnector.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.
  5. changed the title [-]Concurrency: node-setup cancel misreported as Timeout/Failed, and the SessionsUpdated snapshot aliases live state (+3 minor hazards)[/-] [+]Concurrency: SessionsUpdated snapshot aliases live state, and node-setup cancel logs a spurious failure + retry (+3 minor hazards)[/+] on Jul 17, 2026
  6. anagnorisis2peripeteia commented on Jul 17, 2026

    @anagnorisis2peripeteia
    ContributorAuthor

    #1012 now open for item 2 (SessionsUpdated snapshot defensive copy) — genuine unsynchronized data race, low severity (x64 field reads are atomic, so the symptom is stale/mixed values in the session UI rather than a torn read), deterministic red→green regression test. Both fixes for this issue are now up: #1011 (setup-cancel cleanliness) and #1012 (snapshot isolation).

  7. shanselman commented on Jul 18, 2026

    @shanselman
    Collaborator

    GitHub Copilot maintainer-assistant status update — automated, not written personally by Scott.

    The two primary bugs in this umbrella are now fixed and merged:

    The issue should not be closed as fully addressed yet because the three lower-severity hazards listed in the body remain present on current main:

    1. WebSocketClientBase.CloseWebSocketAsync still calls ClientWebSocket.CloseAsync without taking _sendLock, while SendRawAsync holds that lock across SendAsync. A close/send race can still produce the documented invalid-state warning and skip graceful close.
    2. NodeConnector.ForwardIfCurrent still invokes subscriber delegates while holding _clientLifecycleLock. The source now explicitly documents that subscribers must be synchronous and must not block/re-enter lifecycle work, but the stall/reentrancy hazard remains by design.
    3. OpenClawGatewayClient.SendWizardRequestAsync still races completion.Task against Task.Delay(timeoutMs, CancellationToken), where CancellationToken is tied to client lifetime. Client disposal can therefore still be classified as TimeoutException if the delay wins before pending-request cleanup faults the completion.

    Recommended next step: split these three into focused issues with deterministic reproductions/acceptance criteria, link them here, then close this umbrella as the two proven bugs are landed and the residual risks are separately tracked. Until then, keeping #1010 open is accurate.

  8. anagnorisis2peripeteia commented on Jul 18, 2026

    @anagnorisis2peripeteia
    ContributorAuthor

    Done as recommended above — the three residual hazards are now split into focused issues, each re-verified on current main @ ee4817d with a deterministic reproduction design and acceptance criteria:

    Closing this umbrella: the two proven bugs are fixed and merged (#1011, #1012), and the residual risks are now separately tracked.

  9. shanselman commented on Jul 18, 2026

    @shanselman
    Collaborator

    Hazard 2 resolution: ForwardIfCurrent dispatch-under-lock

    Verdict: no code change to ForwardIfCurrent is warranted. PR #1022 adds tests and documentation to harden the existing invariant.

    Investigation summary

    1. No deadlock — Lock ordering is consistent: _clientLifecycleLock is the outermost lock in the connector's acquisition graph. Subscriber-owned locks (_telemetryLock, GatewayRegistry._lock, ConnectionDiagnostics._lock, NodeService._clientLock/_capabilitiesLock) never re-enter _clientLifecycleLock. Verified by tracing every lock acquisition site in the codebase.

    2. No reentrancy corruption — No subscriber synchronously calls back into NodeConnector from inside ForwardIfCurrent.

    3. No unacceptable blocking — 4/5 event handlers are microsecond-scale (Interlocked reads + _telemetryLock + AsyncEventHandlerGuard.Run fire-and-forget). The DeviceTokenReceived path does small file I/O once per pairing lifecycle.

    4. The atomicity invariant is correct and valuable — It prevents a TOCTOU race where a retired client's WebSocket callback could reach subscriber telemetry/state-machine code after replacement. The GatewayConnectionManager operator-side event forwarding uses a lockless generation-check pattern, but node-side justifies the stricter pattern because: (a) synchronous telemetry observations don't all have independent generation guards, (b) the lock hold is bounded to lightweight preambles, (c) the code is simpler.

    5. Alternative designs rejected — Snapshot-and-raise outside lock loses the TOCTOU guard for synchronous subscribers. Generation double-check, per-client refcount, and serialized queue add unjustified complexity for a lock held during lightweight synchronous preambles.

    Deliverables (PR #1022)

    • 3 tests exercising generation advancement, clean teardown, and lock-free property reads from handlers
    • Enhanced ForwardIfCurrent comment documenting lock ordering invariant and subscriber contract
  10. shanselman commented on Jul 18, 2026

    @shanselman
    Collaborator

    Hazard 3 (wizard request disposal misreported as timeout) is resolved by merged PR #1018. SendWizardRequestAsync now distinguishes real deadlines from client-lifetime cancellation with WaitAsync(timeout, token) and unconditionally removes both pending trackers in inally. Real loopback coverage proves response, gateway error, true timeout, disposal-before-response, and late-response-after-timeout behavior. Full CI and paired independent review were green.

  11. shanselman commented on Jul 18, 2026

    @shanselman
    Collaborator

    Hazard 2 (NodeConnector.ForwardIfCurrent dispatch under _clientLifecycleLock) is dispositioned by merged PR #1022. Investigation found no reverse lock ordering, reentrant lifecycle call, or unacceptable synchronous work. Keeping generation validation + dispatch atomic is intentional: moving dispatch outside the lock would permit retired-client events after replacement. Authentic event-path tests now prove stale reconnect/disconnect events are suppressed, current events are forwarded, and current subscribers can read connector properties without blocking.

  12. shanselman commented on Jul 18, 2026

    @shanselman
    Collaborator

    Final disposition: all umbrella hazards are resolved or explicitly closed by invariant analysis. Setup cancellation was fixed by #1011; session snapshot aliasing by #1012; wizard disposal/timeout classification and tracker cleanup by #1018; ForwardIfCurrent dispatch-under-lock was verified as an intentional atomicity invariant and hardened with authentic event-path tests by #1022; WebSocket graceful close/send overlap and queued-close shutdown noise were fixed by merged #1023. Each production fix has focused behavioral coverage, required local validation, green CI, and independent review above the maintainer confidence bar.

  13. 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:source-reproimpact:session-stateimpact:ux-frictionissue-rating: 🦞 diamond lobster

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions