Repository navigation
perf(state): retain SQLite handles for 30 minutes of inactivity - #153601
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: blocked before merge. Reviewed September 20, 2026, 8:56 AM ET / 12:56 UTC (Revision 6). ClawSweeper reviewWhat this changesRetains reusable SQLite connections for 30 idle minutes and coordinates their cleanup to reduce repeated database opens. Merge readiness⛔ Blocked before merge - 3 items remain This remains useful, distinct performance work. Earlier code findings are resolved, and the capacity tradeoff has an explicit maintainer disposition; the repository’s published-updater validation gate remains outstanding. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw’s SQLite owners serve agent data and shared application state to the Gateway and background workers. They manage connection reuse, read admission, and cleanup before database replacement or shutdown. flowchart TD
A[Agent and shared-state operations] --> B[Existing database owners]
B --> C[Check identity and admission]
C --> D[Reuse SQLite connection]
D --> E[Return current committed data]
D --> F[Borrow pins and idle timer]
F --> G[Close after idle expiry]
H[Shutdown or database replacement] --> G
Before merge
Agent review detailsSecurityNone. PR surfaceSource +687, Tests +954, Docs +19, Other +3. Total +1663 across 74 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep connection reuse within the existing lifecycle owners, with upgrade-verified drainage before migration ownership is released. Do we have a high-confidence way to reproduce the issue? Not applicable as a broken-behavior report: this is a performance improvement supported by native-open measurements and current-main eviction code; no tests were executed during this read-only review. Is this the best way to solve the issue? Yes: extending existing connection owners avoids a competing cache or public SDK surface, while preserving per-operation admission and explicit retirement. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against fcc927f58d02. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
57b477f to
d1861b8
Compare
d1861b8 to
3377d6e
Compare
Reuse connections in the existing agent, shared-state, read-worker, and coordinator owners, and align reclamation worker retirement with the same idle window. Preserve explicit lifecycle invalidation with acknowledged worker cleanup, borrow pins, and retries for retained failed cleanup. Keep protected snapshots and native-exit settlement contracts intact. Document focused native-open measurements and lifecycle proof in the PR.
3377d6e to
29fb685
Compare
|
|
Merged via squash.
|
…claw#153601) Reuse connections in the existing agent, shared-state, read-worker, and coordinator owners, and align reclamation worker retirement with the same idle window. Preserve explicit lifecycle invalidation with acknowledged worker cleanup, borrow pins, and retries for retained failed cleanup. Keep protected snapshots and native-exit settlement contracts intact. Document focused native-open measurements and lifecycle proof in the PR.
What Problem This Solves
Repeated agent reads, shared-state Worker reads, and handle-fence acquisitions reopen SQLite unnecessarily. The 64-agent handle cap also makes a 65-agent working set reopen a database on every operation.
User Impact
Reduces SQLite setup and main-thread overhead without changing configuration, schemas, stored-data retention, or update behavior. Reusable connections remain open for 30 minutes without use. Removing count-based eviction means larger active database sets can retain more file descriptors during that window.
Why This Change Was Made
The existing agent, shared-state, reader, coordinator, and reclamation owners share one idle timeout. Borrowers and transactions retain their exact connections; incognito connections keep their explicit lifetime. Close, quarantine, replacement, deletion, WAL checkpoints, and data-version invalidation keep their existing owners.
The existing Node fixed-read Worker pool now retains independent live readers and acknowledges per-path native cleanup before file retirement. It preserves committed-read isolation from native writer transactions. No new pool or public SDK capability is introduced. Task-registry and shared-state write backends already reuse their connections.
Deliberate exceptions remain: private/artifact-preserving snapshots, extension-enabled and nested transaction readers, Bun fixed-read tasks, caller-owned coordinator directories, concurrent independent lock leases, and cold mutation Workers whose native exit proves settlement. Reclamation switching physical databases still joins its original lease/Worker cleanup. The
:memory:runtime/schema initialization results are already memoized per thread; retaining Workers avoids repeating them.Snapshot
owner.sqlitefiles are staging custody records, not application-data copies. Ordinary fixed runtime reads use live handles. Explicit backup/Doctor snapshots and artifact-preserving inspection retain their copy/cleanup contract; aggregate open counts cannot identify their exact caller.Related: #153581, which reuses host verification during native Worker opens. Its verification-adoption change is separate from handle retention.
Evidence
Synthetic local Node 26.8.2 measurements, instrumenting native connection creation:
A newly created coordinator file needs a second open to establish pre-open inode evidence; an existing file uses one connection. These timing samples precede the final CI repairs and integration rebase. Timing varies with host load. These are focused measurements, not a projected reduction for a deployed Gateway.
A synthetic one-thread capacity probe on macOS/Node 26.8.2 measured 200 retained descriptors for 65 warmed agent stores and 389 for 128 (three database/WAL/SHM descriptors per store, one shared store, and two coordinator descriptors). Two further traversals added no descriptors. Explicit agent/shared drainage returned all fixture descriptors and live handles to zero. Process RSS after GC rose from 247.95 MiB before opening to 337.63 MiB at 65 and 359.75 MiB at 128; it remained 356.17 MiB after drainage because handle closure does not promise allocator RSS return. These are sampled retained occupancy and empty-schema memory costs, not a transient OS peak or deployed Gateway sizing estimate. Maintainer disposition: the measured descriptor/memory tradeoff is accepted for the explicitly requested 30-minute idle-only policy. Explicit lifecycle drainage and idle expiry bound connection lifetime; deployed multi-worker peaks remain unmeasured.
The real fixed-read Worker probe observed ten separate peer commits through one connection. Explicit path close released it, and the next read reopened once in the same Worker. Counter and fake-timer tests cover reuse, last-use refresh, 30-minute expiry, borrower pins, quarantine/reopen, physical replacement, and cleanup failures. The new shared-state expiry tests fail against the original cache.
CI verification also caught lifecycle integration gaps. Shared capture stores now hold an idle reference until close, supplied-handle operations refresh inactivity, and capture finalization retains its established ordering before native teardown. Explicitly owned readers survive ordinary validation errors. Native wrapper extraction includes the new runtime modules. Tests preserve revocation and write settlement while checking the new idle policy instead of the removed count-based eviction policy or unrelated global timer counts.
The final integration rebase preserves main's clean-close receipts, native worker verification adoption, and the newer sandbox-registry and execution-approval read commands. A further clean rebase onto
7a1090af25b46be80b8ccd52037aadd443b87c0bpreserves main’s separate input-preparation cleanup in the worker pool alongside retained-resource cleanup. The branch is one commit with its original subject.Validation:
tbx_01m2z5c9d80kmmjgb295wtb440usingnode scripts/run-vitest.mjs(run, provider exit 0; the one-shot lease was stopped).The expanded Linux campaign at
3377d6e7696aa656f7dbdbdbd0aab129a3e6eb70passed all 1,279 tests across 47 files (run, provider exit 0; one-shot lease stopped).The next CI pass exposed two additional fixture assumptions and a Doctor handoff: workspace readiness now expects one reused handle, native Talk awaits explicit close before reconnect, and shared-auth migration joins exact-path source cleanup while maintenance ownership is held. The corresponding exact tests passed in pure-main CI at
61bbd59ea839afe248412898d2e0a2f330cb30e0(run).Known main-existing failure mechanism: the harness cron test reported
Agent worker lease differs from its captured native owner. A synthetic real heartbeat-publication probe reproduces the exact error on both pure main540e91b407b485f963da74776043ac6039947e86and the PR after synchronous shared-state close followed by an inode-preserving file move; awaited close makes both pass. The CI-specific trigger is unproven (local unlink/recreate did not reproduce inode reuse), and the full harness test passes locally in its original order. No change to the lease guard or harness fixture is included.A second known main failure is order-dependent resource-count assertions. Running
src/status/status-text.model.test.tsimmediately beforesrc/state/openclaw-agent-db-resources.test.tsin one non-isolated worker reproduces the same ten failures and 75 passes on both this PR and pure main7ed70e7fc4003967a64524a4361fbd2f279a1cfa. The resource file alone passes all 35 tests. This establishes an existing order-dependent failure on main; no cache/reset or assertion change is included for it. The failed CI shard passed on one rerun; the original failure and pure-main reproduction remain documented here.Final repair validation passed: 320 tests across the six affected files, followed by five targeted migration/maintenance/recovery checks after the error-path fix. The new migration read-failure regression failed before the fix and passed after it; the migration now joins pre-existing resources from the maintenance owner’s final cleanup hook. Fresh independent P0–P2 review is clean, and final core/infra-test types and changed-file lint passed. The four worker-pool integration files passed all 79 tests after the final rebase, and rebased core types passed. Exact-head CI passed on attempt 2 for the final single-commit candidate
29fb68526da047f549c50872190fafd9cf29d358(run).Published-driver compatibility also passed: the installed
[email protected]updater applied the verified candidate source tree through the existing auth-profile survivor lane on Blacksmith Testbox (lease workflow). The first product attempt passed in 163 seconds; automatic auth/session migration checks ran before standalone Doctor, including canonical credentials/order, four completed JSON-import receipts, and archived source bytes. The isolated Gateway started and passed health/readiness/status checks. Build, package validation, and delegated command exited 0; the owned lease is stopped. Successful artifacts do not expose the exact shared-auth relocation receipt; focused migration tests cover that resource handoff.No operator Gateway was changed, and no deployed open-rate measurement was performed. Windows and Bun behavior were not exercised locally; their existing required cleanup exceptions remain intact.