Repository navigation
fix(sessions): prevent database lock failures during reclamation - #139469
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. Reviewed September 5, 2026, 9:13 PM ET / September 6, 2026, 01:13 UTC. ClawSweeper reviewWhat this changesLets synchronous transcript writes service cleanup authorization during lock contention and reclaims free space before pruning retained session archives. Merge readiness✅ Ready for maintainer review This remains a useful fix for a source-confirmed lock cycle. The earlier archive-retention blocker is resolved, and no actionable introduced defect was found. Priority: P1 Review scores
Verification
How this fits togetherOpenClaw stores session transcripts in per-agent SQLite databases. Cleanup workers archive and delete session data while foreground runs write transcripts to the same database. flowchart TD
A[Foreground transcript writes] --> B[Short lock admission attempts]
C[Session cleanup worker] --> D[Pending commit request]
B --> D
D --> E[Current cleanup owner check]
E --> F[Commit or rollback and settlement]
F --> B
F --> G[Reclaim free pages]
G --> H[Measure pressure before archive pruning]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +85, Tests +227, Docs +20. Total +332 across 11 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Preserve cooperative write admission, live cleanup fencing, atomic deletion, and physical space reclamation before archive pruning. Do we have a high-confidence way to reproduce the issue? Yes, from source: a synchronous transcript writer can block the parent event loop while the cleanup worker holds the write lock and awaits that parent's authorization. The body supplies a failing-first reproduction; this review did not execute it. Is this the best way to solve the issue? Yes. Retrying only lock admission breaks the dependency without replaying mutations, while the corrected budget ordering preserves retained archives. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 4d8398494f8e. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
4d345bc to
8d9a074
Compare
|
Merged via squash.
|
* origin/main: fix(cli): keep note text with Windows and Unicode line endings (#139512) fix(agents): keep isolated completion context on its admitted generation (#139607) fix: avoid declaration builds during source-server updates (#139392) fix(models): keep discovered models after catalog refresh failures (#139357) fix(gateway): record a transcript notice when a run fails before replying (#139439) refactor(ios): reuse shared integer conversion (#139581) fix(sessions): prevent database lock failures during reclamation (#139469) perf(test): reuse transforms within owned scheduler slots (#139553) test(agents): share sparse transcript input fixtures (#139589) chore(ui): refresh control ui locales (#139481) fix(slack): keep prototype-named emoji shortcodes intact (#136374) fix(gateway): deliver upgrade rejection responses under Bun (#139516) refactor(test): simplify catalog guards and fix native report fixture (#139496) fix(macos): prevent dashboard fixture loopback timeouts (#139556) fix(matrix): preserve selected reply targets inside threads (#139479)
* commit '6c55a99226ed0611ca088004c81b00fb296f1f71': (182 commits) test(ui): scope dashboard settings setup to the top frame (openclaw#139618) refactor(skills): share pending proposal creation (openclaw#139617) fix(release): accept frozen targets before worker bundles (openclaw#136699) fix(gateway): preserve percent sequences in media filenames (openclaw#139508) fix: preserve current update availability alongside update history (openclaw#139501) feat(diagnostics): expose garbage collection duration metrics (openclaw#139592) fix(ui): keep Logbook timestamps clear of the activity stripe (openclaw#139539) fix(ui): keep Swarm outcomes visible after completion (openclaw#139490) test: check file accessibility without runtime-specific return values (openclaw#139590) refactor(sdk): keep helper types private (openclaw#139601) fix(cron): preserve current-session delivery intent (openclaw#139491) fix: prevent browser profile permission hangs in Doctor (openclaw#139612) fix(agents): repair storage-failure test fixture after failover owner move (openclaw#139531) fix(cli): keep note text with Windows and Unicode line endings (openclaw#139512) fix(agents): keep isolated completion context on its admitted generation (openclaw#139607) fix: avoid declaration builds during source-server updates (openclaw#139392) fix(models): keep discovered models after catalog refresh failures (openclaw#139357) fix(gateway): record a transcript notice when a run fails before replying (openclaw#139439) refactor(ios): reuse shared integer conversion (openclaw#139581) fix(sessions): prevent database lock failures during reclamation (openclaw#139469) ...
* commit 'refs/openclaw/tasks/pr-135167-main': (2467 commits) refactor(ios): reuse shared integer conversion (#139581) fix(sessions): prevent database lock failures during reclamation (#139469) perf(test): reuse transforms within owned scheduler slots (#139553) test(agents): share sparse transcript input fixtures (#139589) chore(ui): refresh control ui locales (#139481) fix(slack): keep prototype-named emoji shortcodes intact (#136374) fix(gateway): deliver upgrade rejection responses under Bun (#139516) refactor(test): simplify catalog guards and fix native report fixture (#139496) fix(macos): prevent dashboard fixture loopback timeouts (#139556) fix(matrix): preserve selected reply targets inside threads (#139479) test(gateway): preserve held-work close failures (#139593) refactor(exec): share package argument scanning (#139560) fix(audit): preserve sequence range validation before numeric decoding (#139587) fix(transcripts): retain capture ownership through failed cleanup (#139572) refactor(models): share selector reference traversal (#139571) perf(agents): classify allowlists without intermediate sets (#138392) chore(release): update appcast for 2026.9.2 (#139575) fix(ci): synchronize cloud retries and board widget input (#139506) fix(plugins): explain SDK incompatibilities after core updates (#139458) fix(voice-call): retain installed WebSocket behavior under Bun (#139567) ...
…nclaw#139469) * fix(sessions): prevent database lock failures during reclamation * fix(sessions): reclaim free pages before pruning archives
…nclaw#139469) * fix(sessions): prevent database lock failures during reclamation * fix(sessions): reclaim free pages before pruning archives (cherry picked from commit 4f1bfca)
Problem
Fixes an issue where concurrent Gateway runs fail with
database is lockedwhile session reclamation is committing. This was reported on the Team Gateway and reproduced with two synchronous transcript writers against an isolated SQLite store.The reclamation worker holds
BEGIN IMMEDIATEand waits for the parent's commit-authorization message handler. A synchronous transcript append on the parent waits in SQLite's native busy handler for that same writer lock, preventing the authorization handler from running. The existing settlement barrier cannot satisfy that event-loop dependency.Solution
Keep archive preparation, deletion, and COMMIT on the worker. Publish a distinct authorization-requested state in the existing shared memory. While reclamation is active, synchronous transcript writers use short admission attempts and service that pending request with the existing authority validator before retrying admission. The same admission path covers synchronous transcript replacement and compaction. Once the write transaction begins, its original busy timeout and diagnostics are restored; append callbacks and mutations are never replayed.
Reclamation performs a PASSIVE checkpoint and caps incremental vacuum at 512 pages per pass. Before pruning retained archives, the disk-budget owner drains its initially observed free pages in bounded units, yielding between them and reacquiring the connection after each yield. It retains physical checkpointing before pressure measurements so pending free pages do not cause unnecessary archive deletion. Duplicate history-deletion and initial sweep logic is consolidated while retaining existing snapshot and retention checks.
Design
The parent registers an operation-scoped authorization service before starting the worker and removes it after the worker settles. The service captures the reclamation owner's async context: the admission checks depend on that context to distinguish the owner's own work from competing admissions. The synchronous append invokes the same live authority checks in that captured context, then grants or rejects the shared request.
There is no parent event-loop dependency between authorization and worker COMMIT. The existing synchronous settlement join remains: after granting approval, the parent must not allow queued owner retirement before COMMIT, rollback, or connection-close settlement, including abrupt worker exit. A later queued request returns the already recorded result or failure, so it cannot authorize twice. Authorization rejection belongs to reclamation; unrelated transcript writers can continue after rollback.
The budget drain is limited to its initial freelist, stops when SQLite makes no progress, and never holds a transaction across a yield. Budget measurements retain TRUNCATE checkpointing because PASSIVE alone leaves WAL allocation counted as disk pressure. Archive pruning starts only after this physical reclamation step; the existing archive-selection and retention rules are unchanged.
The original append admission deadline is checked before and after servicing. An already-consumed authorization still requires the safety join, which cannot be abandoned at that deadline. PASSIVE avoids waiting for readers but does not cap the number of WAL frames copied.
This cooperative design and the production LOC exception were explicitly approved by the maintainer on September 5, 2026.
Impact
This fixes a reproduced production deadlock associated with Team Gateway runs failing with
database is locked. The approved net +85 production lines implement the cooperative commit-authorization protocol: shared request publication, idempotent servicing from the parent's synchronous append path, and short admission attempts. They replace an event-loop dependency the old barrier could never satisfy; the settlement barrier itself remains for fencing.Deletion atomicity, visibility, rollback, fencing, and thread ownership are unchanged. There is no schema change, configuration option, retention change, or dependency addition. Incremental vacuum work is now capped at 512 pages per pass. Nearby duplicate deletion and initial pressure-sweep logic offsets part of the additional protocol and bounded-drain code.
Deltas against task base
74b764e81d4b:Evidence
Failing-first: restored the candidate regression in the session-accessor suite, adjusted the schedule so both synchronous append calls run while the actual worker holds the write lock and awaits authorization, and ran it against unchanged production at the task base:
Initial focused proof, before extending replacement coverage:
The additional synchronous replacement variant also failed with checkpoint expiry before its one-line admission fix. Both cooperative authorization outcomes (grant/rejection), owner-context preservation, abrupt worker exits, barrier failures, native rollback, admission races, and bounded real-page reclamation pass. The existing 100,000-event cleanup recorded a maximum heartbeat gap of 201.23 ms, below its 500 ms requirement.
Broader owner proof on the initial PR head, before the retention follow-up:
Total: 3,066 passed, 9 skipped, across 230 passing files and 2 skipped files. The final 100,000-event cleanup measured 200.66 ms maximum heartbeat gap. The final Codex autoreview is scoped-clean through P2. The initial changed-file gate found an authorizer export that had become test-only; it is now private, and the existing settlement/fault tests exercise the production authorization wrapper instead.
The final five-case reclamation regression also passed after a fixture-only lint cleanup.
A review found that simply capping the worker's vacuum could cause disk-budget pruning to destroy a still-retainable compressed archive. The extended existing budget regression reproduced this on the initial PR head: an 8 MiB compressible history needing 4 MiB of reclamation lost the archive (
expected length 1, received 0). The corrected budget ordering retained it. A separate extension of the real-page test failed on the old budget helper (1539pages reclaimed before the first yield exceeded512), then passed with the bounded drain, including two synchronous writer appends and cache close/reopen across a yield. The retention and neighboring suites passed 33 tests; the bounded-drain and budget suites passed 24 tests. The follow-up broad rerun encountered an unchanged shared-state heartbeat startup failure:state lease heartbeat did not become readyunder its one-second lease. It occurred before the maintenance callback ran; the worker, lease owner, test, and busy-timeout helper are byte-identical to the initial green CI head. Replaying the entire unchanged heartbeat file reproduced that one failure with ten passes under high host load. No timeout or assertion was changed. The session and agent-session portions were run separately:That is 2,203 passed, 3 skipped on the retention-safe candidate. Its 100,000-event cleanup measured 115.50 ms maximum heartbeat gap. The follow-up autoreview is scoped-clean through P2.
node scripts/check-changed.mjscompleted successfully again (exit 0), andgit diff --checkpassed.node scripts/check-changed.mjscompleted successfully (exit 0), including core/test typechecks, core lint, dead-export scans, database guards, and zero runtime import cycles.git diff --checkpassed. No Swift app lint lane was selected. No live Team validation was attempted; the coordinator owns that proof after landing. No UI changed.CI status: blocked by an unrelated main-branch test
Exact-head CI for
4d345bcc69b14443c6a8b27a97d7af8308de329ccompleted with failure because ofsrc/agents/embedded-agent-runner/run/assistant-failure.test.ts:273:maybeRetryTransientdoes not exist on the fixture'sfailovertype.undefined is not a spy or a call to a spy.The assertion was added by #139409, commit
c91b1eaab768dd8223a6176c1a24decf98ee1b9c. It is already present in CI's base0cebe40cf7cb939da0c5722a990eb10522d27d5a; CI checked out mergef758ddd9for this head. This PR does not modify that file. The aggregateopenclaw/ci-gatealso failed. The final observed check rollup was 130 passed, 51 skipped, 3 failed, with none pending. The failure needs an upstream repair and a fresh CI run; it is not being folded into this storage change. ClawSweeper reviewed corrected head4d345bcc69b14443c6a8b27a97d7af8308de329cwith no actionable findings and explicitly cleared the earlier archive-retention blocker.Deferred
Durable logical deletion with resumable, bounded physical cleanup remains a separate approval for deletion latency. This fix preserves the existing atomic deletion units; it does not claim a hard bound on cascading deletion cost.
Release-note: Fix transcript writes failing with database lock errors during concurrent session reclamation, and cap incremental vacuum work per pass.