Skip to content

fix(doctor): refresh SQLite planner stats after migration - #134062

Merged
VACInc merged 3 commits into
mainfrom
openclaw/openclaw-openclaw-pr-119901
Aug 31, 2026
Merged

VACInc merged 3 commits into
mainfrom
openclaw/openclaw-openclaw-pr-119901

Conversation

@roboclaw-bot

@roboclaw-bot roboclaw-bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119884
Related: #119720
Related: #119739
Supersedes #119901

What Problem This Solves

Fixes an issue where users who ran openclaw doctor --fix could finish an agent SQLite schema migration without persisted planner statistics. Large migrated stores could then choose poor query plans, including after the original migration had already completed.

Why This Change Was Made

The repair lives in the normal Doctor-owned agent database migration path. Before releasing each database, Doctor runs ANALYZE main under an explicit 1,000-row-per-index analysis limit. This repairs already-current databases as well as newly upgraded ones without adding runtime maintenance, configuration, or an OpenClaw schema change.

Explicit ANALYZE is required for the supported SQLite 3.44.x floor. In that lineage, PRAGMA optimize=0x10002 ignores the later all-table bit and skips tables that the short-lived Doctor connection has not queried. The older #119901 patch instead placed full ANALYZE in explicit offline compaction, which does not own the normal migration path and could perform unbounded work on large stores. #119739 remains a related, distinct post-compaction proposal, while #133925 covers runtime bulk cleanup.

User Impact

Running openclaw doctor --fix now restores planner statistics for affected agent databases. Existing and newly migrated stores can use their indexes with current approximate statistics. Work is bounded to roughly 1,000 visited rows per index and runs only inside Doctor's explicit repair window; there is no new setting or runtime hot-path maintenance.

Evidence

  • Pre-fix regression: both the v14-to-current migration and an already-current database failed with no such table: sqlite_stat1.
  • Minimum-runtime contract: official SQLite 3.44.6 source at check-in 863c171b76cd36e0 requires TF_StatsUsed for PRAGMA optimize and has no 0x10000 all-table behavior; SQLite documents that behavior as new in 3.46.0.
  • Executable minimum-runtime proof: a source-built SQLite 3.44.6 at that exact check-in honored analysis_limit=1000; bounded ANALYZE main populated two sqlite_stat1 rows for 100,000 indexed records.
  • Executable compatibility A/B: official SQLite 3.44.2 left sqlite_stat1 absent after PRAGMA analysis_limit=1000; PRAGMA optimize=0x10002;; the repaired ANALYZE main sequence populated indexed tables.
  • Regression coverage requires named statistics for idx_agent_transcript_event_sequence after v14 migration and for a populated session_suggestions index that the migration never queries.
  • Owner/sibling migration coverage: 26 tests passed across current, v0/v14/v15, additive-schema, target-resolution, and lifecycle-recovery paths.
  • Doctor orchestration coverage: 97 tests passed in src/commands/doctor-state-migrations.test.ts.
  • Final focused coverage after test-lifecycle cleanup: 15/15 tests passed.
  • node scripts/check-changed.mjs -- src/infra/state-migrations.media-persistence.ts src/infra/state-migrations.media-persistence.test.ts passed, including formatting, production/test types, lint, database-first, schema, and import-cycle guards.
  • Fresh isolated autoreview: scoped-clean, no accepted/actionable findings (0.98 confidence).
  • Production source: +8/-0. The helper has two owner-path call sites and avoids duplicate maintenance policy.
  • Tests: +65/-16, including migration/current-store regressions and conversion of the touched suite to automatic temp cleanup.

Worked on by


View the OpenClaw team session

roboclaw-bot and others added 2 commits August 31, 2026 10:57
Run bounded optimizer maintenance before Doctor releases each migrated agent database so existing and newly upgraded stores persist planner statistics.

Co-authored-by: VACInc <[email protected]>
Worked on by:
- @VACInc

Co-authored-by: VACInc <[email protected]>
OpenClaw-Publication: bfa72b59-2b29-4a60-92e7-a03ae51acd55
@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added size: XS maintainer Maintainer-authored PR labels Aug 31, 2026
@roboclaw-bot
roboclaw-bot marked this pull request as ready for review August 31, 2026 10:58
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 31, 2026, 8:01 AM ET / 12:01 UTC.

