Skip to content

fix: updates roll back when an idle CLI process recently used an agent database - #175986

Merged
RomneyDa merged 1 commit into
mainfrom
fix/agent-db-idle-lease-release
Oct 18, 2026
Merged

RomneyDa merged 1 commit into
mainfrom
fix/agent-db-idle-lease-release

Conversation

@RomneyDa

@RomneyDa RomneyDa commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Related: #172772

What Problem This Solves

Fixes: an update still rolls back (or openclaw update repair exits 2) with "An agent database is in use" when another OpenClaw CLI process, such as a plugin command, used an agent database in the last 30 minutes and is now sitting idle.

User Impact

Updates no longer wait out an idle CLI process. A CLI process now closes an unused agent database about 30 seconds after its last use, so Doctor's existing lease wait from #172772 ends shortly after that process goes idle. The Gateway keeps its 30-minute reuse window. Work that is still running (a borrowed handle or an open transaction) keeps its lease, and Doctor waits for it as before.

Update behavior: the change lives in the process holding the database, not in Doctor. It helps updates away from a release that contains it. A process started from an older release, including every 2026.10.3 process during the 2026.10.3 → next update, keeps the 30-minute window and can still outlast Doctor's ~20-minute wait. Operators should stop such processes before updating; the docs now say so. No config, schema, lease rows, or stored data change.

Why This Change Was Made

An idle agent database handle keeps its lease row until its idle timer fires, and Doctor maintenance needs every lease gone. #172772 makes Doctor wait, but the idle timer was 30 minutes in every process, longer than the wait.

Mechanism choice. I first looked for a way to tell an idle holder in another process that maintenance was requested (the core:agent-database-maintenance lease idea). There isn't one without new infrastructure: Doctor deliberately releases its locks while it waits, the holder is idle so it never rereads state, SQLite has no cross-process notification other than polling (data_version, or watching the WAL), and signalling the holder PID is unsafe (an old release or a non-OpenClaw handler would treat SIGUSR2 as fatal) and unavailable on Windows. Every option is either freshness polling, which AGENTS.md forbids, or a new IPC/sidecar owner. So I took the simpler alternative: CLI processes don't keep the 30-minute idle cache.

Why the 30 minutes exists. #153601 (perf(state): retain SQLite handles for 30 minutes of inactivity) added it to stop reopening on every operation. Its measurements are Gateway-style workloads (paced reads, many warm agent stores, reclamation every 61 s), and the PR records a maintainer decision to accept the descriptor/memory cost for a 30-minute idle-only window. Nothing relies on it for correctness: callers that need the exact connection across awaits borrow it. A 30-second window still covers a command's bursts (100 reads over 60 s still reuse one handle).

Where the policy lives. resolveAgentDatabaseIdleHandleTtlMs() sits next to SQLITE_IDLE_HANDLE_TTL_MS and keys on the database process role that entry points already install (cli-oneshot from src/entry.ts/src/index.ts, gateway from gateway run and startGatewayServer). It returns 30 s for cli-oneshot and 30 min otherwise. The three owners that keep an agent lease while idle use it: the handle cache (refreshAgentDatabaseIdleTimer), the idle executor pool (openclaw-agent-execution-owner), and the session reclamation Worker. The existing close paths are reused unchanged. Worker threads install no role and keep the shared window; their handle is pinned by the executor generation and retired by the parent thread's owner, which follows the role. Embedders that install no role keep today's behavior.

Busy work is unchanged: borrowers and open transactions still postpone the idle close, and FIFO admission, live-authority and integrity checks, and write settlement are untouched. This is lifecycle mechanics, not data retention, so it stays inside the repair-and-land scope of the storage checkpoint.

Known tradeoffs.

  • A CLI process that went idle for more than 30 s reopens the database, claims a new lease, and re-registers. That's a cost, not a correctness change.
  • The deprecated sqlite-runtime.openOpenClawAgentDatabase hands out an unborrowed handle. A plugin CLI command that keeps that raw handle across awaits for more than 30 s now finds it closed, where before it had 30 minutes. That API is deprecated with removal planned, and borrowing (borrowOpenClawAgentDatabase, withOpenClawAgentDatabaseAsync) keeps the handle open.
  • The bare openclaw entry (local TUI/onboarding) is classified gateway by resolveCliDatabaseProcessRole, so it keeps the 30-minute window. It already holds the embedded state lock for its whole life, so an update contends with it either way.

