Repository navigation
fix(sqlite): avoid main-thread stalls during maintenance lease checks - #166331
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 October 6, 2026, 9:08 PM ET / October 7, 2026, 01:08 UTC (Revision 5). ClawSweeper reviewWhat this changesThe PR checks SQLite maintenance ownership through the already-held write transaction, preserves renewal admission checks, and adds a regression against redundant readers. Merge readiness✅ Ready for maintainer review Keep open: current main and the latest release still contain the redundant ownership check. The focused repair has sufficient production proof, successful exact-head CI, and no actionable findings. Likely related people: steipete (medium-confidence routing candidate). Priority: P2 Review scores
Verification
How this fits togetherDoctor and database migrations acquire a maintenance lease before repairing agent databases. The lease wrapper validates ownership and keeps pending maintenance work protected until it settles. flowchart TD
A[Doctor or migration] --> B[Acquire maintenance lease]
B --> C[Held SQLite write transaction]
C --> D[Check scope and durable ownership]
D --> E[Perform maintenance]
E --> F[Settle pending work]
F --> G[Release lease]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource -1, Tests +24. Total +23 across 2 files. View PR surface stats
Review metricsNone. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Use the existing lease owner's transaction-aware validation while retaining durable ownership, heartbeat, and maintenance settlement safeguards. Do we have a high-confidence way to reproduce the issue? Yes, from source: existing-schema maintenance calls the independent reader before transaction-aware validation. The supplied negative control reproduces that redundant-reader defect; this read-only review did not execute tests. Is this the best way to solve the issue? Yes. Delegating to the existing transaction-aware owner removes the redundant work without introducing another owner or weakening the existing validation contract. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 7b66485dcd9b. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
Keep the ownership, admission, and renewal checks in their existing order while removing the single-use helper left after maintenance API cleanup. Retain the transaction-aware ownership repair and its regression from openclaw#166331.
|
Merged via squash.
|
…openclaw#166331) * fix(state): validate maintenance leases on held transactions * refactor(state): inline maintenance renewal admission guard Keep the ownership, admission, and renewal checks in their existing order while removing the single-use helper left after maintenance API cleanup. Retain the transaction-aware ownership repair and its regression from openclaw#166331. --------- Co-authored-by: Peter Steinberger <[email protected]>
What Problem This Solves
Fixes redundant SQLite snapshot and integrity work while Doctor and migration maintenance hold a write transaction. The reported symptom is repeated multi-second main-thread stalls during maintenance, making OpenClaw unresponsive.
Fixes #166330
User Impact
Maintenance validates its lease on the already-held connection, avoiding independent read-only snapshots inside that transaction. This is a sanctioned synchronous lock/lease primitive used by Doctor and migrations; the repair shortens that work rather than moving it to a worker. It does not establish complete live Gateway recovery or graceful shutdown. No configuration, schema, public API, FIFO, integrity policy, stored-data, or update/migration contract changes.
Why This Change Was Made
Route transaction-aware validation directly to the existing lease owner while retaining scope lifetime, expiry, durable ownership, heartbeat responsiveness, the durable recheck after heartbeat waiting, and shared first-failure latching. Main at
7880834c19616still had the redundant no-argument ownership check; its affected production file matches the merge-base version used below.Original fix by @sasan1200 (Sasan Sotoodehfar); maintainer cleanup by Peter Steinberger inlines the now-single-use renewal admission guard without changing check order. The contributor's real-SQLite regression is retained unchanged. The former helper's other callers were removed in #154776 and #157413.
Evidence
Validated head:
46a4314aa762de5af7150898bea191981756f5f4.oxfmt --check, scopednode scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json, andgit diff --checkpassed. Lint used the supported parent dependency directory after its initial missing-local-dependencies refusal; no install or tests ran on the maintainer host.cbx_9169e79aa4ff: trusted-main bootstrap verified the full head, IMDSv2 no-role boundary, and toolchain pins; no hydration or Tailscale. Node 24.21.0, pnpm 12.5.1. Lease stopped and release verified.On the same lease, restore only the production file to merge-base
f215c401e69a22547b31b9e1a2436944ab9528a7, keeping the regression unchanged:The negative control failed as intended (exit 1, 29.18 s command wall time):
LOC vs
origin/mainmerge base: production +12 / -13 = -1 (openclaw-agent-db-maintenance-lease.ts); tests +24 / -0 = +24 (openclaw-agent-db-maintenance.test.ts). No tooling or dependency changes.Test cost: the three-file
pnpm test ... --maxWorkers=1command took 59.91 s including worker preparation; the changed file's 19 cases reported 17.352 s in total, including 0.932 s for the new regression. The two-file infrastructure shard took 29.48 s. These existing native SQLite/worker lifecycle cases cover integrity, exclusion, expiry, cancellation, and settlement; no timers, sleeps, or polling were added. A separate single-file wall time was not measured. Exact-head hosted CI was still running at this update, so final hosted CI seconds remain pending; the AWS results above are completed exact-head proof.Contributor production and CLI proof at the original head (historical evidence)
The following evidence belongs to original contributor head
91861fd6289c48a66e8c9ad07a1f8f71c2a2147f, not the maintainer cleanup head above. Its original scope and limitations are preserved.Runtime proof at the submitted head
Source head:
91861fd6289c48a66e8c9ad07a1f8f71c2a2147f. The checkout was clean; runtime build and postbuild stamps both identify this SHA withinputsClean=true. The runtime-only build succeeded with declaration generation skipped.This execution used the production Doctor SQLite contribution, calling
noteDoctorAgentMemorySchemaHealth({ env: process.env, shouldRepair: true })with real SQLite, maintenance ownership, heartbeat, admission, and migration code; no mocks in that path.The isolated state contained a retained WAL-aware copy of the reported shared-state database (147,095,552 bytes) and a read-only WAL-aware backup of one existing agent database (692,224 bytes). Its registry has 15 agents, but only one agent database was copied. A synthetic no-op trigger named
memory_index_chunk_provenance_after_insertwas added to that copy to require an actual repair. It is controlled fault injection, not a recovered historical trigger definition. The production repair removed it; a subsequent read-only schema query confirmed it was absent. Live databases and gateway services were not modified.Redacted diagnostic output and measured result:
{ "head": "91861fd6289c48a66e8c9ad07a1f8f71c2a2147f", "entry": "Doctor SQLite maintenance contribution", "wallMs": 5423.811, "cpuMicroseconds": { "user": 3533981, "system": 602704 }, "maxResidentSetKiB": 962704, "eventLoopDelayMaxMs": 622.33, "eventLoopDelayP99Ms": 12.714, "repairedCount": 1, "warningCount": 0, "exitCode": 0 }time -ltime -lLimits: This is one measured replay of the production SQLite contribution on copied real state with a controlled repair trigger. It is not a full 15-agent gateway run, a matched before/after benchmark, or proof that normal gateway shutdown is restored. Initial CLI replay attempts failed on copied plugin paths, missing packages, and an added sandbox that blocked native workers. Those failed attempts are retained; the subsequent successful CLI runs after repairing the isolated setup are documented below. The measured RSS and event-loop delay show remaining resource and responsiveness costs. No percentage speedup or elimination of system drain is claimed.
The original reported transaction holds (3.706–4.417 s each) are in the linked issue. They measure individual held transactions, whereas the 5.424 s above measures the complete SQLite contribution; these durations must not be treated as a before/after comparison.
Successful CLI replay after plugin setup repair
The unchanged head
91861fd6289c48a66e8c9ad07a1f8f71c2a2147falso completed the CLI entry point:This used OpenClaw's built-in private rehearsal contract, real copied SQLite state, and normal plugin discovery. Plugin install paths were rebased to isolated payloads; missing Reddit and Gmail packages were restored at their recorded versions using the supported installer. The kitchen-sink archive matched the saved SHA-256/SHA-512 record, was restored and migrated, then its unused legacy test fixture was retired from the replay inventory through the supported uninstall lifecycle, with its files retained. Live plugin inventory was not changed.
The repair run exited 0 in 48.556 s and reported completion of deferred Firecrawl, Lossless, and kitchen-sink state migrations. The following fresh diagnostic run exited 0 in 25.764 s. Its complete captured stdout/stderr contain no unfinished-plugin-upgrade, failed-payload, setup-descriptor, npm-permission, worker-spawn, or migration-refusal messages. Expected rehearsal and offline gateway advisory notes remain in the retained logs.
Host load is shared-machine context, not load attributable to this patch. The repaired shared-state copy is 119,705,600 bytes after Doctor reclamation, with one registered agent database; the retired legacy provenance trigger is absent. This final diagnostic pass follows the successful repair and is not a second timed repair benchmark.
Scope: The full CLI process completed, but the built-in rehearsal defers live channel/provider services and advisory inspections, including auth profiles, structured plugin health, skills, and memory search. Gateway activation and service repair were disabled. This establishes successful copied-state CLI maintenance after setup repair; it does not establish full live-gateway health, graceful shutdown, or removal of all resource drain. No synthetic replacement log or deleted warning lines are used.
Raw stdout SHA-256:
2ebfcdaf9f1213b3abe81e7a0efc481432180c014af623ee67b140a9f89c5552; raw stderr SHA-256:0649fafdc605ae5061f539dd83f328985832834ad847ab8ac9d184f8c3e1f1d5. Complete originals, redacted copies, failed attempts, and the exact-head measurement manifest are retained by the contributor.Hosted CI for this head
CI run 37543677058 is completed with conclusion
success; its recordedhead_shais91861fd6289c48a66e8c9ad07a1f8f71c2a2147f. This updates the earlier unavailable-CI status. Full local build/check/test suites were not run; the runtime-only build and focused tests above are scoped local evidence. ClawSweeper Revision 2 reviewed this unchanged head and accepted the earlier scoped production Doctor proof, reporting no before-merge blocker and requesting maintainer review. The new CLI evidence above supplements that accepted proof.