Skip to content

perf(doctor): avoid duplicate agent integrity scans - #158366

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-unlabeled-startup-hold-20260919
Sep 25, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-unlabeled-startup-hold-20260919

Conversation

@steipete

@steipete steipete commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Media migration scans every healthy agent database twice for physical integrity, holding an immediate write transaction for the first pass. A reported 26 GB store spent 123,621 ms in that unlabeled transaction before media detection.

Related: #151025, which moved legacy repair out of ordinary Gateway startup. This remaining cost affects the shared Doctor owner, including container activation.

User Impact

Doctor and image activation avoid a redundant full-database scan on healthy stores. Slow startup/maintenance transactions now identify their operation. No configuration, schema, retention, or recovery contract changes are required.

Why This Change Was Made

The hold is attributable to repairSqliteIndexCorruption: migrateLegacyMediaPersistence called it unconditionally, and it exhausts PRAGMA integrity_check(2147483647) inside an immediate transaction. Schema admission immediately afterward already performs full integrity and foreign-key validation.

Run schema admission first and enter the existing backup-and-repair path only for a proven integrity failure, then retry admission. This removes the duplicate work without introducing an integrity cache or trusting a schema version as proof of physical health. Quarantine cleanup, original-row preservation, maintenance authority, and legacy migration behavior remain covered. Labels cover the identified outer schema, repair, quarantine, migration cursor, startup lease, and Gateway ownership transactions. Net production growth: 100 lines.

Evidence

Blacksmith Testbox (blacksmith-testbox, profile openclaw-check), synthetic canonical store with 50,000 sessions / 500,000 transcript rows, 1 KiB message content, 743,149,568 bytes. Same lease and fixture recipe, one measurement per revision:

Measurement Before After
Media migration elapsed 4,665 ms 3,634 ms
Longest immediate transaction hold 515.9 ms 7.7 ms
Full integrity scans 2 1
Process peak RSS, including fixture creation 840,764 KiB 687,440 KiB

Total migration improved 22%. The discarded integrity pass alone took 515 ms. These are synthetic measurements, not a production restart or a claim that all startup delay is removed. The existing required admission check and media-content scan remain.

  • Benchmark lease: tbx_01m3d55j1af2kjp5y0f95svg9j. node --import tsx .lane211-bench.ts exercised the real migration API and traced native integrity statements/transaction durations. Scratch fixture and script are task-owned and cleaned up. The new one-scan regression failed on the original code (2 checks) and passed after the fix.
  • Validation lease: tbx_01m3d5xdq88r7dwz3yf1wcajhs. node scripts/run-vitest.mjs src/infra/state-migrations.media-persistence.lifecycle-recovery.test.ts src/infra/sqlite-index-corruption.test.ts src/infra/state-migrations.media-persistence.historical.test.ts src/infra/state-migrations.media-persistence.historical-v14.test.ts src/infra/state-migrations.owner-mismatch.test.ts src/state/openclaw-agent-db-maintenance.test.ts --maxWorkers=1: 36 tests passed, 44.26 s Vitest / 65.47 s wrapper wall. Covers real index corruption with and without quarantine, repair backup/rollback/authority, labeled slow holds using a fake clock, historical schemas, and owner mismatch.
  • On the validation lease, node scripts/check-changed.mjs --base 8133be64d156a7a7f625ab69469b642930e29aec passed: core types, all 25 core test type graphs, lint, formatting, docs, unused exports, and repository guards. The first default-base invocation compared this older worktree with newer main and failed on unrelated upstream line-cap changes; pinning the actual pre-change base scoped the gate correctly.
  • Individual pnpm test <file> --maxWorkers=1 runs passed on the validation lease: lifecycle recovery, 4 tests / approximately 3.16 s test execution / 11.59 s wrapper wall; index corruption, 7 tests / approximately 0.34 s test execution / 7.48 s wrapper wall. CI run elapsed: 1,096 s including orchestration and queue time (not a per-file benchmark).
  • CI run 36193111221 passed on c4be11cc9a1d: 129 successful jobs, zero failures, including openclaw/ci-gate. All reported PR checks passed or were skipped.
  • Independent Codex autoreview: no actionable P0–P2 findings. git diff --check passes; local and Testbox Git blob hashes match for all 12 changed files.

Infrastructure notes: both leases required the prescribed frozen-lockfile dependency installation. Two later sync attempts timed out before executing tests; replacing that lease restored normal sync. Both leases are stopped at closeout. No production database was changed or restarted. A 26 GB replay and a published-updater end-to-end run were not performed.

Let schema admission detect physical corruption before invoking the preserving index repair. Healthy stores no longer take an immediate writer transaction to repeat the same full-file scan. Label startup and maintenance transaction owners so remaining slow holds are attributable.
@clawsweeper

clawsweeper Bot commented Sep 25, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L labels Sep 25, 2026
@steipete
steipete marked this pull request as ready for review September 25, 2026 21:43
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. labels Sep 25, 2026
@clawsweeper

clawsweeper Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 25, 2026, 5:53 PM ET / 21:53 UTC.

ClawSweeper review

What this changes

The branch makes Doctor attempt schema admission before conditional SQLite index repair, labels slow database transactions, and updates focused tests and documentation.

Merge readiness

⛔ Blocked before merge - 3 items remain

