Repository navigation
Description
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 objectsUpdateTrackedSession 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.CloseWebSocketAsyncisn't mutually exclusive with sends —src/OpenClaw.Shared/WebSocketClientBase.cs(CloseWebSocketAsyncvsSendRawAsync).SendRawAsyncholds_sendLockacrossws.SendAsync;CloseWebSocketAsyncskips it.ClientWebSocketforbids aCloseAsyncwhile aSendAsyncis outstanding, so a shutdown racing an in-flight send throwsInvalidOperationExceptionand 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_sendLockinCloseWebSocketAsync.NodeConnector.ForwardIfCurrentraises 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 asTimeoutExceptionrather than a cancellation. Largely mitigated byClearPendingRequestsfaulting the pending completion withOperationCanceledException; 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. |
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Projects
- StatusShow more project fieldsChannels
Activity
anagnorisis2peripeteia commentedon Jul 17, 2026
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.
[-]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)[/+]clawsweeper commentedon Jul 17, 2026
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:
canonicalCanonical: #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:
fixed_by_candidate: fix(setup): cancel node pairing cleanly instead of a spurious timeout warning + wasted retry #1011 - This open PR narrowly addresses the setup-cancellation warning and wasted retry.fixed_by_candidate: fix(gateway): isolate the SessionsUpdated snapshot from live tracked state #1012 - This open PR narrowly addresses the SessionsUpdated snapshot aliasing.adjacent_distinct: Disposal audit of the Windows node: one dead Process to fix; async SemaphoreSlim/CTS fields reviewed and left as-is #1003 - The closed disposal audit covers separate resource-lifetime candidates and is explicitly distinguished by the reporter.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:
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:
src/OpenClaw.SetupEngine/SetupSteps.cs, 9fb1960ec434)src/OpenClaw.Shared/OpenClawGatewayClient.cs, 9fb1960ec434)src/OpenClaw.SetupEngine/SetupSteps.cs, 294ef1798bef)src/OpenClaw.Shared/OpenClawGatewayClient.cs, e36992fb6ef7)src/OpenClaw.Shared/OpenClawGatewayClient.cs, 98f48c2ef966)VISION.md)Likely related people:
src/OpenClaw.Shared/OpenClawGatewayClient.cs,src/OpenClaw.Shared/WebSocketClientBase.cs)src/OpenClaw.SetupEngine/SetupSteps.cs,src/OpenClaw.Connection/NodeConnector.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.[-]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)[/+]anagnorisis2peripeteia commentedon Jul 17, 2026
#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).
shanselman commentedon Jul 18, 2026
The two primary bugs in this umbrella are now fixed and merged:
SessionsUpdatedsnapshots aliasing live mutableSessionInfostate.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:WebSocketClientBase.CloseWebSocketAsyncstill callsClientWebSocket.CloseAsyncwithout taking_sendLock, whileSendRawAsyncholds that lock acrossSendAsync. A close/send race can still produce the documented invalid-state warning and skip graceful close.NodeConnector.ForwardIfCurrentstill 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.OpenClawGatewayClient.SendWizardRequestAsyncstill racescompletion.TaskagainstTask.Delay(timeoutMs, CancellationToken), whereCancellationTokenis tied to client lifetime. Client disposal can therefore still be classified asTimeoutExceptionif 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.
anagnorisis2peripeteia commentedon Jul 18, 2026
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:WebSocketClientBase.CloseWebSocketAsyncskips_sendLock; a close racing an in-flight send throws and skips the graceful close.NodeConnector.ForwardIfCurrentinvokes subscriber delegates while holding_clientLifecycleLock(filed so the accept/fix/defer decision is explicit; the fix must preserve the publish-after-retire guarantee the lock currently provides).TimeoutException(SendWizardRequestAsyncplus thechat.sendand exec-approval siblings; the residual window is register-after-clear, sinceDisposerunsClearPendingRequestsbefore_cts.Cancel()).Closing this umbrella: the two proven bugs are fixed and merged (#1011, #1012), and the residual risks are now separately tracked.
shanselman commentedon Jul 18, 2026
Hazard 2 resolution:
ForwardIfCurrentdispatch-under-lockVerdict: no code change to
ForwardIfCurrentis warranted. PR #1022 adds tests and documentation to harden the existing invariant.Investigation summary
No deadlock — Lock ordering is consistent:
_clientLifecycleLockis 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.No reentrancy corruption — No subscriber synchronously calls back into
NodeConnectorfrom insideForwardIfCurrent.No unacceptable blocking — 4/5 event handlers are microsecond-scale (Interlocked reads +
_telemetryLock+AsyncEventHandlerGuard.Runfire-and-forget). TheDeviceTokenReceivedpath does small file I/O once per pairing lifecycle.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
GatewayConnectionManageroperator-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.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)
ForwardIfCurrentcomment documenting lock ordering invariant and subscriber contracttest+doc: harden ForwardIfCurrent dispatch-under-lock invariant (#1010)
shanselman commentedon Jul 18, 2026
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.
test+doc: harden ForwardIfCurrent dispatch-under-lock invariant (#1010)…
shanselman commentedon Jul 18, 2026
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.
shanselman commentedon Jul 18, 2026
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.