Skip to content

fix(gateway): keep the typed state-contention Stop outcome on sessions.abort - #159282

Closed
wangmiao0668000666 wants to merge 2 commits into
openclaw:mainfrom
wangmiao0668000666:fix/sessions-abort-state-contention
Closed

wangmiao0668000666 wants to merge 2 commits into
openclaw:mainfrom
wangmiao0668000666:fix/sessions-abort-state-contention

Conversation

@wangmiao0668000666

@wangmiao0668000666 wangmiao0668000666 commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Closed 2026-10-12 — see the closing comment for the handoff. The RED/GREEN pair below was captured on base e8b8942affd; since #169622 moved bundled session reads and authority into workers, the real-lock case no longer reaches the contended write on current main (it answers no-active-run), so that pair is prior-base evidence. The production change itself is not in question and the fast RPC-boundary regression is still green.

Closes #160004

What Problem This Solves

A Stop that meets state contention on sessions.abort escapes unclassified, so the Control UI cannot render the uncertainty-preserving notice the server already knows how to produce. handleChatAbortRequest (src/gateway/server-methods/chat-abort-handler.ts) turns typed contention into UNAVAILABLE with details.errorKind, but src/gateway/server-methods/sessions-abort.ts calls handleChatAbortRequestWithLifecycle directly and never passes through that wrapper. sessions.abort is the only route that can cancel a recovered embedded run (src/gateway/chat-abort.ts:60-64, sessionAbortable), so it is the route that most needs the typed outcome.

Precedent: #156067 (same classification, same wording and authority rules; that PR only added it to chat.abort).

Why This Change Was Made

The classification now lives in one owner and both Stop routes use it:

  • respondToAbortStateContention(options, error) — the single typed-contention responder, so wording, ErrorCodes.UNAVAILABLE, and details.errorKind cannot drift between routes.
  • withAbortStateContentionGuard(handler) — wraps a Stop handler: classify, otherwise rethrow.

chat.abort keeps its existing behavior (handleChatAbortRequest is now the guarded handleChatAbortRequestWithLifecycle), and sessions.abort registers withAbortStateContentionGuard(...) around its existing body.

The whole handler is wrapped rather than just the delegated call because the typed error can be thrown by the handler's own session read (sessions-abort.ts loadSessionEntry) as well as by the delegated lifecycle call. The own-read site is the one a real Gateway reaches first (proved below under a real foreign lock, and in the Control-UI proof); the delegated site needs an unconfigured agent with a live run, and is covered by the mocked regression. A partial wrap would leave one of the two sites unclassified, so there is no second defensible shape.

Production LOC is +54/-24. Test LOC is +331/-1 (+45 fast regression at the RPC boundary, +284 live real-lock proof, +2/-1 keeping an existing suite's partial mock in step with the module's exports). Routing is +2 (one release-only inventory line, one doc bullet). No new option, configuration, validator, or persistence surface.

Classification: behavior-completing

User Impact

  • Pressing Stop on a recovered embedded run while the state database is contended now returns the typed busy outcome, so the Control UI keeps its warning-styled "Check status" notice instead of falling back to the generic danger notice with a Refresh button.
  • Non-contention Stop failures are unchanged: they still rethrow exactly as before.
  • chat.abort behavior is unchanged; its two pinned contention contracts still pass.

Evidence

Product head: 56cdbffe98d on main e8b8942affd (rebased; see the rebase note below for what moved). The traces in this section were captured on the pre-rebase head 83bf7249114; the rebased-head run is in the next section.

Rebase note — integration with the current main handlers

