Repository navigation
fix: recover agent databases after orphan session window repair - #167366
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. What this changesThis PR adds backed-up Doctor cleanup of orphan session windows and rechecks cached database integrity failures after repair. Example: The operator runs Doctor on a database containing orphan-window referencing missing-node.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Partial Merge readiness✅ Ready for maintainer review Keep open: this is useful, maintainer-approved recovery work that current main does not provide. No actionable patch findings remain; the orphan-producing operation remains a separate investigation. Priority: P1 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherEach agent stores session identities and transcript windows in SQLite. Database admission checks that state before agent work runs, while Doctor owns offline repair and migration. flowchart TD
A[Agent session database] --> B[Database admission]
B --> C{Integrity refusal cached?}
C -->|Yes| D[Native integrity verifier]
D --> B
C -->|Healthy| E[Agent work proceeds]
A --> F[Offline Doctor maintenance]
F --> G[Preserve original backup]
G --> H[Remove orphan windows and retry migration backup]
Technical reviewBest possible solution: Keep recovery in the existing Doctor and admission owners, while the linked issue separately identifies and repairs the orphan-producing writer. Do we have a high-confidence way to reproduce the issue? Yes for the recovery defects: seeded missing-node windows exercise the real integrity refusal, and recorded Gateway and production-only negative controls demonstrate blocked admission and migration backup. The operation creating real-world orphans remains unknown. Is this the best way to solve the issue? Yes for recovery: the patch reuses Doctor's backup, maintenance, transaction, and verification owners without adding a runtime data-deletion path. It deliberately leaves the producing defect to the linked investigation. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against e6ca676b02b6. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +260, Tests +343, Docs +30, Other +2. Total +635 across 22 files. Added test files: 1. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes: No label 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 HistoryReview history (13 earlier review cycles; latest 8 shown)
Reviewed October 9, 2026, 2:41 AM ET / 06:41 UTC (Revision 14). |
|
Maintainer design acceptance (storage review checkpoint, Accepted scope: Doctor ( The producer of these orphans is still unidentified. Current main cascades window deletion, and the lifecycle paths exercised on a real Gateway left no orphans. So this PR stays Before landing, this PR will be reduced in size, rebased onto main's new admission write guard by merge, and re-proven. |
Keep Doctor's backed-up missing-node window repair and native rechecks only while integrity failures are latched. Reuse existing snapshot, transaction, worker, and rollback owners; remove the extra verifier client and generation clearing machinery. Preserve main's write-admission guard before recovery. Related: #167287. The orphan-producing operation remains unidentified.
Tell operators to stop the Gateway before Doctor repair and restart afterward. Recommend restoring a verified backup only when Doctor still cannot repair the offline database. Align the orphan-window docs and emitted-error expectations. Related: #167287.
|
Maintainer approval (snapshot/baseline exception, root AGENTS.md), 2026-10-08: for the 2026.9.9 -> head upgrade-compatibility proof with a seeded orphan, the strict protected-table snapshot oracle may allow only individually source-verified Doctor-owned metadata changes:
Every session, transcript, stored plugin setting and quarantine row, and the original repair backup, must remain byte/count-exact. No other differences are allowed. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
…claw#167366) * fix: recover agent databases after orphan session window repair * fix: clarify offline SQLite repair guidance Tell operators to stop the Gateway before Doctor repair and restart afterward. Recommend restoring a verified backup only when Doctor still cannot repair the offline database. Align the orphan-window docs and emitted-error expectations. Related: openclaw#167287. * fix(ci): qualify Doctor foreign-key maintenance pragmas
Related: #167287
What Problem This Solves
Fixes: fresh agent work can retain a cached integrity refusal after database repair, and an orphan session window can prevent Doctor from reaching its repair during a release upgrade.
User Impact
Operators can stop the Gateway, run
openclaw doctor --fix, and restart. Doctor preserves the original database before removing windows whose session node is missing. Fresh admission rechecks a latched integrity failure so repaired state can become usable again. Only if Doctor still cannot repair the offline database does the guidance advise preserving the database/WAL and restoring a verified backup.Doctor retains exclusive maintenance ownership. The orphan-producing operation and repeated-failure notifications remain outside this recovery fix; the linked issue stays open.
Why This Change Was Made
The recorded maintainer design puts backed-up orphan cleanup in Doctor. When the pre-migration integrity gate finds damage, Doctor first invokes that narrow repair, then retries the unchanged complete migration backup. Existing-schema maintenance ownership preserves shared schema 19 until the rollback group is captured. Other FK violations remain refused, including another broken FK on the orphan or its children. Original violations are classified before deletion; complete integrity and current maintenance authority are checked before commit.
Main
15305ccd53dedd1663a89f92a402480d7b71bbf8was merged without rebasing, including #167476 (fs-safe 0.25.0) and #167482 (state-derived volume Doctor budget). Main's read-only write guard remains before latched revalidation; healthy admission does not run the recovery scan. Worker/process verification, WAL-aware preservation, rollback, cascades and FTS cleanup retain their existing owners. No new schema/FK, config option, public protocol or runtime compatibility reader.Coordinator dispositions: the +260 production LOC exception is accepted, as is the in-place Doctor proof limitation: Doctor correctly refuses while a running Gateway owns the database; same-PID recovery after external repair plus offline Doctor repair with backup and post-restart success is the accepted proof. Peter separately approved the narrowly bounded metadata snapshot exception.
Exact delta against merged main: production +335/−75 = +260, tests/support +385/−42 = +343, docs +30/−0, tooling +2/−0. Growth provides backed-up orphan repair, pre-migration ordering, unrelated-damage refusal, and latch recovery; no unrelated deletion or code compression funds it. The two tooling lines qualify this Doctor helper's FK PRAGMAs under the existing maintenance rule; ordinary row operations still use Kysely.
Evidence
Final pushed head:
7ca3721b3d9cdcbd45254876a00f8810d7e5d931, tree80af0addcb5c99d99580ca6e0f462b0907c51b2d. Full merged-source autoreview and the final tooling-only autoreview are both scoped-clean through P2; deslop completed. Runtime proof is pinned to its parent6fccdf3bd84ea8f03ba3406237e79c50374944d4, treeaac6098fca19f3be05f9835ca37b3efd758aac85: the only subsequent diff is the two-line guard qualification. All production, tests, docs, package inputs and dependencies are identical.Local six-file proof passed 64 tests, 758.18 seconds including cold preparation. Core types passed in 19.441 seconds, covering test graphs in 210.648 seconds, targeted lint in 51.987 seconds, and format/diff checks passed. Final tooling guard, lint and format passed locally and the architecture guard passed in exact-head CI.
node scripts/run-vitest.mjs \ src/commands/doctor-migration-backup.test.ts \ src/commands/doctor-rehearsal-capture.test.ts \ src/commands/doctor-rehearsal-databases.test.ts \ src/flows/doctor-health.update-schema.test.ts \ src/infra/state-migrations.media-persistence.historical.test.ts \ src/state/openclaw-agent-db.integrity-recovery.test.ts --maxWorkers=1 pnpm tsgo:core pnpm tsgo:core:test --changed-paths-json "$(cat /tmp/orphanland-approved-native/required-proof/module-files.json)"The fresh production-only negative control kept final tests and reverted only production to merged main
15305ccd53dedd1663a89f92a402480d7b71bbf8: 3 intended failures / 1 pass / 11 skipped, 146.36 seconds Vitest / 486.305 seconds total. Orphan upgrade fails at the original migration backup gate; unrelated-FK refusal remains intact. Production and test hashes were verified after restoration.Fresh AWS module coverage accounts for all 78 explicit files: 955 tests passed / 14 skipped / 7 inherited failures, 74 passing files / 1 skipped / 3 failed. The first invocation completed 41 files; two explicit supplements ran the 37 previously unexecuted files (28 then 9), without rerunning completed tests. Command times: 215.869 + 745.547 + 105.331 seconds. Core types passed in 16.825 seconds and the covering test graphs in 134.655 seconds on the same lease. The seven failures are the separately reproduced hydration/conversation/sharing cases below; this module run is not claimed all-green.
Exact-head CI completed: 84 success, 23 skipped, 5 failed test jobs plus the aggregate gate. CI used merge
104a8336533bf89f38a9cb7e319b559e274d74f1of this head into newer main0ffd46b94dd3cd168ca9cda60d4c095dd4bfa275. All ten failed assertions reproduce without this PR:15305…reproduces them; quarantine/refusal behavior remains covered.15305…reproduces all five. Combined conversation/sharing replay: 6 failures / 15 passes, 256.019 seconds; hydration replay: 1 failure / 6 passes, 76.775 seconds.15305…(118.889 seconds), then reproduce the exact three CI failures on CI's main parent0ffd46…(3 failures / 67 passes, 95.842 seconds). Main's fix(storage): preserve committed facts when publication fails #167570 changed post-commit publication to preserve committed results while these assertions still expect throws. Relevant test and owner blobs match CI's merge; these failures are inherited from that newer main, not from the earlier branch base.The two previously documented failures were also rechecked on merged main
15305…: the catalog import-cycle guard fails in 107.351 seconds; the unchanged auth product test times out at 180 seconds (1 failure / 1 pass; 479.88 seconds Vitest, 2,054.712 seconds including cold build). Newer CI main fixes the import cycle; the final architecture job passes. The final CI run does not repeat that auth failure. No test timeout, assertion or baseline was changed to obtain green.The earlier real-Gateway recovery proof remains scoped to
d4ace35335a7bb0f80b9a92004be2dae8551e480: fresh Testboxtbx_01m4en070169jybpp22drdastp(run), isolated state/ephemeral port and a synthetic local OpenAI-compatible provider. A persisted cron job failed on the orphan before provider I/O. Doctor refused concurrent maintenance. External synthetic repair let the next job succeed with the same Gateway PID19272. After stopping the Gateway and reseeding, actual Doctor removed one orphan, preserved original history in its backup and the valid control row, and the next job succeeded after restart (PID21117). Flow: 313.923 seconds. The fresh upgrade proof below covers the subsequent migration-ordering change; the earlier run is not presented as exact-head live proof.ClawSweeper's review of
7ca3721…reports no actionable code findings and confirms the migration-ordering fix. Its remaining “Add data-model compatibility proof” request is addressed below; its prior blocked verdict predates this evidence update. No merge performed.Data-model compatibility
Data-model compatibility: PASS under approved metadata exception. Approval: comment 6073779390.
Fresh AWS lease
cbx_937345b59de7(crimson-crayfish-9fc5, c7a.8xlarge, eu-west-1; Node 24.19.0 / pnpm 12.5.1), no hydration,GITHUB_ACTIONS=false. Frozen candidate is6fccdf3…with fs-safe 0.25.0; candidate tarball SHA-2566854774aa6158a03e3386a03baabfd8838cf06df5d176ea71841f84ca4cd2b9b. Baseline is latest published stable[email protected], registry-integrity verified, buildbcfc88812a35243893585dbeca87ca41b48272ca. Both version strings say 2026.9.9, so installed file hashes/build identity establish which package ran.The older captures lacked compiled Doctor artifact bytes and original Linux file-stat witnesses needed by the exact validator; this authorized rerun recreated only the native seeded-orphan proof. Initial native run completed Doctor repair, migration, strict backups and SDK readback. The first metadata comparison then exposed a validator representation mismatch: the canonical reader strips part of
packageBuild, while the writer stores the complete object. The corrected external validator compares the complete raw stored index with the complete canonical rebuild in the writer's JSON representation before comparing reader projections. FullpackageBuildis also compared with frozen package JSON; no field is dropped or allowance expanded.Final validator run PASS, 12.722 seconds, against both after-Doctor and after-read captures. The validator lives outside the repository, so there is no in-repository validator to commit. It names each allowed table/field explicitly and checks:
config_health_entries: onlylast_known_good_jsonandupdated_at_ms; the fingerprint matches actual config bytes/stat identity and monotonic observation time. Security/identity fields remain exact.config_machine_state: only theconfig.lastTouchedAtandplugins.installedIndexrows'value_json/updated_at_ms. All other rows/columns remain exact. The rebuilt bundled index matches all 66 manifest hashes, 63 package JSON hashes and 15 Doctor artifact hashes; user install records, policy and disabled status are preserved.meta.migrations.webhookListeners(exact empty Telegram/Feishu/Teams/Nextcloud receipt) andwizard.lastRunAt(monotonic). Every other config value remains exact.All 70 other preexisting protected tables remain byte/count-identical, including every session, transcript, stored plugin setting and quarantine row. Upgraded SDK readback loads six sessions and all 24 message appends, reads all four plugin settings, and still enforces the original quarantine. All 74 post-migration protected tables and full config remain exact after readback. Each agent's new empty
session_reactionstable is checked against main's canonical DDL. Shared migration 19→20 retires four empty tables; update receipts record the refused published-driver attempt. The complete database inventory is therefore not claimed unchanged.Exactly one repair backup preserves the orphan and all 30 original protected agent tables; SHA-256
62021c4565f031dc7e1c1d0848652dbdf9dbd5a0775dd7382c272bc6aa0b18d0. Three healthy migration backups share one rollback group and retain original schemas 24/24/19 and all original protected rows. All four original backup file hashes remain exact after validation. The final evidence bundle was downloaded and hash-verified:5f7ce1cd50cb6021991cbea44f0c52bbc738e8ec77e94473c01de77629046895.Commands used (proof helpers are external, synthetic and bound to the frozen head/tree):
The original published updater still refuses the seeded damaged input at
candidate-state-snapshot, before candidate activation; its release package and 72 protected tables are preserved. The candidate cannot patch that already-installed driver. The explicit package-manager install then exercises the candidate's actual Doctor repair. This limitation remains visible despite the compatibility PASS.The already-passing stock
base,sqlite-volumescenarios are retained as historical evidence at8ed2da3cd990237b23c7feae9350892144fcc0f0, leasecbx_d1452a89845a; they were not rerun or relabeled as current-head evidence. Stock run: base 1,512 seconds, volume 2,335 seconds. The large fixture preserves 4,800 sessions, 23,890 transcript events, 2,200 cron jobs and 512 plugin settings; a real Gateway reads eight conversations across two agents. Idempotent Doctor takes 473 seconds under main's state-derived 717-second budget, and final restart succeeds.The AWS lease is released, confirmed by
crabbox list --provider aws; no owned lease remains active. Completed review and baseline worktrees were removed. No operator Gateway, state or ports were touched. The PR remains open and ready for review, with the inherited CI failures documented; it has not been merged.Landing evidence for
67c17df5a7b85ec42df9454fc3918b76e2d45a42This is the coordinator-approved head after clean main merges, including the pending-input and quarantine-hydration test fixes. The coordinator reports core types and all seven changed test files passing on this merged tree. The scoped runtime and compatibility evidence above remains historical evidence for the unchanged recovery implementation.
Current-head CI run 37893488384, attempt 1 completed with 86 successful jobs, 23 skipped jobs, one inherited test-job failure and its downstream aggregate gate failure; no jobs were cancelled. The sole failing case is
src/gateway/conversation-list.test.ts→worker conversation reads > refuses a replaced source while conversation-rows is pending:Error: Conversation read was not dispatched(PR job 113699823793).The same case and error independently fail in scheduled main run 37889372602, job 113686779732, on
53868c16088fd9cc86e84340178d8291c7a6f133. The test, promise gate and relevant conversation-read source blobs match that baseline, the PR's tested merge4a6cb3b5a60c326e2db3631da6988a42903823e7, and maine6ca676b02b6cd6e9a56f588ba5c0e784a6d27d1. The fixture watcheshistoryLane.pool.run, while cold reads route throughtargetDiscoveryLane; no damaged database or latched integrity refusal exists in this fixture. These causal routing owners are untouched by this PR. This is independent baseline execution plus current-source revalidation, not a newly executed current-main test.Landing uses the native inherited-failure exception and retains the failed CI result. The independently enforced security and review gates still apply. Related: #167287 stays open; orphan production and repeated-failure notifications remain outside this recovery fix.