Current main still performs the redundant scan, and the reported SQLite benchmark supports a useful improvement. Source review found no discrete introduced correctness defect. A published-updater upgrade check remains outstanding.

Priority: P2
Reviewed head: c4be11cc9a1d6be984cb93bf20cf3690db7464a1

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused source changes, regression coverage, and a direct SQLite benchmark provide good signal, with upgrade-path proof still outstanding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR reports a Blacksmith Testbox run of the changed production migration API against a real synthetic SQLite store, observing one instead of two native integrity scans and a shorter immediate write hold after the change. A published-updater upgrade cell remains a separate required gate; no stored-data format change was identified.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR reports a Blacksmith Testbox run of the changed production migration API against a real synthetic SQLite store, observing one instead of two native integrity scans and a shorter immediate write hold after the change. A published-updater upgrade cell remains a separate required gate; no stored-data format change was identified.
Evidence reviewed 8 items Current-main behavior: Current main unconditionally invokes the preserving index repair before schema admission; that repair performs a full integrity scan.
Introduced behavior: The introduced branch invokes the preserving repair only after schema preparation reports a terminal integrity failure, then retries preparation.
Doctor entry point: Doctor's state-migration preflight calls the changed media migration owner.
Findings None None.
Security None None.

How this fits together

Doctor checks and migrates each agent's SQLite database during maintenance and image activation. It reports repairs and migration results before the Gateway uses that state.

flowchart LR
A[Doctor or image activation] --> B[Agent SQLite store]
B --> C[Schema admission and integrity]
C --> D{Integrity failure?}
D -- Yes --> E[Backup and index repair]
D -- No --> F[Media migration and report]
E --> F
Loading

Before merge

  • Resolve merge risk (P1) - A published-updater × candidate run on existing agent state is absent, leaving the reordered Doctor admission and repair path unverified during an actual update.
  • Complete next step (P2) - Record a published-updater × candidate run on existing agent state, including Doctor completion and Gateway activation, before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +100, Tests +59, Docs +7. Total +166 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 9 265 165 +100
Tests 2 118 59 +59
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 390 224 +166

Review metrics

Metric Value Why it matters
Production and test growth production +100 lines, tests +59 lines The PR body attributes the production growth mainly to diagnostic labels and the admission reorder.
Reported SQLite benchmark full scans 2 → 1; longest immediate hold 515.9 → 7.7 ms The measured synthetic run targets the redundant scan and write hold this PR aims to remove.

Stored data model

Persistent data-model change detected: database schema: src/infra/state-migrations.media-persistence.ts, migration/backfill/repair: src/infra/sqlite-index-schema.ts, migration/backfill/repair: src/state/openclaw-state-db-repair.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Prove the update path (recommended)
    Run a published updater against existing agent state with this candidate and record Doctor completion and Gateway activation.

Technical review

Best possible solution:

Healthy stores receive one integrity scan while Doctor retains its backed-up index repair and quarantine recovery behavior across upgrades.

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

Yes. Current main unconditionally runs index-repair integrity scanning before schema admission, and the PR reports a before-and-after run of that migration API; I did not execute the checkout.

Is this the best way to solve the issue?

Yes, provisionally. Reusing schema admission and retaining the existing repair owner is a narrow approach; the upgrade path still needs its required proof.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 800bf8e10e7c.

Labels

Label changes:

  • add P2: This is a bounded Doctor performance improvement with meaningful impact on large agent stores.
  • add merge-risk: 🚨 compatibility: Doctor's admission and repair order changes for existing databases, and the repository-required published-updater check has not been shown.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR reports a Blacksmith Testbox run of the changed production migration API against a real synthetic SQLite store, observing one instead of two native integrity scans and a shorter immediate write hold after the change. A published-updater upgrade cell remains a separate required gate; no stored-data format change was identified.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR reports a Blacksmith Testbox run of the changed production migration API against a real synthetic SQLite store, observing one instead of two native integrity scans and a shorter immediate write hold after the change. A published-updater upgrade cell remains a separate required gate; no stored-data format change was identified.

Label justifications:

  • P2: This is a bounded Doctor performance improvement with meaningful impact on large agent stores.
  • merge-risk: 🚨 compatibility: Doctor's admission and repair order changes for existing databases, and the repository-required published-updater check has not been shown.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 PR reports a Blacksmith Testbox run of the changed production migration API against a real synthetic SQLite store, observing one instead of two native integrity scans and a shorter immediate write hold after the change. A published-updater upgrade cell remains a separate required gate; no stored-data format change was identified.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports a Blacksmith Testbox run of the changed production migration API against a real synthetic SQLite store, observing one instead of two native integrity scans and a shorter immediate write hold after the change. A published-updater upgrade cell remains a separate required gate; no stored-data format change was identified.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: 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.

  • Record the repository-required published-updater × candidate run against existing agent state.

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.

@steipete
steipete merged commit 48f8869 into main Sep 25, 2026
283 checks passed
@steipete
steipete deleted the steipete/perf-micro-unlabeled-startup-hold-20260919 branch September 25, 2026 22:15
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 26, 2026
Let schema admission detect physical corruption before invoking the preserving index repair. Healthy stores no longer take an immediate writer transaction to repeat the same full-file scan. Label startup and maintenance transaction owners so remaining slow holds are attributable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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: L 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.

1 participant