Main rewrote both handler files since the previous base 6e0e17d27e5 (#161124 worker-side repository reads, #157413's transaction change for ordinary state writes, and the abort-handler refactors), so the PR's 8 commits were replayed as one commit carrying the same net diff.

The only conflict was the sessions-abort.ts import block. Main now takes abortControlledSubagents / descendantAbortError from chat-abort-descendants.js, abortQueuedCollectorSession from chat-abort-runtime.js, and the ChatSessionEmbeddedAbortOutcome type from chat-abort-runtime.types.js. The resolution keeps main's import sources and adds withAbortStateContentionGuard to the chat-abort-handler.js import, so nothing main landed is reverted.

chat-abort-handler.ts auto-merged: the guard is intact — respondToAbortStateContention (:699), withAbortStateContentionGuard (:718), and handleChatAbortRequest as the guarded lifecycle handler (:732) — and sessions.abort registers it (sessions-abort.ts:162). Net diff after the rebase: production +56/-28 in the two handler files, tests +342/-1, routing +2; oxfmt --check is clean on both production files.

Known interaction: #166269 (open, status: 🚀 automerge armed) also edits sessions-abort.ts, in the dedupe-payload region around :640-680. This change wraps the handler at :162 and closes it at the end of the handler object, and does not touch that region, so a rebase after it lands is mechanical.

Rebased-head RED → GREEN (this revision)

Same host, same command, same test file; the only variable is the two handler files (main's content versus this head). Node v24.18.0, through the repository's own runner:

node scripts/run-vitest.mjs run src/gateway/server-methods/sessions.abort-contention.real-lock.test.ts
# RED — main's handlers, 1 failed (1)
SESSIONS_ABORT_CONTENTION_LIVE {"rpc":"rejected","name":"GatewayClientRequestError","code":"UNAVAILABLE",
  "message":"Error: database is locked: code=ERR_SQLITE_ERROR"}

# GREEN — this head (56cdbffe98d), 1 passed (1)
SESSIONS_ABORT_CONTENTION_LIVE {"rpc":"rejected","name":"GatewayClientRequestError","code":"UNAVAILABLE",
  "details":{"errorKind":"state_contention"},
  "message":"The server is busy. Check this turn's status before trying Stop again.\n\nSQLite transaction admission remained busy. Stopping may already have taken effect."}

The RED payload is the unclassified raw SQLite error (no details.errorKind) that the Control UI cannot render; the GREEN payload is the typed outcome.

What the production contention actually is (post-#157413)

Revision 12's finding said the real-lock test "does not exercise the production state-owner lock". The premise needed correcting, and the test now drives the real production trigger:

  • Since fix: prevent temporary-file exhaustion from SQLite coordination #157413 ("Use transactions on the actual SQLite state and device databases for ordinary writes. Remove redundant coordination databases…"), ordinary state writes are transactions on openclaw.sqlite itself. The state-owner file lock (acquireFileLockSync, state.<hash>.lock) only guards startup/schema/maintenance now, and its contention errors are plain strings ("offline maintenance" / "could not be verified") that isSqliteLockError (src/infra/sqlite-error-diagnostics.ts) deliberately does not classify — it matches only SQLITE_BUSY/SQLITE_LOCKED.
  • So the only classifiable production trigger is a foreign process holding a write transaction on the actual shared-state database while the Gateway's own admission waits. The retired state-lifecycle coordinator file used by the first version of the test can no longer produce this error class at all.

sessions.abort-contention.real-lock.test.ts therefore now holds BEGIN EXCLUSIVE on the live openclaw.sqlite from a separate OS process while a Control-UI client issues a real sessions.abort for a live run. The lock is asserted real in-test: a fresh connection cannot start a write transaction while the child holds it.

Real-Gateway RED → GREEN terminal trace (current head, Node v24.18.0)

# RED — same test against unmodified main handlers (6e0e17d27e5), 1/1 runs
SESSIONS_ABORT_CONTENTION_LIVE {"rpc":"rejected","name":"GatewayClientRequestError","code":"UNAVAILABLE",
  "message":"Error: database is locked: code=ERR_SQLITE_ERROR"}
  # no details.errorKind, no guidance text — the raw SQLite error escapes unclassified,
  # so the UI's errorKind check can never be true and the generic danger notice renders
      Tests  1 failed (1)
# GREEN — same test on the pre-rebase head (83bf7249114), 1/1 runs
SESSIONS_ABORT_CONTENTION_LIVE {"rpc":"rejected","name":"GatewayClientRequestError","code":"UNAVAILABLE",
  "details":{"errorKind":"state_contention"},
  "message":"The server is busy. Check this turn's status before trying Stop again.\n\nSQLite transaction admission remained busy. Stopping may already have taken effect."}
 ✓ sessions.abort keeps the typed state-contention outcome under a foreign lock
      Tests  1 passed (1)

Control-UI before/after Stop screenshots (real built Gateway, real Chromium, real run adoption)

What is real in these runs: the production build of this head (and of main 6e0e17d27e5 for the "before") boots as a real Gateway with a credential-free stalled loopback provider; a headless agent RPC starts a real embedded run on the main session (embedded-registry-owned — the exact ownership that routes Control-UI Stop to sessions.abort, verified in the WebSocket frames: the Stop click sends {"method":"sessions.abort","params":{"key":"agent:main:main","runId":"…"}}); the real built Control UI runs in real Chromium; the real Stop button is clicked.

What is substituted, and why it has to be: only the sessions.abort error response frame, replaced at a WebSocket MITM with the byte-exact error payload captured from the real-Gateway real-lock RED/GREEN runs above. The natural trigger window provably never coexists with a clickable Stop — each half verified on this head:

  • A live embedded run pins its agent database. The run's worker owner holds a borrower until the run ends (src/state/openclaw-agent-worker-store.ts), so the 30-minute idle eviction can never fire while the run lives. Verified with a zero-client-traffic 32-minute window (browser fully closed; the gateway's handle on openclaw-agent.sqlite never closed, and an open UI poll re-arms the idle timer on every sessions.list).
  • Reconnecting the UI under the foreign lock fails earlier than Stop. The WS connect handshake itself writes gateway state, so it returns database is locked and the UI renders "Gateway unreachable" — no Stop button ever appears.
  • The lock alone does not produce contention either. With a warm agent database the same Stop succeeds under the same foreign lock (measured 667 ms / 450 ms).

The committed real-lock test therefore closes the agent databases explicitly before taking the lock — the only window in which the typed refusal is reachable, and the state a foreign writer during a restart/eviction overlap produces.

Before Stop (identical in both builds — the run is adopted from history recovery and Stop is armed; the runId is the embedded run's):

run active, Stop armed

Before — Stop on unmodified main (6e0e17d27e5): the raw database is locked text escapes into the generic danger notice:

before: generic danger notice with raw SQLite error

After — Stop on this head (83bf7249114): the typed outcome renders the warning-styled "Check status" notice:

after: warning notice, The server is busy. Check this turn's status before trying Stop again.

Driver logs (frames, injection, timings): mitm-before.log, mitm-after.log. Both runs used identical state dirs, config, provider, and timing; the UI bundle is byte-identical between the two builds (this PR changes no UI code), so the rendered difference is exactly the wire-payload difference.

Fast regression and sibling contracts

# GREEN — dispatch-level contracts on this head (remote lane, Docker lexiflow-all, Node v24.18.0)
 ✓ sessions.abort-contention.test.ts        1 passed
 ✓ sessions.abort-agent-scope.test.ts      33 passed

Scoped tsgo on the three touched test files on the remote lane: 0 errors in the PR's files (the lane's tree pins older dependency types in unrelated files — pre-existing, not this PR).

Review response (ClawSweeper revision 12)

  • "The revised real-lock test does not exercise the production state-owner lock, and its recorded successful run predates that revision." Both halves handled at 83bf7249114. The test now drives the actual post-fix: prevent temporary-file exhaustion from SQLite coordination #157413 production trigger (foreign write transaction on the real openclaw.sqlite — see the mechanism section above for why the state-owner file lock is not the classifiable surface), and every trace on this page was re-captured on this exact head: the RED/GREEN terminal runs above and the Control-UI screenshots below.
  • "The inspected images show a chat turn rather than the changed Stop notice." The new screenshots capture the Stop notice itself, before (raw error, generic danger styling) and after (typed busy message, warning styling with "Check status"), from real Chromium against the real built Gateway — with the one substituted frame and the proof of why the natural window cannot be clicked, both documented in the screenshot section.

Verification

  • Rebased-head run on this host (Node v24.18.0, repository runner): sessions.abort-contention.real-lock.test.ts 1 passed, and 1 failed against main's handler files with the raw-error payload above — the RED/GREEN pair in the rebase section.
  • Two files could not be judged on this host for reasons outside this diff: sessions.abort-agent-scope.test.ts fails 4 of its cases with TypeError: Cannot read properties of undefined (reading 'dev') raised inside sameFileIdentity → preparePluginModule → resolveProviderModelPolicySurface (src/plugins/plugin-module-loader-cache.ts:391), and sessions.abort-contention.test.ts fails before the handler is reached with User profile catalog is not ready from captureResidentUserProfileAccess during authorizeGatewayMethod. Both throw outside the code this PR changes; the remote-lane results below cover them.
  • sessions.abort-contention.real-lock.test.ts — 1 passed on the pre-rebase head (83bf7249114), 1 failed against the unmodified main handlers (6e0e17d27e5), same command: node scripts/run-vitest.mjs run src/gateway/server-methods/sessions.abort-contention.real-lock.test.ts
  • sessions.abort-contention.test.ts — 1 passed; sessions.abort-agent-scope.test.ts — 33 passed (remote Docker lane)
  • Scoped tsgo (tsconfig.pr159282.json, the three touched test files) — 0 errors in the PR's files on the remote lane
  • Control-UI full-stack proof — real built Gateway × real Chromium × real run adoption, before/after Stop notice screenshots attached above; Stop route verified as sessions.abort with the exact runId in the captured WebSocket frames; only the error response frame is substituted (byte-exact payload from the real-lock runs), for the reasons proven in the screenshot section
  • oxfmt --check on the changed files — clean
  • The real-lock proof reaches the handler's own session read; the delegated lifecycle site needs an unconfigured agent with a live run and is covered by the mocked regression. The live case closes the agent databases before taking the lock — proven above to be the only window in which a foreign lock produces this typed refusal (a live run pins its database; a UI reconnect under the lock fails at connect). No live channel or credential was exercised.

Scope and risk

File Change Risk
src/gateway/server-methods/chat-abort-handler.ts extract the message + responder + guard; handleChatAbortRequest becomes the guarded lifecycle handler chat.abort behavior pinned by its two contention tests; non-contention errors still rethrow
src/gateway/server-methods/sessions-abort.ts register the handler through withAbortStateContentionGuard (+3 import lines) adds a classification layer only; the handler body is unchanged
src/gateway/server-methods/sessions.abort-contention.test.ts fast regression at the RPC boundary test-only
src/gateway/server-methods/sessions.abort-agent-scope.test.ts spread the actual chat-abort-handler.js in the existing partial mock so it does not pin the module's export list test-only; the suite's 36 assertions are unchanged
src/gateway/server-methods/sessions.abort-contention.real-lock.test.ts live real-lock proof (Gateway boot + real sessions.abort + foreign BEGIN EXCLUSIVE on the real state DB) test-only; one Gateway boot and one child process per run, child released over IPC with a 5 s kill fallback; release-only in CI
scripts/lib/ci-proof-test-inventory.mts, docs/ci/scope-and-routing/node-test-lanes.md register the real-lock proof in the release-only runtime inventory and document it routing only; no case or assertion removed, the fast dispatch regression stays in PR CI
  • Existing-solutions preflight: reuses the existing resolveStateContentionPresentation helper, ErrorCodes.UNAVAILABLE, and the same message/authority rules chat.abort already shipped. No new validator, option, config, or storage surface.
  • Config/default, protocol, schema, authorization, storage, migration, upgrade impact: none.

@clawsweeper

clawsweeper Bot commented Sep 27, 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.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Sep 27, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority 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. labels Sep 27, 2026
@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR shares the typed state-contention response between chat.abort and sessions.abort.

Example: Stop for agent:main:main encounters a typed SQLite busy error.

  • Before: sessions.abort returns an unclassified failure, producing generic Stop-error guidance.
  • After: sessions.abort returns UNAVAILABLE with errorKind: state_contention and guidance to check the turn’s status.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful production change with recorded Gateway boundary evidence, but two introduced test failures prevent readiness.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (terminal): Recorded terminal output exercises sessions.abort through a real Gateway transport under actual foreign SQLite locks and shows the shared guard returning UNAVAILABLE with state_contention on production-equivalent head 56cdbff; the browser response-frame substitution demonstrates presentation only, and current CI fixture failures are tracked separately.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A busy-state Stop failure lacks the error kind needed to show the existing uncertainty-preserving notice.
Reason: The patch completes an established response contract without adding configuration, changing permissions, or replaying cancellation.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep this PR open: current main still needs the session Stop classification, but both added contention tests fail in exact-head CI and need repair.

Priority: P2
Reviewed head: 144ca1d8ca1567495c11d1c9ab3e346094b39bb2

Before merge

  • Admit the dispatch fixture and inject at the active read owner (P2) - The previously reported blocker remains. This test supplies a narrow sessions.write caller without establishing an admitted session fixture, and its spy targets loadSessionEntry while sessions.abort’s own read uses withGatewaySessionEntry and current main’s delegated lifecycle uses loadGatewaySessionEntryReadOnlyInWorker. Exact-head CI receives INVALID_REQUEST instead of the asserted UNAVAILABLE, so the test never proves the changed guard. Prepare an authorized session fixture, inject the typed error at the reader actually reached, and retain the dispatch-level response assertion.
  • Make the foreign lock reach a required abort operation (P2) - Holding both WAL write locks does not ensure this chat.send fixture encounters contention during Stop: worker-backed reads can succeed, and the stalled provider emits no assistant text requiring aborted-partial persistence. Exact-head CI reaches the final assertion with rpc: resolved, demonstrating that the injected locks did not exercise the response guard. Use a production cancellation scenario that actually requires the contended operation, such as the embedded-owned persistence path, and establish the untyped base failure and typed head result. This concern is supported by newly available CI failure evidence.

Findings

  • [P2] Admit the dispatch fixture and inject at the active read owner — src/gateway/server-methods/sessions.abort-contention.test.ts:21-23
  • [P2] Make the foreign lock reach a required abort operation — src/gateway/server-methods/sessions.abort-contention.real-lock.test.ts:256

Tests

  • Missing end-to-end proof: Both added regressions need intended base-fail/head-pass validation through the current production owners; exact-head CI currently fails before or without the intended contention.
Agent review details

How this fits together

Gateway Stop RPC handlers authorize cancellation, read session state, cancel owned work, and return an outcome that the Control UI presents.

flowchart LR
  A[Control UI Stop] --> B[Gateway RPC authorization]
  B --> C[Session abort handler]
  C --> D[Session and cancellation owners]
  D --> E[Shared contention guard]
  E --> F[Typed Stop notice]
Loading

Technical review

Best possible solution:

Retain the shared Stop classifier and repair both fixtures to exercise contention through the current production owners.

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

Current source establishes the unguarded sessions.abort route, and supplied Gateway traces demonstrate the typed-error difference; this read-only review executed no target code.

Is this the best way to solve the issue?

Sharing the existing classifier at both RPC boundaries preserves cancellation uncertainty without replaying Stop, but the tests must target current readers and a genuinely contended operation.

Full review comments:

  • [P2] Admit the dispatch fixture and inject at the active read owner — src/gateway/server-methods/sessions.abort-contention.test.ts:21-23
    The previously reported blocker remains. This test supplies a narrow sessions.write caller without establishing an admitted session fixture, and its spy targets loadSessionEntry while sessions.abort’s own read uses withGatewaySessionEntry and current main’s delegated lifecycle uses loadGatewaySessionEntryReadOnlyInWorker. Exact-head CI receives INVALID_REQUEST instead of the asserted UNAVAILABLE, so the test never proves the changed guard. Prepare an authorized session fixture, inject the typed error at the reader actually reached, and retain the dispatch-level response assertion.
    Confidence: 0.99
  • [P2] Make the foreign lock reach a required abort operation — src/gateway/server-methods/sessions.abort-contention.real-lock.test.ts:256
    Holding both WAL write locks does not ensure this chat.send fixture encounters contention during Stop: worker-backed reads can succeed, and the stalled provider emits no assistant text requiring aborted-partial persistence. Exact-head CI reaches the final assertion with rpc: resolved, demonstrating that the injected locks did not exercise the response guard. Use a production cancellation scenario that actually requires the contended operation, such as the embedded-owned persistence path, and establish the untyped base failure and typed head result. This concern is supported by newly available CI failure evidence.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 6315f8adc18a.

Provenance checked

  • Typed Stop response keeps the original intent (3b2c61d: Preserve uncertainty after contention because cancellation may already have taken effect.)
  • Stop request logging keeps the original intent (10a8119: Record who requested chat and session stops; the shared wrapper retains the existing logging.)
  • Session cancellation authority keeps the original intent (da27b33: Keep session access and Stop bound to the original caller; the patch preserves the handler’s authority checks.)
  • Partial mock and shrinking baseline changes intended behavior with a stated reason (unknown: The existing mock omitted other exports; importOriginal now preserves them and makes its baseline exception unnecessary. Historical baseline blobs are unavailable locally.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/gateway/server-methods/sessions.abort-contention.test.ts --maxWorkers=1
  • pnpm test src/gateway/server-methods/sessions.abort-contention.real-lock.test.ts --maxWorkers=1
  • pnpm test src/gateway/server-methods/sessions.abort-agent-scope.test.ts --maxWorkers=1
  • Verify both repaired regressions fail against the base production handlers for the intended missing-classification reason and pass with the PR handlers.
  • Run targeted typecheck, lint, and format checks for changed test files.

What I checked:

PR surface

Source +28, Tests +343, Docs +1, Other 0. Total +372 across 8 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 2 56 28 +28
Tests 3 344 1 +343
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 2 1 1 0
Total 8 402 30 +372

Review metrics

Metric Value Why it matters
Production versus test LOC production +56/-28; tests +344/-1 Production growth shares one response guard; test growth covers distinct dispatch and real-transport boundaries, although both new fixtures need repair.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #160004
Summary: The linked issue owns the session Stop classification gap; earlier merged chat contention work covers the neighboring route.

Members:

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

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.

Label justifications:

  • P2: A limited contention case obscures whether Stop took effect; the proposed fix is useful but its added regression fixtures fail.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (18 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-28T02:58:00.983Z sha 50190776e7272dcfdf1223dffea1522ec0f719cc :: needs real behavior proof before merge. :: [P2] [P2] Hold a production state-owner lease in the lock child
  • reviewed 2026-09-28T03:08:31.860Z sha 50190776e7272dcfdf1223dffea1522ec0f719cc :: needs real behavior proof before merge. :: [P2] Hold a production state-owner lease in the lock child | [P3] Describe the current lock mechanism in the CI guide
  • reviewed 2026-09-28T16:41:18.348Z sha 83bf724911438d679682b82e52bad9a07c106c64 :: blocked before merge. :: none
  • reviewed 2026-10-02T01:19:08.979Z sha 83bf724911438d679682b82e52bad9a07c106c64 :: blocked before merge. :: none
  • reviewed 2026-10-02T10:07:40.911Z sha 9e5e04e141e62627c13a200cdf525f4b08a49585 :: blocked before merge. :: none
  • reviewed 2026-10-02T12:36:04.933Z sha 0214010143dc1c36b5681a010f72878593803f10 :: blocked before merge. :: none
  • reviewed 2026-10-07T16:24:11.871Z sha df0ddf8d58dc13f1e7c8c8fa3272901c2d8191fd :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T23:17:21.800Z sha 56cdbff :: needs changes before merge. :: [P2] Inject contention through the current session-read owner

Reviewed October 12, 2026, 7:30 PM ET / 23:30 UTC (Revision 19).

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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. labels Sep 27, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts labels Sep 27, 2026
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 27, 2026
@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/sessions-abort-state-contention branch from a7540f7 to a3ea138 Compare September 28, 2026 01:33
@clawsweeper clawsweeper Bot added merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 28, 2026
@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/sessions-abort-state-contention branch from 250dddf to 5019077 Compare September 28, 2026 02:50
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 28, 2026
@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/sessions-abort-state-contention branch from 83bf724 to 9e5e04e Compare October 2, 2026 10:00
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (9e5e04e141e, replayed as a single commit; reviewed head was 83bf7249114).

Absorption check first: main's #156067 added the typed contention outcome to chat.abort only — sessions.abort still calls handleChatAbortRequestWithLifecycle without any contention catch on current main, so the gap this PR fixes remains live. Verified by reading sessions-abort.ts at origin/main.

Adaptation notes

  • chat-abort-handler.ts: main kept the inline catch from fix: chat turns fail when session state is briefly busy #156067 verbatim (modulo the refactor(gateway): deslop server methods and worker environments #159752 deslop), so the extraction into respondToAbortStateContention + withAbortStateContentionGuard applies with the same shape; handleChatAbortRequest is now defined through the guard, preserving the reviewed message and error shape byte-for-byte.
  • sessions-abort.ts: handler registration wrapped with the shared guard, same as the reviewed head.
  • sessions.abort-agent-scope.test.ts: the importOriginal spread in the chat-abort-handler.js mock reapplies cleanly onto main's consolidated version so the two new exports survive mocking.
  • The two contention proof files land unchanged; the real-lock proof registered in RELEASE_ONLY_RUNTIME_TEST_FILES (sorted position) with its docs bullet after the inventory entry.

Verification on the rebased head (local runner, Node v24.18.0, OPENCLAW_FS_SAFE_NATIVE_MODE=off, C locale)

  • sessions.abort-contention.test.ts + sessions.abort-agent-scope.test.ts: 31 passed.
  • sessions-abort suite: 9 passed; chat-abort* suites (authority / history-budget / lifecycle-internal / chat-abort): passed.
  • server.chat-abort-dispatch-rejection.test.ts: 2 timing-sensitive failures reproduce identically on pristine origin/main in this environment (attachment-staging races), so they are environmental, not caused by this change.
  • Scoped tsgo over all five changed source/test files: clean, zero errors.

@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/sessions-abort-state-contention branch from 9e5e04e to 0214010 Compare October 2, 2026 12:27
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Real-lock proof re-anchored for main's storage evolution (0214010143d).

What CI surfaced: on the first rebased head, sessions.abort-contention.real-lock.test.ts returned rpc: resolved instead of the typed rejection. Investigation (reproduced locally) showed the cause is not the guard but the trigger: since #161124 moved session reads to the row-projection/read-worker tier, reads are served from WAL snapshots and no longer contend with a foreign writer — so a lock held only on openclaw.sqlite covers neither guaranteed surface, and whether the abort's persistence write contended became a race (the old head's CI was green because its base predates #161124 by a day).

Re-anchor: the lock child now holds BEGIN EXCLUSIVE on both the shared-state openclaw.sqlite and the agent database (agents/main/agent/openclaw-agent.sqlite). Reads are conceded to the snapshot tier by design; the locks cover the abort's persistence write whichever store tier it lands in. Header comment and the node-test-lanes.md bullet updated to record the new premise.

Verification on this head (local runner, Node v24.18.0, OPENCLAW_FS_SAFE_NATIVE_MODE=off, C locale)

  • Dual-lock real-lock proof: 3/3 rejected with the typed UNAVAILABLE / errorKind: state_contention outcome; the BEGIN IMMEDIATE probe asserts both files are actually locked.
  • RED control: with the production files reverted to the merge-base bytes, the same proof yields UNAVAILABLE with the raw database is locked: code=ERR_SQLITE_ERROR and no details.errorKind — the unclassified escape this PR fixes — so the typed outcome is produced by the guard, not by main's own machinery.
  • Fast sibling + agent-scope: 31 passed; scoped tsgo over the changed test file: clean.

@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/sessions-abort-state-contention branch from 0214010 to df0ddf8 Compare October 7, 2026 16:17
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Rebased onto current main and fixed the startup-config failure that was red on CI.

Changes since the last reviewed head:

  • Resolved the chat-abort-handler.ts conflict by keeping main's new formatStopRequest logging inside the shared withAbortStateContentionGuard wrapper, so both Stop entry points still log and share the typed contention outcome.
  • Updated the real-lock proof fixture from the retired agents.entries default marker ({ main: { default: true } }) to the canonical keyed shape ({ main: {} }). Current startup config validation rejects the retired marker with Legacy agents.entries default markers need explicit surface owners, which was the cause of the failing checks-node-changed-compact-large shard.

Local verification on the rebased head:

  • sessions.abort-contention.real-lock.test.ts → pass (real Gateway + foreign BEGIN EXCLUSIVE, ~86s)
  • sessions.abort-contention.test.ts → pass
  • oxfmt --check / oxlint clean

Note: sessions.abort-agent-scope.test.ts > kills controlled subagents after the parent run has already ended fails locally with Agent database resource drainage failed in teardown. I reproduced the same failure on plain origin/main with no PR changes applied, so it is a pre-existing main-side issue unrelated to this PR.

@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Closing this to keep room for fixes with a clearer path to landing. The finding is unchanged: sessions.abort still drops the typed state-contention Stop outcome, and the review at head df0ddf8d5 was ready for maintainer review.

It is currently CONFLICTING against main with checks-fast-baseline-ratchets red, and the file it changes (src/gateway/server-methods/sessions-abort.ts) is also touched by #166269, which is automerge-armed — so the diff would need a rebase and a re-proof anyway once that lands.

Branch fix/sessions-abort-state-contention (head df0ddf8d5) is preserved on the fork, so this can be reopened without losing the work.

…s.abort

chat.abort preserves the typed state-contention outcome at the RPC
boundary (openclaw#156067): when a session read fails while cancellation still
takes effect, Stop answers UNAVAILABLE with the contention errorKind
instead of replaying or claiming it had no effect. sessions.abort calls
the same lifecycle but sat outside that guard, so the same busy-window
read failure surfaced as an untyped internal error from the other Stop
entry point.

Extract the contention response into respondToAbortStateContention and
share it through withAbortStateContentionGuard, then wrap the
sessions.abort handler so both Stop entry points return the identical
typed outcome. The fast dispatch proof covers the guard on both entry
points; the real-lock proof (real Gateway, foreign BEGIN EXCLUSIVE on
the live shared-state database) joins the release-only runtime
inventory.

Co-Authored-By: Claude Code <[email protected]>
@wangmiao0668000666
wangmiao0668000666 force-pushed the fix/sessions-abort-state-contention branch from df0ddf8 to 56cdbff Compare October 12, 2026 23:08
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Oct 12, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Closing — handoff (the proof this PR depends on no longer holds on current main)

Not merging this, and the reason is specific enough to record rather than re-derive.

What the change does is not in question. sessions.abort is the only route that can cancel a recovered embedded run, and on current main it still calls handleChatAbortRequestWithLifecycle directly, so a state-contention error escapes untyped while chat.abort classifies it. The guard (respondToAbortStateContention / withAbortStateContentionGuard) and the fast RPC-boundary regression are unchanged and green; the registration is sessions-abort.ts:162.

Why it is closing now. The headline proof — sessions.abort-contention.real-lock.test.ts, which holds BEGIN EXCLUSIVE on the live state and agent databases from a separate OS process and expects the typed refusal — no longer establishes its precondition on current main. Since #169622 ("move bundled session reads and authority into workers", cbc53ac75) the RPC answers before it reaches the contended persistence write:

SESSIONS_ABORT_CONTENTION_LIVE {"rpc":"resolved","payload":{"ok":true,"abortedRunId":null,"status":"no-active-run"}}

Reproduced locally on current main (base 6315f8adc18, Node v24.18.0, through the repository runner): Tests 1 failed (1), 108 s. On the pre-#169622 base (e8b8942affd) the same test passes with the typed payload, and it failed in CI on the merged tree that already contained #169622. The variable is #169622 — not this rebase, and not runner variance.

What a revival needs, in order.

  1. Decide whether the typed-contention path is still reachable for this caller after #169622. If active-run visibility now comes from the worker-owned authority rather than the Gateway's agent-database handles, then "close the agent databases, then take the lock" may no longer produce the state the case needs: either the fixture must build the new state, or the case is unreachable and this PR's value collapses to the fast dispatch regression.
  2. Re-prove RED/GREEN once on the then-current base. The traces currently in the body are valid only for base e8b8942affd.
  3. Re-run the changed-file shard on the rebased head afterwards.

State left behind. Rebased and pushed head 144ca1d8c on fix/sessions-abort-state-contention (the original head was df0ddf8d5). The rebase's only conflict was the sessions-abort.ts import block — main moved abortControlledSubagents / descendantAbortError to chat-abort-descendants.js and ChatSessionEmbeddedAbortOutcome to chat-abort-runtime.types.js; the resolution keeps main's import sources and adds withAbortStateContentionGuard. It also carries the shrink-only config/test-mock-exports-baseline.txt prune that checks-fast-baseline-ratchets asks for (this PR's mock spread makes one grandfathered factory exact). A local worktree rebase onto 6315f8adc18 exists but is not pushed, because the newest base changes nothing about the failing case.

CI classification on the pushed head (so nobody re-derives it): checks-node-changed-compact-large-26 is the real-lock case above. check-lint and check-test-types-core-3 were main's own red — a duplicate storePath declaration in scripts/e2e/mcp-code-mode-gateway-client.ts introduced by #169622 and fixed on main by 62fa09940. auto-response was an infrastructure socket error in the Barnacle bot. Neither belongs to this PR.

Known interaction: #166269 (open, status: 🚀 automerge armed) edits sessions-abort.ts in the dedupe-payload region around :640-680. This change wraps the handler at :162 and does not touch that region, so a revival rebases mechanically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: sessions.abort loses the typed state-contention Stop outcome

1 participant