Evidence

All times are PT on 2026-10-17. The holder in every run is a real OpenClaw CLI process: a synthetic local plugin whose leaseholder command reads the main agent database once through plugin-sdk/sqlite-runtime (withOpenClawAgentDatabaseAsync), then stays alive doing nothing (a ref'd no-op timer). Doctor runs from the candidate in every run, so only the holder's version differs. State is isolated and synthetic. No operator Gateway was touched.

openclaw update repair (candidate package installed in an isolated npm prefix):

Holder version Holder idle Doctor Lease Result
main e39ce04 18:11:14 Waiting up to 1197 s for OpenClaw process 28476…, then Doctor could not enter maintenance. Waited 1199 s; OpenClaw process 28476 still has an agent database open. still held at 18:31:18 exit 2, Doctor and plugin maintenance pending
this head 7027486 19:11:48 Waiting up to 1197 s for OpenClaw process 42014…, then Agent databases closed after 28 s; continuing Doctor maintenance. gone by 19:12:19, holder still alive exit 0 at 19:13:32
candidate 44a340b (earlier revision) 18:07:52 same wait, Agent databases closed after 28 s gone by 18:08:23 exit 0 at 18:10:16

Update-time Doctor from source (OPENCLAW_UPDATE_IN_PROGRESS=1 pnpm openclaw doctor --fix --non-interactive):

  • main holder idle from 16:22:09: Doctor waited 1199 s and refused at 16:45:02 (maintenance deferred). The lease was still held at 16:46:39.
  • candidate holder idle at 17:02:59: its lease was gone by the next 1 s observation after 30 s (17:03:30), with the process still alive. Doctor then completed (Doctor complete.) with the holder alive and printed no wait.

Published driver 2026.10.3 × candidate (scripts/e2e/published-driver-update-docker.sh, driver 2026.10.3, candidate packed from 44a340b; the only difference from this head is the reclamation-Worker timer and test reshaping). The holder runs the driver's own 2026.10.3 binary, because during a real 10.3 → candidate update every pre-existing process is 10.3. I first tried a candidate-version holder. It can't open state there: the 10.3 Gateway owns it and the candidate schema migration is pending ("refused shared state schema mutation…"). So this cell shows the documented gap, not the fix:

  • 18:11:26: the holder is idle. 18:13:44: the Gateway's leases are gone and only the holder's remains.
  • Activation openclaw doctor ran 18:16:51–18:36:55: Doctor could not enter maintenance. Waited 1199 s; OpenClaw process 1082 still has an agent database open. The update rolled back to 2026.10.3 and the run recorded finished / rolled-back.
  • This is the expected old-holder behavior. The fix takes effect for updates away from a release that contains it.

Published driver 2026.10.3 × this head 7027486, no holder (same script, unmodified): PASS published 2026.10.3 → candidate 2026.10.4 (7027486d01b3…): finished, readyz=200, running version verified, exit 0 at 19:10:52. The update path is not regressed.

Tests (each new test fails with the production change reverted and passes with it):

  • openclaw-agent-db.lease-owner.test.ts: a CLI process's idle handle releases its agent_database_leases row at 30 s (read through readActiveOpenClawAgentDatabaseLeasesReadOnly, the reader Doctor's wait uses). A borrowed handle in the same process keeps its row until release, and a Gateway keeps its row for 30 min.
  • openclaw-agent-execution.idle.test.ts: a CLI process's warm executor retires at 30 s.
  • session-accessor.sqlite-reclamation-reuse.test.ts: a real reclamation Worker retires at 30 s for cli-oneshot and at 30 min for gateway.
  • pnpm test <file> --maxWorkers=1 wall times (Node; Vitest duration in parentheses): lease-owner 12 s (4.7 s), execution idle 7 s (5.0 s), reclamation reuse 26 s (23.4 s; the existing file uses real Workers, and the new case adds one more Worker cycle). Fake timers only, no sleeps.
  • Node pass: 150 tests across the touched suites plus doctor-maintenance.agent-lease-wait, contention-wait, settlement, both migration-refusal suites (src/commands/doctor-maintenance.migration-refusal.test.ts, src/flows/doctor-health.migration-refusal.test.ts), openclaw-agent-worker-store.test.ts, and session-accessor.sqlite-reclamation-worker.test.ts. All passed.
  • Bun pass (OPENCLAW_VITEST_RUNTIME=bun, also this host's default) on the new and changed tests: all passed. One earlier Bun run of the full set failed session-accessor.sqlite-reclamation-worker.test.ts › retains a late lease receipt… (established) once. It passed on 3 later runs with this change and on main, and that file's behavior is unchanged in the final head (role undefined keeps 30 min).
  • Wider sweeps under heavy host load: src/state, src/config/sessions, and then src/commands src/flows src/gateway src/infra src/plugins src/proxy-capture src/cli extensions/memory-core. The second sweep's 32 failing files were rerun alone: 29 passed. The remaining 3 (node-workspace-upload-reader, sessions-create-worktree-base, server.startup-websocket-race) fail identically on main e39ce04 on this host.
  • pnpm tsgo:core and pnpm tsgo:core:test passed. Type-aware oxlint on the changed source and test files, oxfmt, pnpm format:docs:check, and git diff --check are clean. No new source file, so wrapper-components.txt needs no line (sqlite-handle-lifecycle.ts is already listed).

Gaps

  • Processes started from a release without this change keep the 30-minute window (the 10.3 cell above), so the next update from 2026.10.3 still needs the operator to stop such processes. The docs now say so.
  • The positive published-driver cell (a fixed-version holder during a published update) can't run until a published release contains this change. The candidate × candidate update repair run is the closest proof today.
  • The mechanism is keyed on cli-oneshot. Embedders that install no role keep 30 minutes, and so does the bare openclaw TUI entry, which is classified gateway.

@clawsweeper

clawsweeper Bot commented Oct 18, 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.

@RomneyDa RomneyDa changed the title fix: updates wait out an idle CLI process holding an agent database fix: updates roll back when an idle CLI process recently used an agent database Oct 18, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 18, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 18, 2026
@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Releases idle agent database leases after 30 seconds in CLI processes while preserving the Gateway’s 30-minute reuse window.

Example: A plugin CLI command reads the main agent database once and remains alive while openclaw update repair runs.

  • Before: The idle lease lasts 30 minutes, outlasting Doctor’s roughly 20-minute wait and causing exit 2.
  • After: The fixed holder releases its lease after about 30 seconds; the supplied repair run continues and exits 0.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, source-consistent lifecycle repair with useful shipped-command evidence; required successful upgrade validation remains incomplete.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An update can roll back, or update repair can fail, while an otherwise idle CLI process retains an agent database lease.
Reason: The maintainer-authored direction addresses a demonstrated timeout mismatch and explicitly accepts the old-holder limitation and shorter raw-handle lifetime.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a demonstrated update failure through the existing lifecycle owners, and no introduced correctness defect was found.

Priority: P2
Reviewed head: 7027486d01b355b2450e13c961cba98f413ca456

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Record a successful latest-stable published-updater-to-candidate run with no old holder, verifying retained settings and session data; a fixed-version holder in an already published release is not required.
Agent review details

How this fits together

CLI and Gateway operations use cached agent database handles, executors, and reclamation workers; their lifecycle owners retain leases during work and release them on closure so Doctor can enter maintenance.

flowchart TD
  A[CLI or Gateway entry point] --> B[Database process role]
  B --> C[Shared idle timeout policy]
  C --> D[Existing agent database owners]
  D --> E[Borrowed or active work]
  D --> F[Idle close and lease release]
  F --> G[Doctor maintenance admission]
Loading

Technical review

Best possible solution:

Keep the role-aware timeout in the existing lifecycle owners and complete the required published-updater validation before merging.

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

Yes: current-main lease retention exceeds Doctor’s wait budget, and the supplied real CLI holder trace demonstrates the resulting refusal; this read-only review did not execute a reproduction.

Is this the best way to solve the issue?

The timeout policy is a small producer-side fix using existing role and lifecycle owners, avoiding a new cross-process notification mechanism while preserving active-work custody.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Agent handle, executor, and reclamation idle retention changes intended behavior with a stated reason (6c84ca1: Retain reusable connections to reduce repeated opens; later executor work retained a bounded warm pool for agent switching.)
  • Detached native idle cleanup keeps the original intent (0e1d935: Prevent retained cleanup from inheriting an expired worker-task admission context.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned change and current-main behavior: The introduced diff changes the three existing idle-lease owners. Fetched main still uses the unconditional 30-minute timeout, and its intervening changes do not alter these production paths. (src/infra/sqlite-handle-lifecycle.ts:16, 7027486d01b3)
  • Active work retains custody: Native idle closure still postpones closure for borrowers and open transactions; executor release settles accepted work before scheduling retirement, and reclamation clears its idle timer during use. (src/state/openclaw-agent-db-lifecycle.ts:267, 7027486d01b3)
  • Shipped CLI behavior evidence: The complete live PR body reports isolated plugin CLI holders and candidate update repair: the main holder retains its lease until Doctor refuses, while the candidate holder remains alive, releases its lease, and allows repair to exit 0. (7027486d01b3)
  • Original performance rationale: perf(state): retain SQLite handles for 30 minutes of inactivity #153601 introduced 30-minute reuse to reduce repeated opens and explicitly accepted its resource cost; this maintainer-authored PR explains the narrower CLI timeout while retaining Gateway reuse. (src/infra/sqlite-handle-lifecycle.ts:4, 6c84ca109479)
  • Accepted compatibility limits: The maintainer explicitly records that older running holders retain their old timeout and deprecated unborrowed SDK handles can now close after 30 seconds; borrowing remains the supported way to retain an exact connection across awaits. (src/plugin-sdk/sqlite-runtime-legacy.ts:34, 7027486d01b3)
  • Upgrade validation remains incomplete: The update contract requires published-driver-to-candidate proof. The body records an expected old-holder rollback and still marks the no-holder upgrade run as running, without a successful upgrade and preserved-state result. Public docs: docs/install/updating.md. (docs/install/updating.md:36, 7027486d01b3)

Likely related people:

  • Peter Steinberger: Raw commit 6c84ca1 adds src/infra/sqlite-handle-lifecycle.ts:2 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6c84ca109479; files: src/infra/sqlite-handle-lifecycle.ts)
  • Vincent Koc: Raw commit 0e1d935 adds src/state/openclaw-agent-db-lifecycle.ts:286 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0e1d935b007e; files: src/state/openclaw-agent-db-lifecycle.ts)