ClawSweeper review

What this changes

The PR makes openclaw doctor --fix run bounded SQLite analysis for agent databases after media-persistence migration checks, with regression coverage for both upgraded and already-current stores.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep this maintainer-labeled PR open: current main lacks the planner-statistics refresh, while the introduced helper covers both no-op and rewritten Doctor migration paths without a concrete correctness or security defect found.

Priority: P1
Reviewed head: b9d68ddfa1d8acecac67d96e76a18aac861495e6

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is a focused owner-boundary repair with direct regression assertions and no supported blocking finding.
Proof confidence 🌊 off-meta tidepool Not applicable: Repository State identifies this as a MEMBER-authored PR, so the external-contributor real-behavior-proof gate does not apply; the submitted regression and compatibility evidence remains supplemental review context.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State identifies this as a MEMBER-authored PR, so the external-contributor real-behavior-proof gate does not apply; the submitted regression and compatibility evidence remains supplemental review context.
Evidence reviewed 6 items Current main still lacks this repair: The fetched current-main migration path returns immediately after a no-op detection and returns after schema validation without refreshing SQLite planner statistics.
Introduced owner-boundary coverage: The PR adds one local helper and invokes it after no-op detection and after the rewrite/schema path, so all successful paths through this migration owner receive the same maintenance step.
Doctor entry point and concurrency boundary: Doctor-only migrations call this owner, and the enclosing lease closes cached agent handles and fences cross-process writers before the callback runs.
Findings None None.
Security None None.

How this fits together

Doctor is OpenClaw’s explicit repair command. Its agent-database migration flow opens each registered store under a maintenance lease, normalizes legacy media data and schema, then returns the database to normal Gateway consumers.

flowchart LR
  A[Operator runs Doctor fix] --> B[Doctor migration orchestration]
  B --> C[Agent database maintenance lease]
  C --> D[Media and schema migration]
  D --> E[Bounded SQLite analysis]
  E --> F[Agent database returned to Gateway]
Loading

Before merge

  • Resolve merge risk (P1) - The claimed pre-3.46 SQLite behavior is supported by the submitted 3.44.x A/B evidence, but independent upstream SQLite-source inspection could not be completed because this checkout’s promisor remote cannot resolve GitHub.
  • Resolve merge risk (P2) - This bug-fix PR adds eight production lines; the inspected path has no existing helper that owns the required bounded analysis sequence, so the localized helper is the clearest current implementation.
Agent review details

Security

None.

PR surface

Source +8, Tests +49. Total +57 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 8 0 +8
Tests 1 65 16 +49
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 73 16 +57

Review metrics

Metric Value Why it matters
Production versus test delta production +8; tests net +49 The production addition is one two-call-site owner helper; test growth adds direct coverage for upgraded and already-current databases while replacing manual temporary-directory cleanup.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #119884
Summary: This PR is a candidate fix for the linked missing-statistics-after-Doctor-migration behavior; adjacent proposals address compaction, runtime cleanup, or broader write architecture.

Members:

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

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Land the bounded analysis at this Doctor-owned migration boundary once exact-head CI and maintainer review accept the supplied pre-3.46 SQLite compatibility evidence.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Land the bounded analysis at this Doctor-owned migration boundary once exact-head CI and maintainer review accept the supplied pre-3.46 SQLite compatibility evidence.

Do we have a high-confidence way to reproduce the issue?

Unclear for an independently executed current-main run: source shows no explicit statistics refresh, and the introduced tests define a focused reproduction, but this read-only review did not execute it.

Is this the best way to solve the issue?

Yes. The change belongs in the Doctor migration owner under its existing stopped-writer lease and covers both successful migration outcomes rather than adding runtime maintenance or a parallel compaction path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 43e9a3d81776.

Labels

Label justifications:

  • P1: Missing planner statistics after a Doctor migration can leave large agent stores with severely degraded session operations and Gateway responsiveness.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Repository State identifies this as a MEMBER-authored PR, so the external-contributor real-behavior-proof gate does not apply; the submitted regression and compatibility evidence remains supplemental review context.

Evidence

