Repository navigation
fix: updates roll back when an idle CLI process recently used an agent database - #175986
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesReleases 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.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherCLI 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +26, Tests +57, Docs +19. Total +102 across 12 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 17, 2026, 10:00 PM ET / October 18, 2026, 02:00 UTC. |
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.
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.
Related: #172772
What Problem This Solves
Fixes: an update still rolls back (or
openclaw update repairexits 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-maintenancelease 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 treatSIGUSR2as 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 toSQLITE_IDLE_HANDLE_TTL_MSand keys on the database process role that entry points already install (cli-oneshotfromsrc/entry.ts/src/index.ts,gatewayfromgateway runandstartGatewayServer). It returns 30 s forcli-oneshotand 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.
sqlite-runtime.openOpenClawAgentDatabasehands 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.openclawentry (local TUI/onboarding) is classifiedgatewaybyresolveCliDatabaseProcessRole, 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
leaseholdercommand reads themainagent database once throughplugin-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):e39ce04Waiting up to 1197 s for OpenClaw process 28476…, thenDoctor could not enter maintenance. Waited 1199 s; OpenClaw process 28476 still has an agent database open.7027486Waiting up to 1197 s for OpenClaw process 42014…, thenAgent databases closed after 28 s; continuing Doctor maintenance.44a340b(earlier revision)Agent databases closed after 28 sUpdate-time Doctor from source (
OPENCLAW_UPDATE_IN_PROGRESS=1 pnpm openclaw doctor --fix --non-interactive):maintenance deferred). The lease was still held at 16:46:39.Doctor complete.) with the holder alive and printed no wait.Published driver 2026.10.3 × candidate (
scripts/e2e/published-driver-update-docker.sh, driver2026.10.3, candidate packed from44a340b; 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:openclaw doctorran 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 recordedfinished/rolled-back.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 itsagent_database_leasesrow at 30 s (read throughreadActiveOpenClawAgentDatabaseLeasesReadOnly, 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 forcli-oneshotand at 30 min forgateway.pnpm test <file> --maxWorkers=1wall 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.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, andsession-accessor.sqlite-reclamation-worker.test.ts. All passed.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 failedsession-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).src/state,src/config/sessions, and thensrc/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 maine39ce04on this host.pnpm tsgo:coreandpnpm tsgo:core:testpassed. Type-aware oxlint on the changed source and test files, oxfmt,pnpm format:docs:check, andgit diff --checkare clean. No new source file, sowrapper-components.txtneeds no line (sqlite-handle-lifecycle.tsis already listed).Gaps
update repairrun is the closest proof today.cli-oneshot. Embedders that install no role keep 30 minutes, and so does the bareopenclawTUI entry, which is classifiedgateway.