PR surface

Source +26, Tests +57, Docs +19. Total +102 across 12 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 32 6 +26
Tests 3 84 27 +57
Docs 4 21 2 +19
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 137 35 +102

Review metrics

Metric Value Why it matters
Agent database idle timeout CLI: 30 minutes → 30 seconds; Gateway: unchanged Bounds idle CLI lease retention within Doctor’s wait budget without adding a configuration option.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A demonstrated update failure affects the limited case of long-lived CLI processes retaining an idle agent database.
  • merge-risk: 🚨 compatibility: Deprecated raw SDK handles retained across awaits can close sooner; the maintainer explicitly accepts this behavior and identifies borrowed-handle alternatives.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete the successful published-updater-to-candidate compatibility run with preserved settings and session data.

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.

Reviewed October 17, 2026, 10:00 PM ET / October 18, 2026, 02:00 UTC.

@RomneyDa
RomneyDa enabled auto-merge (squash) October 18, 2026 17:58
@RomneyDa
RomneyDa merged commit f8ce98e into main Oct 18, 2026
165 of 167 checks passed
@RomneyDa
RomneyDa deleted the fix/agent-db-idle-lease-release branch October 18, 2026 17:58
steipete added a commit that referenced this pull request Oct 18, 2026
The 30-second CLI idle window introduced in #175986 is consumed through resolveAgentDatabaseIdleHandleTtlMs by the handle cache, executor pool and reclamation worker. Keep the implementation constant private and let its three consumer tests independently assert the documented 30-second boundary. No lifetime, lease or role behavior changes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 19, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 19, 2026
The 30-second CLI idle window introduced in openclaw#175986 is consumed through resolveAgentDatabaseIdleHandleTtlMs by the handle cache, executor pool and reclamation worker. Keep the implementation constant private and let its three consumer tests independently assert the documented 30-second boundary. No lifetime, lease or role behavior changes.
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

1 participant