Repository navigation
fix: stop Doctor from rewriting healthy agent databases while the Gateway is stopped - #206707
Conversation
Plan the agent database migration read-only and leave a database whose every condition is none unopened for writing, unleased and sealed.
…ent database plan
|
🦞👀 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: blocked before merge. What this changesThis PR plans agent database maintenance read-only and skips writable maintenance when every applicable condition reports no work. Example: Run openclaw doctor --fix again on a healthy Linux installation with four agent databases.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 2 items remain Keep this maintainer-authored PR open: it addresses unnecessary Doctor maintenance still present on main, but its new healthy-database test fails on supported platform paths. Reviewed head: Before merge
Findings
Tests
Agent review detailsHow this fits togetherDoctor's migration graph supplies discovered agent stores to media maintenance and cold-navigation repair; the new plan determines which stores can bypass those writes while remaining available to later repair steps. flowchart TD
A[Doctor migration graph] --> B[Discover agent stores]
B --> C[Read-only maintenance plan]
C --> D[Healthy stores skip writes]
C --> E[Existing maintenance and repair]
D --> F[Later Doctor steps]
E --> F
Technical reviewBest possible solution: Keep the plan within the existing migration owners, preserve fallback repair and fresh integrity checks, and correct the platform-dependent test expectations. Do we have a high-confidence way to reproduce the issue? Current-main source shows healthy stores entering writable maintenance, and supplied CLI logs demonstrate that behavior on the baseline; this read-only review ran no reproduction. Is this the best way to solve the issue? Planning at the migration owner is a coherent way to eliminate unnecessary writes while retaining repair behavior; the reviewed production paths reveal no definite new data-loss defect. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 89425fd75d4e. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +905, Tests +710. Total +1615 across 16 files. Added test files: 1. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 27, 2026, 8:59 AM ET / 13:59 UTC. |
…he state directory
|
Merged via squash.
|
…eway is stopped (openclaw#206707) * fix(doctor): skip agent database maintenance that has nothing to do Plan the agent database migration read-only and leave a database whose every condition is none unopened for writing, unleased and sealed. * test(doctor): cover deleted and incognito agent databases in the plan * fix(doctor): count changed archive rows and interior fanout in the agent database plan * fix(doctor): accept an empty table within optimize's lower bound * fix(doctor): keep SQLite's last loaded table estimate in the planner check * fix(doctor): skip empty tables with an unanalyzed index in the planner check * test(doctor): honor supported SQLite versions and Windows in the plan tests * test(doctor): compact the agent database plan guards and satisfy the CI ratchets * test(doctor): walk fixture files without recursive readdir and type the state directory * fix(doctor): plan nothing through copied store reads and count stat1 creation * chore: drop the test-lines allocation the change no longer needs * chore: record the plan's regression-test allocation
|
Follow-up from main's hourly CI.
Each one fails with |
Related: #204775
What Problem This Solves
openclaw doctor --fixstops the Gateway and then migrates and maintains every agent database, even when there is nothing to do. On a healthy install it opens each agent database read-write twice, takes seven maintenance leases, deletes each database's clean-close seal, runs three write transactions per database and rewrites theagent_databasesregistry rows. All of that happens while the Gateway is stopped. Deleting the seal also means the restarted Gateway can no longer reuse the last integrity proof.User Impact
On a healthy install, Doctor now reads each agent database once, read-only, and finds nothing to do. It does not open the database for writing, takes no maintenance lease, leaves the seal in place and begins no write transaction. When any check finds work, or cannot decide, that database goes through the same migration as before. The integrity check still runs on every Doctor run, but read-only. No configuration, schema, stored field or retention changes.
Why This Change Was Made
A read-only plan at the agent database migration owner (
src/infra/state-migrations.agent-database-plan.ts) checks every condition the media pass and the cold-navigation pass act on. It answers work, none or undecidable for each database. The condition list came from going through the code write by write (table below). Each check reuses or extracts the writing code's own predicate, so the two cannot drift apart:findCanonicalSqliteIndexDrift, now shared byrepairCanonicalSqliteIndexesverifyOnlynow returnspendinghasCurrentAgentSchemaMetadata, next topersistAgentSchemaMetadataagentDatabasePermissionsNeedRepairhasPendingSessionKeyContractSchemahasPendingSessionEntryValidity,hasPendingSessionAdditiveSchemamisplacedOwnerIdtranscriptArchiveNeedsMigrationmigrateLegacyMediaPersistenceskips a database only when all of its media-pass conditions are none. It skips the whole pass, discovery lease included, only when the discovery conditions are also none. A skipped database is still handed to the later steps as admitted and repair-ready, exactly as the full no-op pass reported it.migrateSessionColdNavigationdrops admitted targets whose read-only query finds no cold archive to backfill, and takes no lease when none remain. The legacy archive-file pass moved to its owner,media-persistence-archive-source.ts, to keep the media pass under its line cap.The integrity transaction. #158366 and #175402 make a fresh check of the current bytes part of every Doctor run, so the check stays. It never needed a write transaction, a lease or seal invalidation. The check itself already runs in a read-only child process (
runSqliteIntegrityOperationInWorker). TheBEGIN IMMEDIATEaround it covers only the index repair that a failed check would trigger. The plan runs the same check, with the samefullorquickcoverage as the writing pass, on a read-only connection. A failure sends the database through the unchanged repair path. Expensive reads (archive verification, archive files, integrity) run only after every cheap condition is none, so a database that has work is not checked twice.last_seen_at. Its consumers are the path-repair ordering among aliases of one database, the migration witness (which only checks that it is non-negative) and QA startup state, which strips it. None of them needs Doctor to refresh it: the Gateway re-registers every database when it boots, and Doctor restarts the Gateway. So a registry row with the right path and schema version is none, and only a missing or different row is work.size_bytesfollows the same reasoning.Planner statistics. SQLite cannot answer "would optimize analyze?" on a read-only connection. In debug mode,
PRAGMA optimizestill asks for a write transaction once two tables need its size check (seen on the agent schema).sqlitePlannerStatisticsNeedRefreshapplies SQLite's per-table rule to the committed catalog:dbstat.A test checks it against SQLite's own debug output, on a writable copy, at every step of a growth, delete and reanalysis lifecycle. Before SQLite 3.46 the writing pass runs plain
ANALYZE, so this condition is always work there.Live-store guard. Inside the stop, the plan opens databases with the owner's read-only reader, as the agent-memory schema repair already does. That is the point where the writing pass would otherwise open them read-write. Incognito, deleted or ownerless stores, and stores the reader reports as
database-missing, are undecidable. To feed theconfig-flowstep'spendingcheck later, wrapplanAgentDatabaseMigration(...).pendingindecideDoctorPendingFromLiveStores, using the state database path plus the discovered target paths. This PR does not wire it: the step's overall answer belongs to the state-schema work, and an export with no production consumer fails the dead-export gate.media-persistence-targets.tsdiscoverAgentDatabaseMigrationTargets)recoverMisplacedAgentDatabaseCopiesmoves a copy asidehasMisplacedAgentDatabaseCopiesmigrateAgentDatabaseversion migration;versionMigrationsassertOpenClawAgentDatabaseOwnerfailure becomes a warningensureAgentSchemasame-version branch (openclaw-agent-db-schema.ts400–409)session_reactionsensureSessionEntryValidityProjectionentry_valid = 0existspersistAgentSchemaMetadata(418)app_versionrepairCanonicalSqliteIndexes(411, and inside the integrity steps)findCanonicalSqliteIndexDriftassertOpenClawAgentCurrentRuntimeSchemaagentDatabaseIntegrityBeforeMutationSteps(593) plus index-corruption repairmedia-persistence.ts265–283)ensureOpenClawAgentDatabasePermissions(578, 628)agentDatabasePermissionsNeedRepairregisterOpenClawAgentDatabase(631)hasMediaRowsMigrationReceiptmigrateCanonicalTranscriptArchives(442): blob, file, journal and receipt writesverifyOnlypendingmigrateLegacyTranscriptArchiveFilestranscriptArchiveNeedsMigrationrefreshSqlitePlannerStatistics(453)sqlitePlannerStatisticsNeedRefreshmigrateSessionColdNavigationbackfillhasPendingSessionColdNavigationUpdate behavior
Doctor-only. No updater, launcher or migration-driver change. A shipped updater reaches this through the candidate's own
openclaw doctor --fix. UnderOPENCLAW_UPDATE_IN_PROGRESS, under an updater migration capture or during an artifact-preserving read, the plan reads nothing and answers undecidable, so the migration runs exactly as before.storeReadsNeedCopies, now shared withdecideDoctorPendingFromLiveStores, makes that check. The cold-navigation filter also does nothing there.Evidence
Cell measurements: head
651057f7521against base788ca3c2f2b. Since651057f7521, the production changes are:// SAFETY:comments;sqlite_stat1.The healthy-install path in the cell runs neither case, so the measured results still apply. The other later commits are tests, the test-lines allocation and merges of
main.Cell: Linux Docker, systemd user Gateway, npm install, a 4 GiB main agent database and three small agents, 1 MiB/s of writes while serving. One seeded store had already been through two
doctor --fixruns and was restored byte-identical before every run.Red, base (two runs): for each of the four databases inside
cli.bootstrap.legacy-state-migrations:BEGIN IMMEDIATE, one live.sealdeleted (two more unlink attempts on the already-deleted seal), one statement write;state_leasesinserts: 7 in all;agent_databaseswrites: 4.The migration step took 5.4 s and 6.1 s, of which the agent media pass was 4.2 s.
Green, head (two runs): read-only opens only. 0 read-write opens, 0
BEGIN IMMEDIATE, 0 seal changes, 0 lease inserts, 0 registry writes.doctor.agent-database-plan pending=none databases=4 unchanged=4. The migration step took 2.9 s and 2.7 s, of which the plan was 2.1 s and 1.9 s. That time is mostly the read-only full integrity check.Red recording (base
788ca3c2f2b):doctor-agent-db-plan-red.mp4
Green recording (head
651057f7521):doctor-agent-db-plan-green.mp4
Raw red log (base 788ca3c)
Raw green log (head 651057f)
Outage A/B, using the same cell and store restored byte-identical before every run. Runs are offline and the builds alternate (B,H / H,B / B,H). Each hold discards one warm-up per build, leaving 6 measured runs per build. The probe hits
/healthzevery 250 ms. Medians with ranges:788ca3c2f2b651057f7521doctor.config-flowcli.bootstrap.legacy-state-migrationsPaired differences (head minus base): −1.8, +2.7, −1.6, −0.8, −1.3, −4.3 s. The one positive pair ran while host load peaked at 9.9; the other runs were between 1.4 and 6.8. No other section moved by 0.10 s or more. Keeping the seal did not measurably shorten the restart. The remaining time for this owner, 1.9 to 2.1 s, is the read-only full integrity check of the 4 GiB store, which runs on every Doctor run by design (#175402).
Unit, red then green: one healthy-rerun test runs only the existing entry points. On base it fails ("expected 4 to be +0": four maintenance leases on a no-op rerun); on head it passes. The tests written for the review findings each fail with their fix reverted and pass with it:
Commands on the final head:
node scripts/run-vitest.mjson 22 affected files (headf092ccb8ba0), including the generic guardsdoctor-health-contributions.pending-read-only.test.tsanddoctor-maintenance.stopped-systemd.test.ts: all pass.node scripts/check-changed.mjs: passes (exit 0) onf092ccb8ba0.release-update-survivorDocker lane, run locally throughpnpm test:docker:allon PR head0c4ae3e2b30, a build of0c4ae3e2b30against its merge base: all three release cases pass (healthy, crash, and the schema downgrade thatschema-downgrade-source.mjsselects because this PR changessrc/state/*schema*and*migrations*files), in 2038 s. On CI the same lane timed out twice at its 3300 s budget: the last output came seconds before the kill, while the runner was still fetching packages, not stalled in Doctor. A daemon-only PR (improve: avoid Windows task imports during Linux service discovery #206777), which does not select the downgrade case, passed in 1358 s.Autoreview: Codex route,
--max-priority P2 --thinking high, with 17 owner and caller files as source context. Seven passes found ten P2 findings, all fixed with regression tests. The last two, from after a merge ofmain, were: planning under migration capture, andsqlite_stat1creation. Each regression test fails with its fix reverted. The eighth pass, on headf092ccb8ba0with 19 source-context files, was scoped-clean ("patch is correct"), and its report lists the inspected files.Test files audited in full:
state-migrations.agent-database-plan.test.ts(new);sqlite-planner-statistics.test.ts(existing cases kept; oracle and 3.44 cases added);state-migrations.cold-navigation.test.ts(one case added);state-migrations.media-persistence.canonical-archives.test.ts(four verify cases added).Nothing in the existing tests was removed. While compacting, two of the new cases were folded away:
Test-lines allocation:
config/test-lines-allocations/206707-doctor-agent-db-plan.txtrecords 109 lines above the 400-line allowance. They cover one real-database guard per maintenance condition (the coverage this change exists to keep honest), the SQLite optimize oracle, and the archive, cold-navigation and copied-read consumer cases.Platform gates: on Windows, permissions are rewritten on every pass, and before SQLite 3.46 planner statistics are refreshed on every pass, so the no-op cases expect work there.
Not proven: PostgreSQL agent stores (undecidable by design), macOS launchd, pnpm installs, databases large enough that the read-only integrity check outweighs the saved transactions, and the
config-flowstep's overall answer (not wired).On the steady-state store, no other owner in the migration window opened an agent database read-write (only read-only opens). On a store that had never been through
doctor --fix, the transcript-directives cursor and the workspace-setup auth-profile cleanup also wrote agent databases once. Those are other owners and outside this PR.