Skip to content

fix(gateway): isolate the SessionsUpdated snapshot from live tracked state - #1012

Merged
shanselman merged 1 commit into
openclaw:mainfrom
anagnorisis2peripeteia:fix/session-snapshot-isolation
Jul 17, 2026
Merged

shanselman merged 1 commit into
openclaw:mainfrom
anagnorisis2peripeteia:fix/session-snapshot-isolation

Conversation

@anagnorisis2peripeteia

Copy link
Copy Markdown
Contributor

Related: #1010

What Problem This Solves

Fixes a data race where a SessionInfo snapshot delivered to SessionsUpdated subscribers is not isolated from the gateway client's live tracked state. A subscriber reading a session's fields (e.g. CurrentActivity, LastSeen, Status) can observe them changing underneath it while the message-receive thread updates the same session — so a consumer (the tray's session views) can read shifting/inconsistent values, e.g. a session's activity from one update mixed with its timestamp from the next.

Severity — being precise: this is a genuine unsynchronized read/write, but low-severity in practice. On x64 the individual field reads are atomic (string references and DateTime's backing ulong), so the symptom is stale/mixed field values in the UI, not a torn read or crash. The fix is a cheap, standard hardening (hand out an immutable copy) rather than a fix for an observed corruption.

Why This Change Was Made

GetSessionListInternal snapshots the array but copies the SessionInfo references straight out of the _sessions map (_sessions.Values.CopyTo(arr, 0)). UpdateTrackedSession then mutates those same objects in place under _sessionsLock, while SessionsUpdated subscribers read the snapshot with no lock. The delivered snapshot is therefore a live alias of mutable state. The fix hands out a defensive copy — arr[i] = arr[i].Clone() (a SessionInfo.Clone() via MemberwiseClone) — so a delivered snapshot is immutable with respect to later in-place updates.

User Impact

Consumers of the sessions list (the tray's session views) now receive a stable, point-in-time snapshot rather than objects that can mutate mid-read. No user-facing behavior change beyond the removal of the race.

Evidence

Focused red→green regression test SessionSnapshotIsolationTests.SessionSnapshot_IsNotAliasedToLiveTrackedState, plus the full Windows build+test matrix below.

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

Full CI-matrix mirror on a Windows host (win-x64, .NET 10.0.301), HEAD e36992fb vs base 9fb1960e. Every project built and all 8 test suites passed (exit 0), including the changed Shared.Tests:

build all projects + all 8 test projects .......... exit 0
test Shared.Tests (contains the regression) ....... exit 0
test SetupEngine / Connection / WinNode.Cli ....... exit 0
test Tray.Tests / Tray.IntegrationTests ........... exit 0
test FunctionalUI.Tests / Tray.UITests ............ exit 0

(Note: this repo has two intermittent pre-existing flakes — Connection.Tests.ConnectAndReconnect_EmitCompletedOperatorSpans and Tray.UITests.ChatTimelineVirtualizationProofTests — neither of which fired in this run; both are on surfaces this Shared-only diff does not touch.)

Real Behavior Proof

  • Environment tested: Windows host, .NET SDK 10.0.301, win-x64 (full matrix); the focused test also on macOS 10.0.302
  • PR head or commit tested: e36992fb (branch fix/session-snapshot-isolation)
  • Exact steps or command run: dotnet test tests/OpenClaw.Shared.Tests --filter "FullyQualifiedName~SessionSnapshotIsolation", run against base and HEAD. The test records a session with activity "compiling", captures its snapshot via GetSessionList(), then issues a second update for the same key and asserts the earlier snapshot is unchanged.
  • Evidence after fix: on base the captured snapshot's CurrentActivity flips to "running-tool" (the later update reaching back through the aliased object) → fails; on HEAD it stays "compiling" → passes.
  • Observed result: base red, HEAD green; deterministic (no threads/timing — proves the aliasing directly).
  • Screenshot or artifact links verified? N/A (non-UI shared-state logic; proof is the paired red/green test)
  • Not verified or blocked: none

Security Impact

  • New permissions or capabilities? No
  • Secrets or tokens handling changed? No
  • New or changed network calls? No
  • Command or tool execution surface changed? No
  • Data access scope changed? No

Compatibility and Migration

  • Backward compatible? Yes
  • Config or environment changes? No
  • Migration needed? No

Review History

Local review history (findings + dispositions per commit): https://gist.github.com/anagnorisis2peripeteia/30c18e621cc0d17539ed1362931f8fc6

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.

…state

GetSessionListInternal copies the _sessions array but its elements are the
same SessionInfo instances the map holds, which UpdateTrackedSession mutates
in place under _sessionsLock. SessionsUpdated subscribers read the snapshot
with no lock, so they can observe CurrentActivity/LastSeen/Status changing
underneath them — a data race on shared mutable state.

Hand out a defensive copy (SessionInfo.Clone via MemberwiseClone) so a
delivered snapshot is isolated from later in-place mutation.

Adds SessionSnapshotIsolationTests (red before the fix: a captured snapshot's
CurrentActivity is overwritten by a later update for the same key; green after).
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal priority bug or improvement with limited blast radius. labels Jul 17, 2026
@clawsweeper

clawsweeper Bot commented Jul 17, 2026

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed July 17, 2026, 11:57 AM ET / 15:57 UTC.

Summary
The PR clones each gateway session object before returning or publishing a session snapshot and adds a regression test proving later tracked-state updates cannot mutate an earlier snapshot.

Reproducibility: yes. at source level: retaining live object references makes a captured snapshot change after the same tracked session is updated, and the focused regression test directly expresses that path. An independent live gateway reproduction was not established during this read-only review.

Review metrics: 2 noteworthy metrics.

  • Patch scope: 3 files, 64 added, 0 removed. The fix is tightly confined to the session model, snapshot construction, and focused regression coverage.
  • Behavioral paths changed: 1 snapshot path changed. Only the gateway session snapshot boundary changes; configuration, persistence, networking, and migration behavior remain untouched.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #1010
Summary: The linked issue is the canonical multi-hazard report, and this PR is the focused candidate fix for its session-snapshot aliasing component.

Members:

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

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦪 silver shellfish
Patch quality: 🐚 platinum hermit
Result: blocked until real behavior proof from a real setup is added.

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

Rank-up moves:

  • [P1] Add redacted terminal or runtime-log proof from a real gateway session showing that an earlier captured snapshot remains unchanged after a later update.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The deterministic regression and reported test matrix are valuable supplemental evidence, but no after-fix run through a real gateway setup is shown; add redacted terminal, live output, or logs, update the PR body to trigger review, or ask a maintainer for @clawsweeper re-review if needed.

Risk before merge

  • [P1] The external PR provides only automated red/green tests and CI-style output; repository review policy still requires after-fix evidence from a real gateway setup before merge.

Maintainer options:

  1. Decide the mitigation before merge
    Retain the defensive snapshot copy and regression test, then add a redacted real-gateway terminal or log transcript showing a held session snapshot remains stable across a later session update before landing the fix.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Next step before merge

  • [P1] Keep the PR in human review until the contributor supplies the required after-fix real-gateway proof; no mechanical code repair is currently identified.

Security
Cleared: The patch adds no permissions, dependency, credential, network, command-execution, persistence, or supply-chain changes.

Review details

Best possible solution:

Retain the defensive snapshot copy and regression test, then add a redacted real-gateway terminal or log transcript showing a held session snapshot remains stable across a later session update before landing the fix.

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

Yes at source level: retaining live object references makes a captured snapshot change after the same tracked session is updated, and the focused regression test directly expresses that path. An independent live gateway reproduction was not established during this read-only review.

Is this the best way to solve the issue?

Yes. Copying the session objects while constructing the lock-protected snapshot is the narrowest maintainable way to preserve the existing API while preventing later live-state mutation from leaking to consumers.

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add P2: This is a valid but low-severity shared-state race that can produce inconsistent session UI values without crashing or corrupting persisted data.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The deterministic regression and reported test matrix are valuable supplemental evidence, but no after-fix run through a real gateway setup is shown; add redacted terminal, live output, or logs, update the PR body to trigger review, or ask a maintainer for @clawsweeper re-review if needed.

Label justifications:

  • P2: This is a valid but low-severity shared-state race that can produce inconsistent session UI values without crashing or corrupting persisted data.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The deterministic regression and reported test matrix are valuable supplemental evidence, but no after-fix run through a real gateway setup is shown; add redacted terminal, live output, or logs, update the PR body to trigger review, or ask a maintainer for @clawsweeper re-review if needed.
Evidence reviewed

What I checked:

  • Current-base aliasing: At the reviewed base, GetSessionListInternal copies _sessions values into a new array but retains the same mutable SessionInfo references, so the array is not an isolated point-in-time snapshot. (src/OpenClaw.Shared/OpenClawGatewayClient.cs:3397, 9fb1960ec434)
  • Narrow defensive-copy fix: The PR head clones every session while the snapshot is assembled, preventing subsequent in-place tracked-state mutation from reaching objects already returned to consumers. (src/OpenClaw.Shared/OpenClawGatewayClient.cs:3400, e36992fb6ef7)
  • Clone semantics: SessionInfo.Clone uses MemberwiseClone; the session fields implicated by this patch are scalar values, value types, or immutable strings, making the shallow copy sufficient for the represented state. (src/OpenClaw.Shared/Models.cs:256, e36992fb6ef7)
  • Regression coverage: The added test captures a session snapshot, updates the same tracked session, and asserts that the captured activity remains unchanged, directly exercising the reported aliasing behavior. (tests/OpenClaw.Shared.Tests/SessionSnapshotIsolationTests.cs:34, e36992fb6ef7)
  • Canonical report relationship: The linked open report tracks this session-snapshot race alongside distinct setup-cancellation and lower-severity concurrency concerns; this PR is the candidate fix only for its session-snapshot portion.
  • Validation and proof supplied: The PR reports a base-red/head-green focused regression and a successful Windows build/test matrix, but all supplied evidence is automated test output rather than observation through a real gateway setup. (e36992fb6ef7)

Likely related people:

  • shanselman: Recent merged work hardened gateway session aggregation and related gateway-client behavior, making this the strongest available routing signal for the affected session path. (role: recent session and gateway area contributor; confidence: medium; commits: 2fcfe76; files: src/OpenClaw.Shared/OpenClawGatewayClient.cs)
  • ranjeshj: Recent merged gateway connection-stability work is adjacent to the client lifecycle and tracked gateway state affected here. (role: recent gateway connection contributor; confidence: low; commits: 5f2de90; files: src/OpenClaw.Shared/OpenClawGatewayClient.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.

@shanselman
shanselman merged commit 081f307 into openclaw:main Jul 17, 2026
14 checks passed
shanselman added a commit that referenced this pull request Jul 20, 2026
- SessionInfo.Clone() now deep-copies Presentation and Worktree objects
  so defensive snapshots cannot alias live tracked session state (#1012).
- TrayDashboardSummary.SelectActiveSession prefers non-ended sessions
  as the fallback display item, preserving AbortedLastRun visibility.
- Add snapshot isolation tests proving clone independence.
- Add runtime behavior tests for ended/background/routing pipeline.
- Add dashboard ended-session deprioritization tests.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: c311ae3b-8656-403f-91a6-5bfe2f91f5cd
shanselman added a commit that referenced this pull request Jul 21, 2026
* fix: render sessions with friendly presentation metadata

* fix: harden legacy session presentation fallbacks

* fix: use valid session wrapper tuple names

* fix: preserve sparse session presentation updates

* fix: preserve legacy main identity on sparse updates

* fix: decouple session localization from test runtime

* fix: align session presentation drift guard

* fix: complete session title localization

* fix(chat): retain session title tooltips

* fix: deep-copy nested session state and harden ended-session surfaces

- SessionInfo.Clone() now deep-copies Presentation and Worktree objects
  so defensive snapshots cannot alias live tracked session state (#1012).
- TrayDashboardSummary.SelectActiveSession prefers non-ended sessions
  as the fallback display item, preserving AbortedLastRun visibility.
- Add snapshot isolation tests proving clone independence.
- Add runtime behavior tests for ended/background/routing pipeline.
- Add dashboard ended-session deprioritization tests.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: c311ae3b-8656-403f-91a6-5bfe2f91f5cd

---------

Co-authored-by: Scott Hanselman <[email protected]>
Co-authored-by: Copilot App <[email protected]>
@anagnorisis2peripeteia
anagnorisis2peripeteia deleted the fix/session-snapshot-isolation branch September 9, 2026 00:36
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. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants