Skip to content

fix(infra): state-lifecycle lock stays held when a command reaches a closed SQLite worker actor - #158202

Merged
fuller-stack-dev merged 1 commit into
openclaw:mainfrom
jarvis-stephens-bot:fix/sqlite-worker-lifecycle-release
Sep 26, 2026
Merged

fuller-stack-dev merged 1 commit into
openclaw:mainfrom
jarvis-stephens-bot:fix/sqlite-worker-lifecycle-release

Conversation

@jarvis-stephens-bot

Copy link
Copy Markdown
Contributor

Related #158095
Related #157325

What Problem This Solves

Fixes: a gateway stops running agent turns, failing every one with StateDatabaseCoordinatorContentionError: another OpenClaw process owns state-lifecycle while health stays ok, when a SQLite store worker receives a command for an actor that has already been closed.

User Impact

User impact: a closed-actor command no longer leaves the shared state-lifecycle lock held inside the gateway, so later agent turns, idle cleanup, WAL maintenance and cron reconciliation keep acquiring it instead of failing until someone restarts the gateway.

This PR addresses only the first of the two paths listed in #158095. The second (worker retirement awaiting waitForWorkerNativeSections without a timeout in worker-task-pool) is not touched here, so the issue should stay open.

Why This Change Was Made

In src/infra/sqlite-store.worker.ts, executeCommand ran await prepareLifecycle() (which acquires the state-lifecycle coordinator, i.e. BEGIN EXCLUSIVE on the shared lock file) before checking actors.get(request.actor). When the actor was already closed, the "SQLite worker actor is closed" throw happened before the try/finally that calls releaseLifecycle, and the failure reply did not set retire. The broker kept a live, idle worker that still owned the lock, and since the lock is process-wide, every later acquire in the gateway failed.

The fix moves the closed-actor check ahead of the acquisition, which is the order the close branch already uses. Nothing else can throw between prepareLifecycle() resolving and the releasing finally (acquireSqliteWorkerLifecycle releases its own coordinator on internal failure, and the execute-frame path only reaches executeCommand after execute-start verified the actor while pendingInput blocks an interleaved close), so this closes the gap without reshaping the function.

Evidence

Production observation (the motivating incident). On 2026.9.6 (eb377ac), arch-desktop, the gateway logged another OpenClaw process owns state-lifecycle at roughly 1/s from 02:54 on 2026-09-25 until a restart at 11:30 (~915 per 15 min). state_leases / agent_database_leases showed only the live gateway pid as owner and no other openclaw process was alive. Sessions failed with Agent database execution admission is closed (home:main 69, finance:main 19) while health stayed ok; the restart cleared it immediately. This matches the report in #158095 (same version, lock held by the gateway's own pid, health green, restart is the only remedy).

Focused test (src/infra/sqlite-worker-closed-actor.test.ts): spawns the real sqlite-store.worker.ts in a Worker, sends an execute request for a never-opened actor with a broker-style lifecyclePreparation port (accepting check with no borrowed lifecycle so the worker acquires the coordinator itself, then accepting acquired), asserts the reply is the closed-actor failure without retire, and then asserts the main thread can take acquireStateDatabaseCoordinator for the same database/runtime directory.

  • Before the fix (worker change stashed), the test fails with the exact production fingerprint, the holder being the test process itself:
    × releases state-lifecycle when the commanded actor is already closed
      → StateDatabaseCoordinatorContentionError: OpenClaw state database is busy (state-lifecycle). ... holder={"pid":192630,"startTime":58252937,"command":"node","family":"state-lifecycle"}
    
  • With the fix:
    ✓ |unit-fast| src/infra/sqlite-worker-closed-actor.test.ts > releases state-lifecycle when the commanded actor is already closed 2191ms
    Test Files  1 passed (1) / Tests  1 passed (1)
    
    Run as vitest run --config test/vitest/vitest.unit-fast-root.config.ts src/infra/sqlite-worker-closed-actor.test.ts (Node v26.8.1, vitest 5.0.0).

Lint/format: oxlint and oxfmt --check pass on both touched files. Only the focused test was run locally, not the full suite.

🤖 Generated with Claude Code

…losed

In `executeCommand`, `await prepareLifecycle()` acquired the
state-lifecycle coordinator (BEGIN EXCLUSIVE on the shared lock file)
before the `actors.get(request.actor)` check. When the actor had already
been closed, the "SQLite worker actor is closed" throw escaped ahead of
the `try`/`finally` that calls `releaseLifecycle`, and the failure reply
did not set `retire`. The broker therefore kept a live worker that owned
state-lifecycle, and every later acquire in the process, from the main
thread or a reclamation worker, failed with
`StateDatabaseCoordinatorContentionError: another OpenClaw process owns
state-lifecycle` until the gateway was restarted.

Check for the closed actor before acquiring, matching the order the
`close` branch already uses, so nothing can throw between acquisition
and the releasing `finally`.

Add a focused test that drives the worker with an execute request for a
never-opened actor through a broker-style lifecycle preparation port and
then asserts the main thread can still take the state-lifecycle
coordinator. On the previous code it fails with the contention error
naming the test's own pid as holder.

Related openclaw#158095
Related openclaw#157325

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clawsweeper

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

@clawsweeper clawsweeper Bot added P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. 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 25, 2026
@clawsweeper

clawsweeper Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 25, 2026, 12:25 PM ET / 16:25 UTC.

ClawSweeper review

What this changes

The branch makes the SQLite store worker reject a command for a closed actor before acquiring the shared state-lifecycle lock, and adds a worker-thread regression test.

Merge readiness

✅ Ready for maintainer review

Current main still has the lock leak, and this PR addresses a concrete worker exit path. The related gateway outage has another proposed cause, so this branch is a scoped fix rather than a complete resolution of that report.

Priority: P0
Reviewed head: aa3c100f185ed8b990cf02eeedf47200f13b8f89

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused change and real worker lock check provide good evidence for the narrow defect, with no discrete patch bug found.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR reports a before-fix contention failure and after-fix recovery through the production SQLite worker running in a real Worker thread: after the closed-actor reply, the main thread acquires the same coordinator lock. The test supplies a broker-style preparation handshake; it proves this worker lock invariant, while full Gateway incident attribution remains outside its scope. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR reports a before-fix contention failure and after-fix recovery through the production SQLite worker running in a real Worker thread: after the closed-actor reply, the main thread acquires the same coordinator lock. The test supplies a broker-style preparation handshake; it proves this worker lock invariant, while full Gateway incident attribution remains outside its scope. No stored-data contract changes.
Evidence reviewed 6 items Introduced worker change: The PR moves the actor lookup and closed-actor rejection ahead of lifecycle acquisition; the command's later try/finally releases an acquired coordinator.
Current-main need: Fetched main still acquires the coordinator before checking whether the actor exists, leaving the reported throw ahead of the releasing finally.
Worker-boundary proof: The added test starts the production worker in a real Worker thread, sends a closed-actor command over a MessagePort, checks the failure reply, and then acquires the same coordinator from the main thread. The PR body reports the lock-contention failure before the reorder and a passing 2,191 ms test afterward; the reviewer did not execute contributor code.
Findings None None.
Security None None.

How this fits together

The SQLite store worker receives database commands from the broker and acquires a shared lifecycle lock around admitted work. Its replies and lock release determine whether later agent turns and maintenance can use the state database.

flowchart LR
  A[Database command] --> B[SQLite worker]
  B --> C{Actor open?}
  C -- No --> D[Failure reply]
  C -- Yes --> E[Acquire lifecycle lock]
  E --> F[Execute command]
  F --> G[Release lock and reply]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +1, Tests +76. Total +77 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 2 1 +1
Tests 1 76 0 +76
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 78 1 +77

Review metrics

Metric Value Why it matters
Focused regression duration 1 worker-thread test added; 2,191 ms reported The worker boundary is needed to observe whether the cross-thread lifecycle lock is released.

Technical review

Best possible solution:

Keep the worker's closed-actor rejection ahead of lock acquisition, and track the separate worker-retirement investigation in the linked gateway issue.

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

Yes for the narrow worker defect: source shows the pre-fix throw outside the releasing finally, and the PR reports a before-and-after worker-thread lock check. The full gateway incident was not independently reproduced.

Is this the best way to solve the issue?

Yes for this lock leak: rejecting the missing actor before acquisition is a narrow repair. It does not address the separately reported worker-retirement wait.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P0: The reported lock hold can make every agent turn fail until the Gateway restarts.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR reports a before-fix contention failure and after-fix recovery through the production SQLite worker running in a real Worker thread: after the closed-actor reply, the main thread acquires the same coordinator lock. The test supplies a broker-style preparation handshake; it proves this worker lock invariant, while full Gateway incident attribution remains outside its scope. No stored-data contract changes.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR reports a before-fix contention failure and after-fix recovery through the production SQLite worker running in a real Worker thread: after the closed-actor reply, the main thread acquires the same coordinator lock. The test supplies a broker-style preparation handshake; it proves this worker lock invariant, while full Gateway incident attribution remains outside its scope. No stored-data contract changes.

