Skip to content

fix(sessions): keep one agent's session cleanup and /stop from killing another agent's work - #161736

Merged
steipete merged 4 commits into
mainfrom
fix/w3-sessions-scope
Sep 30, 2026
Merged

steipete merged 4 commits into
mainfrom
fix/w3-sessions-scope

Conversation

@steipete

@steipete steipete commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

One agent's session operations could destroy another agent's live work. With two agents (for example main and research) whose sessions share a raw session key such as global:

  • Deleting, resetting, or archiving research's session aborted main's active reply run and cleared main's queued follow-ups and queued lane commands.
  • Research running /stop (both the fast abort path and the command stop path) did the same: main's queued follow-ups were deleted and main's run was aborted.

The operator sees main's turn silently disappear mid-reply, with no error, because another agent touched its own session.

Why This Change Was Made

Root cause: follow-up queues, embedded session command lanes, and the reply-run registry are process-wide and keyed by raw session keys, while the cleanup paths matched on the key alone. prepareSessionLifecycleDrain (src/gateway/server-methods/sessions-lifecycle-drain.ts) cancelled by raw key and then ran an unscoped clearSessionQueues; commands-session-abort.ts and abort-operation.ts did the same for /stop.

The fix makes ownership explicit where the work is produced and matched:

  • Follow-ups: clearSessionLifecycleQueues / hasSessionLifecycleQueueWork (src/auto-reply/reply/queue/cleanup.ts) match agent, request-key aliases, and session identity, and are used for both cleanup stages and for authoritative-work detection.

  • Command lanes: queue entries now carry an optional sessionTarget captured at enqueue by the embedded, CLI, and compaction producers. clearCommandLane(lane, matches) and countQueuedCommandsInLane remove/count only the selected agent's entries in shared raw lanes. Lane names and scheduling are unchanged.

  • Reply runs: one selector in reply-run-registry.registry.ts resolves the exact agent-owned operations; lifecycle drain and both stop paths abort and await settlement only for those.

  • Owner settlement: aborting an unretained pre-backend reply reservation cleared its registry slot but never settled its owner promise (reply-run-registry.operation.ts). The old drain waited on the slot and never noticed; the exact-owner drain waits on owner settlement, so Incognito expiry timed out after cancelling the run. The abort now completes the reservation through its existing complete() (production +1/−1).