What I checked:

  • Current main still lacks this repair: The fetched current-main migration path returns immediately after a no-op detection and returns after schema validation without refreshing SQLite planner statistics. (src/infra/state-migrations.media-persistence.ts:425, 43e9a3d81776)
  • Introduced owner-boundary coverage: The PR adds one local helper and invokes it after no-op detection and after the rewrite/schema path, so all successful paths through this migration owner receive the same maintenance step. (src/infra/state-migrations.media-persistence.ts:359, b9d68ddfa1d8)
  • Doctor entry point and concurrency boundary: Doctor-only migrations call this owner, and the enclosing lease closes cached agent handles and fences cross-process writers before the callback runs. (src/infra/state-migrations.doctor.ts:1200, b9d68ddfa1d8)
  • Regression assertions cover both relevant paths: The upgraded-v14 case now requires a named transcript-index statistic, and the already-current case inserts into an otherwise unqueried table and requires its named statistic after Doctor finishes. (src/infra/state-migrations.media-persistence.test.ts:439, b9d68ddfa1d8)
  • Runtime floor and direct dependency boundary: OpenClaw opens SQLite through node:sqlite and rejects unsupported SQLite versions; current docs explicitly retain the 3.44.6 floor cited by the PR. (src/infra/node-sqlite.ts:47, b9d68ddfa1d8)
  • Prior review response: The prior review’s only rank-up concern was pre-3.46 SQLite behavior; the exact-head contributor update documents a 3.44.2 A/B and changes the implementation from optimizer-mask reliance to explicit bounded ANALYZE. (b9d68ddfa1d8)

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete exact-head CI and have a maintainer review the supplied SQLite 3.44.x compatibility evidence.

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 (1 earlier review cycle)
  • reviewed 2026-08-31T11:07:23.592Z sha d03c888 :: needs maintainer review before merge. :: none

Use bounded explicit analysis so Doctor refreshes every indexed table on supported pre-3.46 SQLite runtimes. Strengthen the regression around named planner statistics and adopt automatic temp cleanup.

Co-authored-by: VACInc <[email protected]>
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Exact head b9d68ddfa1d8acecac67d96e76a18aac861495e6 addresses the minimum-runtime contract gap from the prior review.

  • An official SQLite 3.44.2 amalgamation probe confirmed PRAGMA analysis_limit=1000; PRAGMA optimize=0x10002 leaves sqlite_stat1 absent, while the bounded ANALYZE main replacement populates indexes for both a queried table and an otherwise untouched table.
  • Doctor still owns the operation under its stopped-writer migration lease.
  • The regression now requires named statistics for both the migrated transcript index and a populated session_suggestions index that this migration never queries.
  • Local proof: focused migration 15/15, owner/sibling migration 26/26, Doctor orchestration 97/97, changed gate clean, isolated autoreview clean at 0.98 confidence.

Exact-head CI is running; no merge or automerge is requested.

@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

Exact head b9d68ddfa1d8acecac67d96e76a18aac861495e6 resolves the minimum-SQLite rank-up item. The repair now uses bounded ANALYZE main instead of the post-3.46 0x10000 optimize behavior, after direct SQLite 3.44.6 source inspection and an executable pre-3.46 A/B. Regression coverage now requires statistics for a populated index on a table the Doctor migration never queries.

@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

Exact-head verification for b9d68ddfa1d8acecac67d96e76a18aac861495e6 is complete.

  • CI: https://github.com/openclaw/openclaw/actions/runs/33388919555 — green, including build-artifacts, compact Node shards, type/lint/boundary checks, and openclaw/ci-gate.
  • Focused owner/sibling migration proof: 26 tests passed across current, v0/v14/v15, additive-schema, target-resolution, and lifecycle-recovery paths.
  • Doctor orchestration: 97 tests passed in src/commands/doctor-state-migrations.test.ts.
  • Final focused owner suite: 15/15 passed after automatic temp-directory cleanup conversion.
  • Changed gate: node scripts/check-changed.mjs -- src/infra/state-migrations.media-persistence.ts src/infra/state-migrations.media-persistence.test.ts passed with no warnings.
  • SQLite floor proof: official 3.44.6 check-in 863c171b76cd36e0, 100,000 indexed rows, analysis_limit=1000; ANALYZE main populated two sqlite_stat1 rows while the rejected optimize-mask variant populated none.
  • Fresh isolated autoreview: scoped-clean at 0.98 confidence.
  • ClawSweeper exact-head review: no actionable correctness or security findings: fix(doctor): refresh SQLite planner stats after migration #134062 (comment)

Known proof gap: configured Blacksmith Testbox could not provision because its host-owned login is unavailable. The dependency-floor proof instead compiled and executed the exact official SQLite source locally in an isolated disposable tree. No production-scale timing fixture was available; the regression proves the missing persisted statistics and both Doctor completion paths.

No merge or automerge was requested or enabled.

@VACInc
VACInc enabled auto-merge (squash) August 31, 2026 15:19
@VACInc
VACInc merged commit c884d51 into main Aug 31, 2026
272 of 274 checks passed
@VACInc
VACInc deleted the openclaw/openclaw-openclaw-pr-119901 branch August 31, 2026 15:22
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 1, 2026
…34062)

* fix(doctor): refresh SQLite planner stats after migration

Run bounded optimizer maintenance before Doctor releases each migrated agent database so existing and newly upgraded stores persist planner statistics.

Co-authored-by: VACInc <[email protected]>

* fix(doctor): refresh SQLite planner stats after migration

Worked on by:
- @VACInc

Co-authored-by: VACInc <[email protected]>
OpenClaw-Publication: bfa72b59-2b29-4a60-92e7-a03ae51acd55

* fix(doctor): cover supported SQLite planner stats

Use bounded explicit analysis so Doctor refreshes every indexed table on supported pre-3.46 SQLite runtimes. Strengthen the regression around named planner statistics and adopt automatic temp cleanup.

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: VACInc <[email protected]>

xiaoz012007 commented Nov 5, 2026 •

Copy link
Copy Markdown

Operator-reported maintenance follow-up (2026-11-05), related to #119884 and #133925.

On an Ubuntu deployment of OpenClaw 2026.10.9, the local investigation reported stale statistics for three transcript-related tables while integrity checks passed and the inspected query plans still used indexes. Attempts to acquire a SQLite write lock with 4 s and 45 s timeouts both failed before ANALYZE started.

After a maintenance intervention that included statistics refresh and exactly one Gateway restart, the operator's report recorded:

  • The same measured query: 580–657 ms before, 0.16–0.83 ms afterward.
  • Session-update writer-queue wait: a previous 40.6 s observation versus 0 ms in the reported post-maintenance samples.
  • Four new real transcript records and two successful conversational checks; no lock errors were observed in that short verification window.
  • Remaining first-update overhead of about 1.2 s and startup-maintenance overhead of about 6.3 s.

These are before/after observations for a combined intervention, not an isolated causal benchmark or proof that all SQLite delays are resolved. Long-running concurrent load has not been validated. Queue wait is not itself proof of a native SQLite lock wait.

The separate local synthetic-test report describes three repeated runs in which restarting alone did not repair persisted stale statistics, and an already-open connection needed to reload the refreshed statistics or be replaced. The local source audit reports that #133925 and #134062 are already present. We have not established that either repair failed, that its triggering maintenance path ran, or that a new upstream defect exists.

This comment is based on the operator-provided investigation summaries. The exact SQL, SQLite build details, synthetic fixture and complete local report are not attached or independently revalidated here, so this is a limited field note rather than a reproducible bug submission. No production database, conversation contents, credentials or private paths are included.

Potential documentation takeaway: when assessing planner-statistics maintenance, verify both persisted statistics and their use by long-lived connections, while measuring writer-queue wait separately from transaction execution and COMMIT. No reopening, new patch, or duplicate fix is requested.


AI contribution acknowledgment: The overall troubleshooting work—including fault investigation, diagnosis, remediation, validation, and preparation of this report—was carried out with technical assistance from GPT-6 Astra and Codex. The operator supplied the environment, authorized the interventions, and confirmed the user-facing recovery. Thanks to Astra and Codex for their technical support throughout this work. This comment was drafted and revised by GPT-6 Astra; the exact model used in each separate Codex session has not been independently verified. This acknowledgment does not expand the verification claims or resolve the evidence gaps described above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. 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.

3 participants