Label justifications:

  • P0: The reported lock hold can make every agent turn fail until the Gateway restarts.
  • 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. Sufficient (terminal): The PR reports a before-fix contention failure and after-fix recovery through the production SQLite worker running in a real Worker thread: after the closed-actor reply, the main thread acquires the same coordinator lock. The test supplies a broker-style preparation handshake; it proves this worker lock invariant, while full Gateway incident attribution remains outside its scope. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports a before-fix contention failure and after-fix recovery through the production SQLite worker running in a real Worker thread: after the closed-actor reply, the main thread acquires the same coordinator lock. The test supplies a broker-style preparation handshake; it proves this worker lock invariant, while full Gateway incident attribution remains outside its scope. No stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Galin Iliev: 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.

@jarvis-stephens-bot

Copy link
Copy Markdown
Contributor Author

CI note: the only red shard is checks-windows-node-test-4, where test/scripts/write-unified-entry-dts.test.ts › reuses unaffected canonical groups while rebuilding runtime after input edits hit the 120 s test timeout (Test timed out in 120000ms); the other 244 tests in that shard passed, and the file is a tooling test unrelated to this change. All other shards are green. Happy to rebase to retrigger if a maintainer prefers.

Field data since opening: the same reorder applied to a 2026.9.6 gateway that had been re-wedging on another OpenClaw process owns state-lifecycle within ~1 h of every restart has now run 8 h / ~200 turns with zero Agent database execution admission is closed failures and no sustained lifecycle contention.

@fuller-stack-dev

fuller-stack-dev commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

Additional maintainer validation on unchanged head aa3c100f185ed8b990cf02eeedf47200f13b8f89 supports this fix and preserves the contributor branch.

The same private fixture exercised the production suspension entry point with a dirty task registry and the updater's completed-step receipt writer. Parent f10369550e488e592e265bab0e73f86246cb1bf6 blocked both for about 5 seconds after a closed-actor request. This head made suspension ready and persisted the receipt before the rejected worker was terminated. A genuinely held writer still refused both operations, and both recovered when it released. Independent source-blind validation passed all six contract clauses across uncontended, finite-writer, held-writer and closed-actor cases.

Local checks on this head passed all 8 cases: the new worker regression in 1.423 seconds and 7 existing lifecycle-cleanup cases covering framed results, queued followers, revoked authority, nested scopes and preparation refusal. The first adjacent-suite attempt did not collect because a filtered install omitted QuickJS; restoring frozen workspace dependencies resolved that setup failure. The new 76-line test was audited in full. Independent AutoReview reported no P0/P1 findings.

Sanitized raw evidence · Artifact manifest

This proves the repaired transition. The cause of the historical operator incident remains unconfirmed. The separate worker-retirement path remains open. The matched Windows file diagnostic passed all 11 tests, including the timed-out case in 95.619 seconds with the unchanged 120-second deadline: https://github.com/openclaw/openclaw/actions/runs/36213627830. The original full shard then passed on unchanged head aa3c100: 16 files across five projects, 383 tests passed and 14 existing platform skips, with the timed-out case completing in 102.130 seconds. This establishes observed timing variability under the original workload; no timing defect was patched, and the original failed attempt remains recorded. No test or deadline changed. Full shard result. Both CI-gate contexts passed before native merge.

Artifact links expire October 3.

@fuller-stack-dev
fuller-stack-dev merged commit a53728b into openclaw:main Sep 26, 2026
170 of 172 checks passed
@fuller-stack-dev

Copy link
Copy Markdown
Member

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 26, 2026
…losed (openclaw#158202)

In `executeCommand`, `await prepareLifecycle()` acquired the
state-lifecycle coordinator (BEGIN EXCLUSIVE on the shared lock file)
before the `actors.get(request.actor)` check. When the actor had already
been closed, the "SQLite worker actor is closed" throw escaped ahead of
the `try`/`finally` that calls `releaseLifecycle`, and the failure reply
did not set `retire`. The broker therefore kept a live worker that owned
state-lifecycle, and every later acquire in the process, from the main
thread or a reclamation worker, failed with
`StateDatabaseCoordinatorContentionError: another OpenClaw process owns
state-lifecycle` until the gateway was restarted.

Check for the closed actor before acquiring, matching the order the
`close` branch already uses, so nothing can throw between acquisition
and the releasing `finally`.

Add a focused test that drives the worker with an execute request for a
never-opened actor through a broker-style lifecycle preparation port and
then asserts the main thread can still take the state-lifecycle
coordinator. On the previous code it fails with the contention error
naming the test's own pid as holder.

Related openclaw#158095
Related openclaw#157325
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

2 participants