Skip to content

fix(sqlite): avoid main-thread stalls during maintenance lease checks - #166331

Merged
steipete merged 2 commits into
openclaw:mainfrom
sasan1200:fix/sqlite-maintenance-transaction
Oct 7, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
sasan1200:fix/sqlite-maintenance-transaction

Conversation

@sasan1200

@sasan1200 sasan1200 commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

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 7880834c19616 still 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.

  • Static checks: scoped oxfmt --check, scoped node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json, and git diff --check passed. Lint used the supported parent dependency directory after its initial missing-local-dependencies refusal; no install or tests ran on the maintainer host.
  • Independent Codex branch review and final candidate review: scoped-clean through P2. ClawSweeper's latest review had no actionable findings; its earlier production-proof request was already satisfied by the contributor evidence below.
  • Secretless AWS Crabbox lease 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.
  • Positive check: core types and all 52 tests passed in 76.45 s combined wall time; the test command took 59.91 s.
pnpm tsgo:core && pnpm test src/state/openclaw-agent-db-maintenance.test.ts src/state/openclaw-state-lease-existing.test.ts src/state/openclaw-state-db-existing-write.test.ts --maxWorkers=1

On the same lease, restore only the production file to merge-base f215c401e69a22547b31b9e1a2436944ab9528a7, keeping the regression unchanged:

git checkout f215c401e69a22547b31b9e1a2436944ab9528a7 -- src/state/openclaw-agent-db-maintenance-lease.ts
pnpm test src/state/openclaw-agent-db-maintenance.test.ts --maxWorkers=1 -t 'checks maintenance authority on the held transaction without opening separate readers'

The negative control failed as intended (exit 1, 29.18 s command wall time):

AssertionError: expected "withOpenClawStateDatabaseReadOnly" to not be called at all, but actually been called 2 times
Tests 1 failed | 18 skipped (19)

LOC vs origin/main merge 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=1 command 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 with inputsClean=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_insert was 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:

Doctor changes
- Agent <agent>: removed memory_index_chunk_provenance_after_insert
  (<isolated-state>/agents/<agent>/agent/openclaw-agent.sqlite)
{
  "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
}
Measurement Observed after-fix value
Doctor SQLite contribution wall time 5.424 s
Node process CPU time during contribution 3.534 s user + 0.603 s system
Average CPU during contribution 76.3% of one core equivalent
Node process peak RSS 940.14 MiB
Maximum / p99 event-loop delay, 10 ms sampling 622.330 / 12.714 ms
Whole launcher wall time, native time -l 6.73 s
Whole launcher and children CPU, native time -l 8.47 s user + 1.95 s system
Repair result 1 repaired, 0 warnings, exit 0

Limits: 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 91861fd6289c48a66e8c9ad07a1f8f71c2a2147f also completed the CLI entry point:

node scripts/run-node.mjs --profile <isolated-profile> doctor --fix --non-interactive --no-workspace-suggestions --no-color

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.

[state/agent-db] agent database clean-close receipt: written
Doctor complete.
exit_code=0
timeout=false
Final diagnostic measurement Observed value
Wrapper wall time 25.764 s
Native launcher wall time 25.73 s
Native process and children CPU 15.08 s user + 12.04 s system
Native maximum RSS 976,961,536 bytes (931.703 MiB)
Host load average before, 1/5/15 min 2.185 / 1.932 / 3.293
Host load average after, 1/5/15 min 4.027 / 2.360 / 3.405

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 recorded head_sha is 91861fd6289c48a66e8c9ad07a1f8f71c2a2147f. 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.

@clawsweeper

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

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 9:08 PM ET / October 7, 2026, 01:08 UTC (Revision 5).

ClawSweeper review

What this changes

The 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
Reviewed head: 46a4314aa762de5af7150898bea191981756f5f4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, correct repair with strong scoped production evidence, a discriminating negative control, and successful exact-head CI.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The retained contributor-head Doctor run exercises the changed maintenance wrapper with real SQLite on copied existing state and confirms successful trigger repair; completed CLI runs supplement it. The reviewed cleanup only inlines the renewal guard in the same order, so that evidence remains applicable. Exact-head regression and CI are supplemental. Full Gateway recovery and a percentage speedup are not established or required for this scoped repair; no stored-data contract changes occur.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The retained contributor-head Doctor run exercises the changed maintenance wrapper with real SQLite on copied existing state and confirms successful trigger repair; completed CLI runs supplement it. The reviewed cleanup only inlines the renewal guard in the same order, so that evidence remains applicable. Exact-head regression and CI are supplemental. Full Gateway recovery and a percentage speedup are not established or required for this scoped repair; no stored-data contract changes occur.
Evidence reviewed 9 items Pinned introduced patch: The merge-base-to-head patch changes only maintenance lease validation and its regression. Transaction checks delegate directly to the existing owner; scope lifetime, shared failure latching, renewal admission order, and pending-work settlement remain intact.
Current main still needs the repair: The fetched main production file still invokes the no-argument check before transaction-aware validation. Its comparison with the pinned merge-base production file is empty.
Latest release retains the old path: The production file at v2026.9.8 also performs both ownership checks. Release metadata confirms publication on 2026-10-03; this PR's repair is not present in that release.
Findings None None.
Security None None.

How this fits together

Doctor 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -1, Tests +24. Total +23 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 12 13 -1
Tests 1 24 0 +24
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 36 13 +23

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #166330
Summary: This PR is the open implementation candidate for the reported redundant maintenance ownership reads.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This focused repair removes redundant SQLite work during maintenance without evidence of data loss or a broader runtime emergency.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The retained contributor-head Doctor run exercises the changed maintenance wrapper with real SQLite on copied existing state and confirms successful trigger repair; completed CLI runs supplement it. The reviewed cleanup only inlines the renewal guard in the same order, so that evidence remains applicable. Exact-head regression and CI are supplemental. Full Gateway recovery and a percentage speedup are not established or required for this scoped repair; no stored-data contract changes occur.
  • proof: sufficient: Contributor real behavior proof is sufficient. The retained contributor-head Doctor run exercises the changed maintenance wrapper with real SQLite on copied existing state and confirms successful trigger repair; completed CLI runs supplement it. The reviewed cleanup only inlines the renewal guard in the same order, so that evidence remains applicable. Exact-head regression and CI are supplemental. Full Gateway recovery and a percentage speedup are not established or required for this scoped repair; no stored-data contract changes occur.

Evidence

What I checked:

  • Pinned introduced patch: The merge-base-to-head patch changes only maintenance lease validation and its regression. Transaction checks delegate directly to the existing owner; scope lifetime, shared failure latching, renewal admission order, and pending-work settlement remain intact. (src/state/openclaw-agent-db-maintenance-lease.ts:42, 46a4314aa762)
  • Current main still needs the repair: The fetched main production file still invokes the no-argument check before transaction-aware validation. Its comparison with the pinned merge-base production file is empty. (src/state/openclaw-agent-db-maintenance-lease.ts:64, 7b66485dcd9b)
  • Latest release retains the old path: The production file at v2026.9.8 also performs both ownership checks. Release metadata confirms publication on 2026-10-03; this PR's repair is not present in that release. (src/state/openclaw-agent-db-maintenance-lease.ts:64, fc23bc864e45)
  • Existing ownership safeguards: The underlying owner checks active authority, reads exact durable ownership and expiry from the supplied transaction, checks heartbeat responsiveness, and repeats durable validation afterward. The repair changes neither eligible principals nor authority lifetime. (src/state/openclaw-state-lease.ts:369, 46a4314aa762)
  • Production caller and real behavior proof: The captured PR body records the production Doctor contribution at contributor head 91861fd using WAL-aware copies of existing state and a controlled legacy trigger. Repair removed the trigger with one repair, zero warnings, and exit zero; subsequent CLI repair and diagnostic runs completed. This proves scoped maintenance, not complete Gateway recovery or a matched performance benchmark. (src/commands/doctor-agent-memory-schema.ts:191, 91861fd6289c)
  • Retained proof remains applicable: GitHub's exact-head commit patch and the independently read original production blob show that the later cleanup only inlines the single-use renewal guard, preserving its check order. The contributor's transaction-aware repair and regression are retained. (src/state/openclaw-agent-db-maintenance-lease.ts:69, 46a4314aa762)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-06T23:00:05.416Z sha 91861fd :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-06T23:39:50.055Z sha 91861fd :: needs maintainer review before merge. :: none
  • reviewed 2026-10-07T00:24:32.081Z sha 91861fd :: needs maintainer review before merge. :: none
  • reviewed 2026-10-07T01:01:55.199Z sha 46a4314 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 6, 2026
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.
@steipete
steipete merged commit ed49744 into openclaw:main Oct 7, 2026
120 checks passed
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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.

[Bug]: SQLite maintenance ownership checks stall the main thread with redundant snapshots

2 participants