Own-session behavior is preserved: main deleting/resetting/stopping its own global session still cancels its run and clears its queued follow-ups and lane commands (including the default agent's raw lanes, which an independent review flagged on the first iteration and is now covered).

Production LOC: roughly +290 net across the three owner surfaces. This is the ownership record the shared queues were missing, not a guard layered on top; the stop paths reuse the lifecycle selector instead of a parallel matcher.

Not covered here (tracked as a follow-up): a few other callers of the generic raw-key clearSessionQueues (provider review, worker placement, rewind, fallback session abort) can still pass raw aliases. The generic API is kept because those paths intentionally tear down a whole drain; each needs its own reproduction.

User Impact

In multi-agent setups with shared session keys (notably session.scope: global), deleting, resetting, archiving, or stopping one agent's session no longer kills or drops another agent's in-flight reply, queued follow-ups, or queued commands.

Evidence

  • Reproduced before the fix: 7 failing lifecycle cases (delete/reset/archive, global and colliding ordinary keys, queued work) and 6 failing stop-boundary cases (fast and command stop; follow-up deletion and cross-agent run abort).
  • After: sessions-lifecycle-agent-scope.test.ts 10/10, stop owner-boundary tests 16/16; 174/174 across 14 related files; on Blacksmith Testbox the related suites pass (9 files / 59 tests plus queue and command-queue shards, 5 shards green).
  • Real isolated Gateway proof (worker run): repeated research deletion/reset leaves main's turn running to completion; deleting a main-owned session still aborts main.
  • Settlement regression: server.incognito-lifetime.test.ts passes 10/10 on origin/main (negative control), failed on the pre-settlement head, and passes 10/10 after; three new reservation-settlement cases fail before and pass after. Expanded 218-file lifecycle selection (every caller of delete/reset/archive drains): 3,112 passed, two opt-in benchmarks skipped.
  • check-changed passes; all 27 core test-type graphs pass; Codex autoreview on the full branch: no accepted findings.

@clawsweeper

clawsweeper Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review September 30, 2026 07:48
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: XL labels Sep 30, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 30, 2026
@clawsweeper

clawsweeper Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed September 30, 2026, 5:22 AM ET / 09:22 UTC (Revision 2).

ClawSweeper review

What this changes

The branch makes session deletion, reset, archive, and /stop select an agent’s reply runs and queued work by agent and session identity, with regression tests and session documentation.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep this PR open. Current main still clears session work by shared raw key, and the branch addresses the reported cross-agent interruption. The new Gateway regression file still needs the measured test cost required by repository policy.

Priority: P1
Reviewed head: 49ed4307f617541618bf0835bf800dbe30d4de7c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The owner-scoped repair has substantial boundary coverage and reported Gateway behavior proof; measured cost for the new Gateway file remains undisclosed.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: Repository State classifies the author as MEMBER, so contributor proof is not required. The PR body reports an isolated Gateway run in which research deletion and reset let main finish, and the added handler tests inspect the corresponding final cancellation effects; this read-only review did not execute them. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State classifies the author as MEMBER, so contributor proof is not required. The PR body reports an isolated Gateway run in which research deletion and reset let main finish, and the added handler tests inspect the corresponding final cancellation effects; this read-only review did not execute them. No stored-data contract changes.
Evidence reviewed 9 items Current main remains affected: The fetched main revision still clears queues and aborts reply runs by raw session key during lifecycle drain.
Existing session contract: The current documentation says agents using the shared global key retain separate conversations and agent-selected replies.
Scoped queue selection: The introduced cleanup matches agent, session-key aliases, and session incarnation before removing pending follow-ups or lane entries.
Findings 1 actionable finding [P3] Report the new Gateway test file’s measured cost
Security None None.

How this fits together

Gateway session actions and /stop enter cancellation handlers before a session changes. Those handlers inspect shared reply and command queues to decide which agent turns end and which continue.

flowchart LR
A[Session action or stop] --> B[Select agent and session]
B --> C[Find reply runs]
B --> D[Find queued messages]
B --> E[Find queued commands]
C --> F[Cancel selected work]
D --> F
E --> F
F --> G[Other agents continue]
Loading

Before merge

  • Report the new Gateway test file’s measured cost (P3) - The new Gateway regression file adds per-PR CI work, but the PR body gives test counts without its one-worker wall time or CI seconds. Repository policy requires those measurements so maintainers can assess the test budget; the final commit message measures two other files.
  • Complete next step (P2) - Add the new Gateway test file’s one-worker wall time to the PR body, and add its CI seconds once the current run provides them.

Findings

  • [P3] Report the new Gateway test file’s measured cost — src/gateway/server-methods/sessions-lifecycle-agent-scope.test.ts:32
Agent review details

Security

None.

PR surface

Source +287, Tests +321, Docs +3. Total +611 across 27 files.

View PR surface stats
Area Files Added Removed Net
Source 16 428 141 +287
Tests 10 453 132 +321
Docs 1 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 27 884 273 +611

Review metrics

Metric Value Why it matters
Production and test growth production +287 net lines; tests +321 net lines The PR explains the production growth as ownership recording for shared queues; the added tests make measured per-PR cost relevant.

Technical review

Best possible solution:

Keep cancellation selection in the queue and reply-run owners, preserve own-session cancellation, and handle the distinct embedded-run ID collision in #141379.

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

Yes, from source: two agents with the same raw session key reach process-wide cleanup that current main performs by key alone. The PR reports before-fix failures, but this read-only review did not execute them.

Is this the best way to solve the issue?

Yes. Recording ownership when work enters shared queues and selecting the owning agent and session at cancellation is a focused repair that preserves lane scheduling.

Full review comments:

  • [P3] Report the new Gateway test file’s measured cost — src/gateway/server-methods/sessions-lifecycle-agent-scope.test.ts:32
    The new Gateway regression file adds per-PR CI work, but the PR body gives test counts without its one-worker wall time or CI seconds. Repository policy requires those measurements so maintainers can assess the test budget; the final commit message measures two other files.
    Confidence: 0.96

Overall correctness: patch is correct
Overall confidence: 0.86

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 94ee9b54006b.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: A session action for one agent can silently interrupt another agent’s live reply or pending messages on current main.
  • merge-risk: 🚨 message-delivery: The patch changes which active replies and queued messages cancellation discards, making agent selection consequential beyond green CI.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Repository State classifies the author as MEMBER, so contributor proof is not required. The PR body reports an isolated Gateway run in which research deletion and reset let main finish, and the added handler tests inspect the corresponding final cancellation effects; this read-only review did not execute them. No stored-data contract changes.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. A Telegram Test Server run can observe whether stopping one agent leaves another agent’s reply visible when their sessions share a raw key.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Navarro III: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-30T07:56:01.305Z sha 1920e85 :: needs changes before merge. :: [P3] Record the measured cost of the new regression tests

Match reply operations and queued follow-ups against the selected agent, request-key aliases, and session identity in both lifecycle cleanup stages. Preserve foreign work in shared raw-key queues while keeping own-session cancellation and owner settlement intact.

Gateway-boundary regressions cover delete, reset, archive, global and ordinary key collisions, queued work, and own-session cancellation. Real isolated Gateway proof preserves main through repeated research deletion/reset and still aborts a deleted main-owned session.

Validation: related unit and boundary suites, two session end-to-end flows, full builds, and all 27 core test-type graphs passed. check-changed stops at the inherited parseBoolean declaration in scripts/ci-build-manifest.mjs:101; neither that file nor its guard changes here.
Capture session ownership when embedded, CLI, and compaction commands enter their lanes. Count and remove only the selected agent and session incarnation, while preserving sibling commands sharing a raw key. Keep lane names and scheduling unchanged.

Regression: seven raw-lane lifecycle cases fail before the fix; all 10 lifecycle cases and 18 queue cleanup tests pass on Blacksmith Testbox. Formatting verified remotely; local dependencies are absent.
Share the lifecycle reply-operation selector with both Stop paths. Resolve queued work and active runs by agent and session identity, and clear captured queues before signaling cancellation. Preserve the distinct whole-drain cleanup contract for other callers.

Boundary regressions reproduce foreign queue loss in six cases and cross-agent active-run cancellation in both Stop entry points before the fix. All 174 focused and sibling tests pass on Blacksmith Testbox. Complete changed-file gates in stages, including runtime and test typechecks, lint, and lifecycle guards. Extract the abort queue fixture for the line-cap ratchet and correct earlier queue regression lint.
An aborted, unretained pre-backend reservation cleared its registry slot without settling its owner promise. The exact-owner lifecycle drain introduced in 196ad44 therefore timed out Incognito expiry after successfully cancelling the queued run. Complete the reservation through its existing owner while preserving retained execution and delivery barriers and all agent-scoped selection.

Blacksmith proof: origin/main 84ce02b passed all 10 Incognito tests. Before the fix, head 1920e85 failed the expiry test and all three new reservation-settlement cases. After the fix, 49 focused tests passed; the expanded 218-file selection passed 3112 tests with two opt-in benchmarks skipped. All selected files were observed, including lifecycle caller grep matches and the existing scope and Stop regressions.

check-changed passed, including runtime types, all 27 core test-type graphs, formatting, and zero-warning lint. Standalone costs with one worker: registry cancellation 13 tests in 2.80s wall; Incognito lifetime 10 tests in 38.87s wall. Staged secret scan passed. Production +1/-1 LOC; tests +39/-13 LOC.
@steipete
steipete force-pushed the fix/w3-sessions-scope branch from 1920e85 to 49ed430 Compare September 30, 2026 09:15
@clawsweeper clawsweeper Bot added the proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. label Sep 30, 2026
@steipete
steipete merged commit c773890 into main Sep 30, 2026
199 checks passed
@steipete
steipete deleted the fix/w3-sessions-scope branch September 30, 2026 10:10
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Sep 30, 2026
… module

c773890 (#161736) called resolveActiveReplyOperationForSessionId from
reply-run-registry.registry.ts, but that name exists there only as an
export alias (export { resolveReplyRunForCurrentSessionId as ... }), which
creates no local binding, so pnpm tsgo:core fails on main with TS2552.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 1, 2026
…g another agent's work (openclaw#161736)

* fix(sessions): isolate lifecycle cleanup by agent

Match reply operations and queued follow-ups against the selected agent, request-key aliases, and session identity in both lifecycle cleanup stages. Preserve foreign work in shared raw-key queues while keeping own-session cancellation and owner settlement intact.

Gateway-boundary regressions cover delete, reset, archive, global and ordinary key collisions, queued work, and own-session cancellation. Real isolated Gateway proof preserves main through repeated research deletion/reset and still aborts a deleted main-owned session.

Validation: related unit and boundary suites, two session end-to-end flows, full builds, and all 27 core test-type graphs passed. check-changed stops at the inherited parseBoolean declaration in scripts/ci-build-manifest.mjs:101; neither that file nor its guard changes here.

* fix(sessions): clear owned commands from shared session lanes

Capture session ownership when embedded, CLI, and compaction commands enter their lanes. Count and remove only the selected agent and session incarnation, while preserving sibling commands sharing a raw key. Keep lane names and scheduling unchanged.

Regression: seven raw-lane lifecycle cases fail before the fix; all 10 lifecycle cases and 18 queue cleanup tests pass on Blacksmith Testbox. Formatting verified remotely; local dependencies are absent.

* fix(reply): scope stop cancellation to agent-owned sessions

Share the lifecycle reply-operation selector with both Stop paths. Resolve queued work and active runs by agent and session identity, and clear captured queues before signaling cancellation. Preserve the distinct whole-drain cleanup contract for other callers.

Boundary regressions reproduce foreign queue loss in six cases and cross-agent active-run cancellation in both Stop entry points before the fix. All 174 focused and sibling tests pass on Blacksmith Testbox. Complete changed-file gates in stages, including runtime and test typechecks, lint, and lifecycle guards. Extract the abort queue fixture for the line-cap ratchet and correct earlier queue regression lint.

* fix(reply): settle aborted queued reservations

An aborted, unretained pre-backend reservation cleared its registry slot without settling its owner promise. The exact-owner lifecycle drain introduced in 196ad44 therefore timed out Incognito expiry after successfully cancelling the queued run. Complete the reservation through its existing owner while preserving retained execution and delivery barriers and all agent-scoped selection.

Blacksmith proof: origin/main 8454fca passed all 10 Incognito tests. Before the fix, head 1920e85 failed the expiry test and all three new reservation-settlement cases. After the fix, 49 focused tests passed; the expanded 218-file selection passed 3112 tests with two opt-in benchmarks skipped. All selected files were observed, including lifecycle caller grep matches and the existing scope and Stop regressions.

check-changed passed, including runtime types, all 27 core test-type graphs, formatting, and zero-warning lint. Standalone costs with one worker: registry cancellation 13 tests in 2.80s wall; Incognito lifetime 10 tests in 38.87s wall. Staged secret scan passed. Production +1/-1 LOC; tests +39/-13 LOC.

Co-authored-by: Peter Steinberger <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 1, 2026
… module

8b94d33 (openclaw#161736) called resolveActiveReplyOperationForSessionId from
reply-run-registry.registry.ts, but that name exists there only as an
export alias (export { resolveReplyRunForCurrentSessionId as ... }), which
creates no local binding, so pnpm tsgo:core fails on main with TS2552.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant