Repository navigation
fix(gateway): upgrade state in place at start instead of refusing for copy space - #201716
fuller-stack-dev wants to merge 24 commits into
Conversation
…image per outdated database
…and finish an interrupted chain
…sts when the start owns the image
|
🦞👀 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. |
|
Replica-shaped Gateway start on a real 30 GiB APFS disk image (release databases v22/v27 plus 40 GiB of Codex session history; no mocks). RED, base pr2-red.mp4GREEN, head pr2-green.mp4 |
|
Codex review: stale review; fresh review needed. Summary Next step Review history (1 earlier review cycle)
|
…image - Keep the in-place work directory once the migration started, and drop an interrupted record only after the new one holds its inventory. - Carry the first run's file inventory across a resume. - Resume on every database the interrupted start imaged; replace a leftover image of a finished upgrade instead of reusing it. - Record only created databases (and their companions) as trial additions, so a revert never deletes a moved-source archive. - Fold the live WAL of an imaged database in before the fallback rebuild. - Restore a symlinked config through its link. - A full disk while publishing an image or the config image skips it. - The launcher compares the image it would restore, not the live file, against the previous release's schema limits. - Heartbeat backups no longer follow the start's image ownership. - The e2e digest reads every table, WITHOUT ROWID included.
…y on evidence - The fallback rebuilds from the live databases as the chain left them, so rows Doctor already imported stay; images remain the rollback baseline. - An imaged database's WAL is folded in through SQLite before the swap; if the checkpoint or mode switch is refused, the start stops with every file in place. - The durable plan carries the run's additions, so a resumed swap records them. - The resume record names every database its run started on, imaged or not. - The config image is written 0600 when the config is a link. - Full-disk and space-admission errors are recognized through wrapping causes. - The launcher reverts only on positive evidence: the previous release's declared schemas, each remaining database's header and shared content version, and the config's image after an upgrade; it ignores databases the revert removes.
… the trial without one - A config refusal that restores the images also renames Doctor's `.migrated` archives of this run back to their sources; the launcher does the same and stays forward when a source name was taken again. - A resumed run keeps only the images the interrupted run recorded; a database it started on without one is never imaged again after it may have changed. - A linked config is neither imaged nor written through. - When a database the run starts on has no image, the start ends the Git release trial before migrating, so no launcher, old or new, reverts onto a release that refuses the state. - Doctor keeps its backup set when a pending store lies outside the start's own discovery. - The launcher reads a restored image with its preserved WAL, stays forward on an unreadable record or agent listing, and removes created databases with their companions.
…oved legacy source - A refusal restore writes restore.json first; the next start finishes it before anything else, and the run's created databases leave with it. - A file that existed before Doctor and is gone after (a legacy source Doctor moved into SQLite, whatever its archive name) blocks the refusal restore and is recorded as a remove op; the launcher stays forward on it, also from an interrupted run's inventory, instead of mirroring each owner's archive names. - The launcher counts .sqlite stores missing from an interrupted inventory as additions. - Doctor ends the Git release trial before migrating a store outside the start's discovery, which no launcher can restore. - The record's directory entry and the config image's directory are fsynced. - Docs state Doctor's remaining backups, the complete-set rule and the first hop.
…ts images do not cover - The start images the outdated databases, the shared state (which Doctor writes even when current) and the config. After the chain it compares an explicit allowlist: a file from the inventory that is gone, a store created, or a store or config written without an image ends the trial, so no launcher (old or new) reverts past it, and a refusal keeps the state migrated. - The archive-name restore, moved-source records, launcher inventory scans and the addition bookkeeping are gone; the launcher stays forward on any unfinished upgrade. - Doctor's backup exemption covers exactly the stores the start's record names, resolved, so a store behind a linked agent directory keeps its backup. - The applied record is fsynced before the work record goes; only a missing restore record means no restore is in progress. - Machine-failure checks reuse collectNestedErrorCandidates. - Drop the test-line allocation; the remaining growth is reported in the PR.
… migrated A run of Doctor in place can change state no image covers (configured legacy sources outside the state directory, stores it writes) and can stop before any check sees it, so no revert after a migration can be shown safe: - The start ends the Git release trial before Doctor runs; a later failed start stays on the new release and is fixed forward, under the old launcher too. - A refused start keeps the state migrated with its images; the restore record, the outside-change allowlist and the shared-state image go away. - Only outdated databases (and the config) are imaged. - An interrupted in-place record of another build is resumed, not discarded; only a missing inventory means the run had changed nothing. - Custody takes the owner-lease check on live reads, so it stages no private copy of the shared database that a small scratch volume could refuse. - Doctor skips its capture and backup set only when the start's own record is present; a store it names is matched by resolved path. - The success message counts missing images against the imaged databases.
…ith their build - A Doctor child stopped by a signal leaves the upgrade pending (no fallback over a half-done run); the next start reruns it. - Images another build took, which a resumed run reused, keep their generation at finish instead of being pruned as stale. - A recorded database newer than this build is never resumed or rebuilt down. - Ending a Git release trial syncs the trial directory before any migration. - Remove the shadow tree walker the in-place path no longer uses.
…ates-in-place # Conflicts: # src/commands/doctor-migration-backup.ts
|
Closing in favour of class C in #204775 (#204752): copy only the databases an update migrates, clone where the filesystem allows, and refuse before the Gateway stops when a copy cannot fit. The large-state case this PR was written for (about 70 GiB to copy with about 100 GiB free) becomes a class C test case. The one case I asked to keep open there is a schema change to a large database on a filesystem that cannot clone; that discussion continues on #204775. The branch stays in place, including its clone code, for reference. |
## Problem Gateway boot copies a private state tree, runs Doctor there, and publishes database replacements. The generic rebuild fallback adds another migration owner. Update cost grows with unrelated state and retains competing copy/swap machinery. Based on main ba96ee5, including #204956. Main only; no release-branch changes. ## Fix - Migrate canonical databases in place through existing state, agent and engine owners under exclusive custody. - Keep `discoverDatabases` as the inventory. Reuse #204915's per-release `.restore` v1 receipt; only a raised reader floor needs a database image. SQLite images are independent CoW clones or byte copies, never hard links. PostgreSQL copies a namespace only as its rollback image. - Keep the installed launcher's `.pre-<build-generation>` naming and existing `kind: add` receipt contract. No launcher reader or resident transition is added. - Reuse legacy-file imports, native credential custody, heartbeat/config repair and session imports on live paths. Include repair preserves authored directives and images every changed physical file. - Admit projected config and its source/hot-journal guard first; close that snapshot, migrate under the exclusive owner, then enforce database readiness. Config still invalid after projection refuses before writes. - Retain the session import/post-session handoff from Doctor (`doctor-health-contribution-runners.state.ts:62–84`; `doctor-session-transcripts.ts:227–355`). - Retain historical BLOB-backed TEXT repair from `de5a86ead888^:src/state/state-upgrade-tree.ts:719–753`, now in existing schema repair before typed readers and only for outdated databases. The original order normalized before `runChain` (`state-upgrade.ts:454–481`), not inside Doctor. Normalization now uses one existing transaction per database; conflicts roll back, name the table/key and take the existing exit-78 refusal path. - Preserve an already-lower reader floor during same-version Doctor repair. - Delete the shadow-tree writer, generic rebuild/value helpers, forward database swap wrappers, copied-target validation/readability, Doctor-on-copy process, copy-only CLI handoff and copied-state fixtures. Existing retention and historical receipt readers remain. - Settle only already-written `.upgrade-*/plan.json` before state reads. Stable 2026.11.10 shipped these plans; finishing one preserves committed WAL rows after an interrupted companion removal. No new plan is written. - Implement the engine gate's existing migrations permission at its one execution owner. Ordinary Gateway, closed/expired custody and config-only custody still refuse. No new table, column, stored-row shape, migration option or fallback. Clone reuse follows @fuller-stack-dev's #201716 via existing `copySqliteFile`. Related: #198389, #168750, #161888; retains #204752/#204227 inventory and clean-WAL work. ## User impact Starts and updates stop copying/replacing the state tree. Compatible schema steps, including compatible external stores, take no database image. Floor-raising rollback uses only the recorded image; unsupported paths refuse before the old Gateway stops with move/retry instructions. Accepted cost: without CoW, a floor-raising boot takes one byte copy of that database. No size refusal or 30-second probe. Required-image failure refuses before that step. Non-trial starts do not acquire copy-only prerequisites. Historical imports must retain sessions. The six published-release corpora remain required. One-time empty-source ownership maintenance is followed by a no-op boot; its regression preserves bytes on the second boot. Inherited frozen-reader edge: **A commits → downgrade T → return to the same A build → A fails before replacing its receipt** can consume stale build-keyed `kind: add` entries (`rollback-source.ts:39–55`). Existing debt; the paused per-release manifest reader removes it. Legacy-import plans may conservatively declare prospective stores. A future manifest reader could remove a store created later at such a path during rollback. This is accepted only on the one-time legacy-import path, not schema-only/additive updates; absent targets are now excluded unless existing source owners report legacy import sources. Accepted recovery edge: an invalid legacy `device.json` with no canonical identity is refused after the in-place schema upgrade; the existing full original backup preserves the pre-upgrade bytes. Canonical identity retains its shipped precedence over an invalid legacy file. No new credential reader or custody bypass is added. ## Evidence and current gate Remote head: **d449180993a4ee51aa180d9cb0a6b25ecdd27d52**. Current CI is the maintainer's final gate; earlier results remain scoped to their tested heads. The latest focused PostgreSQL proof is recorded below. - On the preceding 033d3de production tree, `ocx build --dist` passed, then selected **2026.7.1-blob E2E passed (20.94s)** with combined projection, additive-only and corrected historical non-STRICT normalization changes. The first version-only gate failed this corpus; the corrected gate passed. - Corrected Doctor/native-bootstrap/admission files **49/49 passed**; restored original fresh-profile pending-pin/offline-handoff contract **9/9 passed**; recovery tests passed, including localhost/0.0.0.0. - Final catalog-only migration observer **7/7 passed**. Inventory **27/27 passed**. Leasehold **4/4** and admission gate **7 passed/3 PostgreSQL skipped** passed on the initial catalog repair; the final historical gate was additionally qualified by the observer and BLOB corpus. - PostgreSQL tests had **6 skips** without a qualified local connection. Neither skips nor the inventory-only run qualify the live PostgreSQL behavior. - Local import-cycles, Madge (0 cycles) and Kysely guards passed on the repair batch. This is not behavioral proof. - On committed **bda681956e**, `ocx build --dts` completed the actual full build in 13m05s (not a cache hit), including native declarations and all 165 public SDK subpaths. Earlier infrastructure-only lock/admission failures were resolved without changing source or bypassing ownership. - Baseline regressions proved: [run_f5d15c230817a891fa97f1a7218498af](https://crabbox.openclaw.ai/portal/runs/run_f5d15c230817a891fa97f1a7218498af). Pinned `434459170f` loses the WAL witness at the selected assertion and refuses with `config original must precede manifest`; pinned `d31b2ca386` refuses the repairable include with `config-invalid: diagnostics.otel`. Only test fixtures were overlaid. Lease released with `--wait`. - **Older a5ef head:** [run_d4822472e48e3a5f847c9bde74317959](https://crabbox.openclaw.ai/portal/runs/run_d4822472e48e3a5f847c9bde74317959): full build, package and all six historical corpora **passed** (2026.7.1, 7.1-blob, 7.35, 8.35, 9.37, 10.10; seven tests including invalid-config preservation, zero skips). Admission/owner/live-PG/test-types/lint failed; subsequent fixes are not called green without verification. - **Older 78af head only:** published 2026.11.10 routed Gateway API upgrade passed: [run_605e7f763523ff2d8dd7d20b7428893f](https://crabbox.openclaw.ai/portal/runs/run_605e7f763523ff2d8dd7d20b7428893f), product row `e4d2cb81-841a-46a1-a6b7-50164052d3cd`, state40→42/agent42→44, clean WAL without SHM accepted, exact commit serving, no sampled/final `.upgrade-*` tree. Product downtime82.424s; sampled95.671s. This does not qualify the current head's modern selective-image contract. - **539 diagnostic only:** [run_cbb2a0713d7096f4e6a9588d3b0a4f9c](https://crabbox.openclaw.ai/portal/runs/run_cbb2a0713d7096f4e6a9588d3b0a4f9c), one cron case: Gateway ready, zero provider requests, pre-run persistence refused missing `public.unaccent`. The private AWS driver omitted extension provisioning present in canonical CI; the driver is corrected, with no speculative product change. This is setup-failure evidence, not a passing cron result. Lease released with `--wait`. - Obsolete 716 proof lanes were stopped by maintainer direction; every lease was released with `--wait`. Current-head native rollback, interrupted-plan startup and additive-boot qualification remain unproven. No AWS lease remains allocated. Remaining proof gaps: current-head CI, live PostgreSQL, and the native scenarios above. Inherited failures left unchanged: checkpoint timing at `agent-database-startup-verification.test.ts:340` (#205290); scheduled-turn budget failure matches [scheduled main run45634242694/job139276192521](https://github.com/openclaw/openclaw/actions/runs/45634242694/job/139276192521) exactly. For be51's merge-only stale-validator failure, owner regeneration left all52 outputs unchanged with identical SHA-256 manifests; no generated output was hand-edited. On 033d3de, `tokei` on all46 touched `src` production files, excluding `*.test.ts`, `*.test-support.ts` and `*.test-harness.ts`, against ba96ee5: **15,307→13,481 (-1,826)** code lines. Whole PR including tests/docs: **+3,586/-6,364, net -2,778**. ### PostgreSQL startup admission follow-up Under PostgreSQL, retired heartbeat configuration is now repaired at startup instead of merely reported: startup is valid, the legacy heartbeat is durably removed, and PostgreSQL configuration is retained. The ordinary main-thread PostgreSQL refusal remains enforced. Only synchronous Doctor manifest selection uses the existing engine admission; no admission spans asynchronous preparation. The focused regression passed locally against the CI-pinned PostgreSQL 16 Docker image with `unaccent`, `pg_trgm` and `vector`: **1 passed, 5 unselected cases skipped**. Extended-stack reproduction identified the bundled-discovery policy read during Doctor manifest selection; the fixed test verifies the persisted repair. The owned container was removed after proof. This qualifies the selected regression, not the entire PostgreSQL suite. Co-authored-by: Ayaan Zaidi <[email protected]>
…205165) ## Problem Gateway boot copies a private state tree, runs Doctor there, and publishes database replacements. The generic rebuild fallback adds another migration owner. Update cost grows with unrelated state and retains competing copy/swap machinery. Based on main c6eb8cd, including openclaw#204956. Main only; no release-branch changes. ## Fix - Migrate canonical databases in place through existing state, agent and engine owners under exclusive custody. - Keep `discoverDatabases` as the inventory. Reuse openclaw#204915's per-release `.restore` v1 receipt; only a raised reader floor needs a database image. SQLite images are independent CoW clones or byte copies, never hard links. PostgreSQL copies a namespace only as its rollback image. - Keep the installed launcher's `.pre-<build-generation>` naming and existing `kind: add` receipt contract. No launcher reader or resident transition is added. - Reuse legacy-file imports, native credential custody, heartbeat/config repair and session imports on live paths. Include repair preserves authored directives and images every changed physical file. - Admit projected config and its source/hot-journal guard first; close that snapshot, migrate under the exclusive owner, then enforce database readiness. Config still invalid after projection refuses before writes. - Retain the session import/post-session handoff from Doctor (`doctor-health-contribution-runners.state.ts:62–84`; `doctor-session-transcripts.ts:227–355`). - Retain historical BLOB-backed TEXT repair from `de5a86ead888^:src/state/state-upgrade-tree.ts:719–753`, now in existing schema repair before typed readers and only for outdated databases. The original order normalized before `runChain` (`state-upgrade.ts:454–481`), not inside Doctor. Normalization now uses one existing transaction per database; conflicts roll back, name the table/key and take the existing exit-78 refusal path. - Preserve an already-lower reader floor during same-version Doctor repair. - Delete the shadow-tree writer, generic rebuild/value helpers, forward database swap wrappers, copied-target validation/readability, Doctor-on-copy process, copy-only CLI handoff and copied-state fixtures. Existing retention and historical receipt readers remain. - Settle only already-written `.upgrade-*/plan.json` before state reads. Stable 2026.11.10 shipped these plans; finishing one preserves committed WAL rows after an interrupted companion removal. No new plan is written. - Implement the engine gate's existing migrations permission at its one execution owner. Ordinary Gateway, closed/expired custody and config-only custody still refuse. No new table, column, stored-row shape, migration option or fallback. Clone reuse follows @fuller-stack-dev's openclaw#201716 via existing `copySqliteFile`. Related: openclaw#198389, openclaw#168750, openclaw#161888; retains openclaw#204752/openclaw#204227 inventory and clean-WAL work. ## User impact Starts and updates stop copying/replacing the state tree. Compatible schema steps, including compatible external stores, take no database image. Floor-raising rollback uses only the recorded image; unsupported paths refuse before the old Gateway stops with move/retry instructions. Accepted cost: without CoW, a floor-raising boot takes one byte copy of that database. No size refusal or 30-second probe. Required-image failure refuses before that step. Non-trial starts do not acquire copy-only prerequisites. Historical imports must retain sessions. The six published-release corpora remain required. One-time empty-source ownership maintenance is followed by a no-op boot; its regression preserves bytes on the second boot. Inherited frozen-reader edge: **A commits → downgrade T → return to the same A build → A fails before replacing its receipt** can consume stale build-keyed `kind: add` entries (`rollback-source.ts:39–55`). Existing debt; the paused per-release manifest reader removes it. Legacy-import plans may conservatively declare prospective stores. A future manifest reader could remove a store created later at such a path during rollback. This is accepted only on the one-time legacy-import path, not schema-only/additive updates; absent targets are now excluded unless existing source owners report legacy import sources. Accepted recovery edge: an invalid legacy `device.json` with no canonical identity is refused after the in-place schema upgrade; the existing full original backup preserves the pre-upgrade bytes. Canonical identity retains its shipped precedence over an invalid legacy file. No new credential reader or custody bypass is added. ## Evidence and current gate Remote head: **d449180993a4ee51aa180d9cb0a6b25ecdd27d52**. Current CI is the maintainer's final gate; earlier results remain scoped to their tested heads. The latest focused PostgreSQL proof is recorded below. - On the preceding 033d3de production tree, `ocx build --dist` passed, then selected **2026.7.1-blob E2E passed (20.94s)** with combined projection, additive-only and corrected historical non-STRICT normalization changes. The first version-only gate failed this corpus; the corrected gate passed. - Corrected Doctor/native-bootstrap/admission files **49/49 passed**; restored original fresh-profile pending-pin/offline-handoff contract **9/9 passed**; recovery tests passed, including localhost/0.0.0.0. - Final catalog-only migration observer **7/7 passed**. Inventory **27/27 passed**. Leasehold **4/4** and admission gate **7 passed/3 PostgreSQL skipped** passed on the initial catalog repair; the final historical gate was additionally qualified by the observer and BLOB corpus. - PostgreSQL tests had **6 skips** without a qualified local connection. Neither skips nor the inventory-only run qualify the live PostgreSQL behavior. - Local import-cycles, Madge (0 cycles) and Kysely guards passed on the repair batch. This is not behavioral proof. - On committed **bda681956e**, `ocx build --dts` completed the actual full build in 13m05s (not a cache hit), including native declarations and all 165 public SDK subpaths. Earlier infrastructure-only lock/admission failures were resolved without changing source or bypassing ownership. - Baseline regressions proved: [run_f5d15c230817a891fa97f1a7218498af](https://crabbox.openclaw.ai/portal/runs/run_f5d15c230817a891fa97f1a7218498af). Pinned `434459170f` loses the WAL witness at the selected assertion and refuses with `config original must precede manifest`; pinned `d31b2ca386` refuses the repairable include with `config-invalid: diagnostics.otel`. Only test fixtures were overlaid. Lease released with `--wait`. - **Older a5ef head:** [run_d4822472e48e3a5f847c9bde74317959](https://crabbox.openclaw.ai/portal/runs/run_d4822472e48e3a5f847c9bde74317959): full build, package and all six historical corpora **passed** (2026.7.1, 7.1-blob, 7.35, 8.35, 9.37, 10.10; seven tests including invalid-config preservation, zero skips). Admission/owner/live-PG/test-types/lint failed; subsequent fixes are not called green without verification. - **Older 78af head only:** published 2026.11.10 routed Gateway API upgrade passed: [run_605e7f763523ff2d8dd7d20b7428893f](https://crabbox.openclaw.ai/portal/runs/run_605e7f763523ff2d8dd7d20b7428893f), product row `e4d2cb81-841a-46a1-a6b7-50164052d3cd`, state40→42/agent42→44, clean WAL without SHM accepted, exact commit serving, no sampled/final `.upgrade-*` tree. Product downtime82.424s; sampled95.671s. This does not qualify the current head's modern selective-image contract. - **539 diagnostic only:** [run_cbb2a0713d7096f4e6a9588d3b0a4f9c](https://crabbox.openclaw.ai/portal/runs/run_cbb2a0713d7096f4e6a9588d3b0a4f9c), one cron case: Gateway ready, zero provider requests, pre-run persistence refused missing `public.unaccent`. The private AWS driver omitted extension provisioning present in canonical CI; the driver is corrected, with no speculative product change. This is setup-failure evidence, not a passing cron result. Lease released with `--wait`. - Obsolete 716 proof lanes were stopped by maintainer direction; every lease was released with `--wait`. Current-head native rollback, interrupted-plan startup and additive-boot qualification remain unproven. No AWS lease remains allocated. Remaining proof gaps: current-head CI, live PostgreSQL, and the native scenarios above. Inherited failures left unchanged: checkpoint timing at `agent-database-startup-verification.test.ts:340` (openclaw#205290); scheduled-turn budget failure matches [scheduled main run45634242694/job139276192521](https://github.com/openclaw/openclaw/actions/runs/45634242694/job/139276192521) exactly. For be51's merge-only stale-validator failure, owner regeneration left all52 outputs unchanged with identical SHA-256 manifests; no generated output was hand-edited. On 033d3de, `tokei` on all46 touched `src` production files, excluding `*.test.ts`, `*.test-support.ts` and `*.test-harness.ts`, against c6eb8cd: **15,307→13,481 (-1,826)** code lines. Whole PR including tests/docs: **+3,586/-6,364, net -2,778**. ### PostgreSQL startup admission follow-up Under PostgreSQL, retired heartbeat configuration is now repaired at startup instead of merely reported: startup is valid, the legacy heartbeat is durably removed, and PostgreSQL configuration is retained. The ordinary main-thread PostgreSQL refusal remains enforced. Only synchronous Doctor manifest selection uses the existing engine admission; no admission spans asynchronous preparation. The focused regression passed locally against the CI-pinned PostgreSQL 16 Docker image with `unaccent`, `pg_trgm` and `vector`: **1 passed, 5 unselected cases skipped**. Extended-stack reproduction identified the bundled-discovery policy read during Doctor manifest selection; the fixed test verifies the persisted repair. The owned container was removed after proof. This qualifies the selected regression, not the entire PostgreSQL suite. Co-authored-by: Ayaan Zaidi <[email protected]>
Gateway boot copies a private state tree, runs Doctor there, and publishes database replacements. The generic rebuild fallback adds another migration owner. Update cost grows with unrelated state and retains competing copy/swap machinery. Based on main ba96ee5, including #204956. Main only; no release-branch changes. - Migrate canonical databases in place through existing state, agent and engine owners under exclusive custody. - Keep `discoverDatabases` as the inventory. Reuse #204915's per-release `.restore` v1 receipt; only a raised reader floor needs a database image. SQLite images are independent CoW clones or byte copies, never hard links. PostgreSQL copies a namespace only as its rollback image. - Keep the installed launcher's `.pre-<build-generation>` naming and existing `kind: add` receipt contract. No launcher reader or resident transition is added. - Reuse legacy-file imports, native credential custody, heartbeat/config repair and session imports on live paths. Include repair preserves authored directives and images every changed physical file. - Admit projected config and its source/hot-journal guard first; close that snapshot, migrate under the exclusive owner, then enforce database readiness. Config still invalid after projection refuses before writes. - Retain the session import/post-session handoff from Doctor (`doctor-health-contribution-runners.state.ts:62–84`; `doctor-session-transcripts.ts:227–355`). - Retain historical BLOB-backed TEXT repair from `de5a86ead888^:src/state/state-upgrade-tree.ts:719–753`, now in existing schema repair before typed readers and only for outdated databases. The original order normalized before `runChain` (`state-upgrade.ts:454–481`), not inside Doctor. Normalization now uses one existing transaction per database; conflicts roll back, name the table/key and take the existing exit-78 refusal path. - Preserve an already-lower reader floor during same-version Doctor repair. - Delete the shadow-tree writer, generic rebuild/value helpers, forward database swap wrappers, copied-target validation/readability, Doctor-on-copy process, copy-only CLI handoff and copied-state fixtures. Existing retention and historical receipt readers remain. - Settle only already-written `.upgrade-*/plan.json` before state reads. Stable 2026.11.10 shipped these plans; finishing one preserves committed WAL rows after an interrupted companion removal. No new plan is written. - Implement the engine gate's existing migrations permission at its one execution owner. Ordinary Gateway, closed/expired custody and config-only custody still refuse. No new table, column, stored-row shape, migration option or fallback. Clone reuse follows @fuller-stack-dev's #201716 via existing `copySqliteFile`. Related: #198389, #168750, #161888; retains #204752/#204227 inventory and clean-WAL work. Starts and updates stop copying/replacing the state tree. Compatible schema steps, including compatible external stores, take no database image. Floor-raising rollback uses only the recorded image; unsupported paths refuse before the old Gateway stops with move/retry instructions. Accepted cost: without CoW, a floor-raising boot takes one byte copy of that database. No size refusal or 30-second probe. Required-image failure refuses before that step. Non-trial starts do not acquire copy-only prerequisites. Historical imports must retain sessions. The six published-release corpora remain required. One-time empty-source ownership maintenance is followed by a no-op boot; its regression preserves bytes on the second boot. Inherited frozen-reader edge: **A commits → downgrade T → return to the same A build → A fails before replacing its receipt** can consume stale build-keyed `kind: add` entries (`rollback-source.ts:39–55`). Existing debt; the paused per-release manifest reader removes it. Legacy-import plans may conservatively declare prospective stores. A future manifest reader could remove a store created later at such a path during rollback. This is accepted only on the one-time legacy-import path, not schema-only/additive updates; absent targets are now excluded unless existing source owners report legacy import sources. Accepted recovery edge: an invalid legacy `device.json` with no canonical identity is refused after the in-place schema upgrade; the existing full original backup preserves the pre-upgrade bytes. Canonical identity retains its shipped precedence over an invalid legacy file. No new credential reader or custody bypass is added. Remote head: **d449180993a4ee51aa180d9cb0a6b25ecdd27d52**. Current CI is the maintainer's final gate; earlier results remain scoped to their tested heads. The latest focused PostgreSQL proof is recorded below. - On the preceding 033d3de production tree, `ocx build --dist` passed, then selected **2026.7.1-blob E2E passed (20.94s)** with combined projection, additive-only and corrected historical non-STRICT normalization changes. The first version-only gate failed this corpus; the corrected gate passed. - Corrected Doctor/native-bootstrap/admission files **49/49 passed**; restored original fresh-profile pending-pin/offline-handoff contract **9/9 passed**; recovery tests passed, including localhost/0.0.0.0. - Final catalog-only migration observer **7/7 passed**. Inventory **27/27 passed**. Leasehold **4/4** and admission gate **7 passed/3 PostgreSQL skipped** passed on the initial catalog repair; the final historical gate was additionally qualified by the observer and BLOB corpus. - PostgreSQL tests had **6 skips** without a qualified local connection. Neither skips nor the inventory-only run qualify the live PostgreSQL behavior. - Local import-cycles, Madge (0 cycles) and Kysely guards passed on the repair batch. This is not behavioral proof. - On committed **bda681956e**, `ocx build --dts` completed the actual full build in 13m05s (not a cache hit), including native declarations and all 165 public SDK subpaths. Earlier infrastructure-only lock/admission failures were resolved without changing source or bypassing ownership. - Baseline regressions proved: [run_f5d15c230817a891fa97f1a7218498af](https://crabbox.openclaw.ai/portal/runs/run_f5d15c230817a891fa97f1a7218498af). Pinned `434459170f` loses the WAL witness at the selected assertion and refuses with `config original must precede manifest`; pinned `d31b2ca386` refuses the repairable include with `config-invalid: diagnostics.otel`. Only test fixtures were overlaid. Lease released with `--wait`. - **Older a5ef head:** [run_d4822472e48e3a5f847c9bde74317959](https://crabbox.openclaw.ai/portal/runs/run_d4822472e48e3a5f847c9bde74317959): full build, package and all six historical corpora **passed** (2026.7.1, 7.1-blob, 7.35, 8.35, 9.37, 10.10; seven tests including invalid-config preservation, zero skips). Admission/owner/live-PG/test-types/lint failed; subsequent fixes are not called green without verification. - **Older 78af head only:** published 2026.11.10 routed Gateway API upgrade passed: [run_605e7f763523ff2d8dd7d20b7428893f](https://crabbox.openclaw.ai/portal/runs/run_605e7f763523ff2d8dd7d20b7428893f), product row `e4d2cb81-841a-46a1-a6b7-50164052d3cd`, state40→42/agent42→44, clean WAL without SHM accepted, exact commit serving, no sampled/final `.upgrade-*` tree. Product downtime82.424s; sampled95.671s. This does not qualify the current head's modern selective-image contract. - **539 diagnostic only:** [run_cbb2a0713d7096f4e6a9588d3b0a4f9c](https://crabbox.openclaw.ai/portal/runs/run_cbb2a0713d7096f4e6a9588d3b0a4f9c), one cron case: Gateway ready, zero provider requests, pre-run persistence refused missing `public.unaccent`. The private AWS driver omitted extension provisioning present in canonical CI; the driver is corrected, with no speculative product change. This is setup-failure evidence, not a passing cron result. Lease released with `--wait`. - Obsolete 716 proof lanes were stopped by maintainer direction; every lease was released with `--wait`. Current-head native rollback, interrupted-plan startup and additive-boot qualification remain unproven. No AWS lease remains allocated. Remaining proof gaps: current-head CI, live PostgreSQL, and the native scenarios above. Inherited failures left unchanged: checkpoint timing at `agent-database-startup-verification.test.ts:340` (#205290); scheduled-turn budget failure matches [scheduled main run45634242694/job139276192521](https://github.com/openclaw/openclaw/actions/runs/45634242694/job/139276192521) exactly. For be51's merge-only stale-validator failure, owner regeneration left all52 outputs unchanged with identical SHA-256 manifests; no generated output was hand-edited. On 033d3de, `tokei` on all46 touched `src` production files, excluding `*.test.ts`, `*.test-support.ts` and `*.test-harness.ts`, against ba96ee5: **15,307→13,481 (-1,826)** code lines. Whole PR including tests/docs: **+3,586/-6,364, net -2,778**. Under PostgreSQL, retired heartbeat configuration is now repaired at startup instead of merely reported: startup is valid, the legacy heartbeat is durably removed, and PostgreSQL configuration is retained. The ordinary main-thread PostgreSQL refusal remains enforced. Only synchronous Doctor manifest selection uses the existing engine admission; no admission spans asynchronous preparation. The focused regression passed locally against the CI-pinned PostgreSQL 16 Docker image with `unaccent`, `pg_trgm` and `vector`: **1 passed, 5 unselected cases skipped**. Extended-stack reproduction identified the bundled-discovery policy read during Doctor manifest selection; the fixed test verifies the persisted repair. The owned container was removed after proof. This qualifies the selected regression, not the entire PostgreSQL suite. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit e43debf) Release adaptation: floorRaisingDatabases drops the agent v44 member-access additive exception because release has no v44 schema; release keeps the restore-path owner in state-upgrade-databases.ts as on main (release-only state-upgrade-paths.ts from the #204916 adaptation removed along with state-upgrade-tree.ts); modify/delete conflicts on files absent from release (upgrade-survivor-migration-chain test, historical declared-input fixtures) keep the release state; remaining conflicts resolved by applying the source change over release-only hunks. Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vincentkoc <[email protected]>
What Problem This Solves
When a new OpenClaw build started on state from an older release, the Gateway upgraded its databases in a private shadow:
That had two costs:
Separately, if the migration committed and the new build still failed twice, the launcher switched back to a previous release that cannot open the newer schema.
User Impact
<file>.pre-<buildId>:openclaw triage.cron/jobs.json).state/openclaw.sqlitein place, so it stays the same file.Why This Change Was Made
The owner approved option D in the copy inventory, fix-plan items 8 and 9:
Every schema step commits in one SQLite transaction with its version bump.
This head also repairs the data-safety findings of the landing round on
d533da100e2, verdicts below. It holds one rule everywhere:The state machine section lists every file family and step against that rule.
Boot upgrade (
src/state/state-upgrade.ts,state-upgrade-tree.ts)copySqliteFile,@openclaw/fs-safe).copyTree,diffTree, prefix rewriting) are gone.restore.jsonthat the next start finishes if this one stops, and the databases the run created are removed. Otherwise the databases stay migrated and the start says why. A linked config is neither imaged nor written through.Doctor (
flows/doctor-health.ts,commands/doctor-*.ts)--state-upgrade-live-state-dir. No new flag, environment variable or config key was added.preImageOwner: "state-upgrade"), unless a pending store lies outside the start's own discovery (a configured agent directory); then it takes its normal set.openclaw doctor --fixkeeps its backups.Launcher (
src/infra/git-release-launcher.ts)After two failed starts, before changing anything, it reverts only when all of these hold:
openclaw.schemaVersions.node:sqliteis available.state.schema.contentVersion, the same admission facts that release applies. Databases the revert removes as additions are skipped.Anything else keeps the service forward, with a message that lists what was not proven. No new
.trialfield.Update behavior for published updaters
publishGitRelease), so this rule applies from the first update after the updater that ships it..pre-<buildId>file newer than the trial, which includes this start's images, so a first-hop revert lands safely whenever every outdated database was imaged. When one has no image, this start ends the trial before migrating, so the earlier launcher never counts the failed starts and cannot revert onto a refusing release. What the earlier launcher still does not check is a legacy source Doctor moved; on the first hop, a revert after such a move leaves that source archived, as the copy-and-swap upgrade's revert did not (its Doctor ran in the shadow).Steps left to a person: none. A start that cannot fit the migration says so, and resumes once space is free. A trial that stays forward points to
openclaw triage.State machine of the start's upgrade
Rule held at every step: a file that may hold committed data is deleted or replaced only after its replacement is durable and verified. A failure at any step leaves the previous state recoverable. The launcher reverts only on positive evidence.
File families the start touches:
D, withD-wal,D-shm,D-journalandD.seal.C, which can be a symlink.D.pre-<gen>andC.pre-<gen>..upgrade-<gen>-<pid>-<t>/. It holdsinventory.json({files, outdated, images}),chain.log, the fallback'sfallback/builds,plan.json(fallback only) andrestore.json(refusal only)..upgraded-<gen>.json..migrated,.migrated.<n>,.migrated-<stamp>-<id>, by owner). The start never deletes or renames these. A source missing after the run is recorded as aremoveop, and it blocks every revert.In the table, "Restart" is what the next start does. "Test" names the test that covers the row: unit tests are in
state-upgrade.test.tsunless another file is named, the kill sweep is "sweep" and the fallback kill sweep is "fb-sweep".restore.json(idempotent). Applies an interrupted durableplan.json(idempotent). Reads an interrupted record of this build and keeps it. Deletes other builds' plan-less records (scratch only).releases retained handles before finishing an interrupted plan;records the fallback's additions when its swap is interrupted and resumed.upgrade-<gen>-*(empty); fsync of the state directorypre|0DDthrough SQLite (never deletesD-wal). WritesD.pre-<gen>.partial-<pid>and renames it toD.pre-<gen>, which replaces a finished run's leftover only by that rename. A full disk, wrapped or not, skips the image. On resume, aDthe interrupted run started on keeps only the image that run recorded, else none; it is never imaged after it may have changed.Dunchanged.images only the outdated databases…;migrates without an image when a copy…;skips the image when a copy layer wraps a full disk;replaces a leftover image…;resumes only with images the interrupted run published…; sweeppre|0/5/20CC.pre-<gen>.partial(mode 0600, exclusive create), fsync, rename, fsync of its directory. A full disk skips it. A linkedCis never imaged or written: the config writer does not follow a final link.Cunchanged.images a config privately, and never writes through a linked one;keeps a config outside the state directory as a pre-imageDhas no imageresumes only with images…(onUnimagedcalled once)inventory.json({files, outdated, images}) via tmp, fsync, rename, then fsync of the directory.keeps a database it started on without an image in a resumed runkeeps its record when the disk fills mid-chain…D(each step commits with its version bump), the config rewrite and archives of moved sources.Dat its old or new version; record present.abs|*,wal|*;finishes a chain a kill interrupted…;keeps its record when the disk fills mid-chain…Djournal_mode=DELETE. A busy or refused fold stops the start with every file in place.stops the fallback with the live WAL intact when SQLite cannot fold it in; fb-sweepDas the chain left itfallback/Dinside the record and checkpoints it. The liveDis unchanged, so Doctor's imports are kept.keeps rows Doctor committed before the chain failed…; fb-sweepfallback|*Chave an image, and no file from the inventory is gone. Firstrestore.json(files, suffix, created databases) is written durably. Then for each imagedDit deletesD-wal/-journal/-shmand renames the image overD(fsynced at step 2), restoresC, deletes the created databases with their companions, and removes the record.Drestored, the rest still migrated with their images;restore.jsonpresent.a start refused for invalid config restores the previous state(e2e);keeps the state migrated when Doctor moved a legacy source a refusal cannot put back;finishes a refusal's restore that a stop interrupted before anything else;keeps a database it started on without an image…;migrates in place, keeps the pre-image…fallback/D, writesplan.json(replace ops, companion removals and the run's additions) via tmp, fsync and rename, then applies it. Apply order: linkD-waltoD-wal.pre-<gen>only whereDhas no image (otherwise it was folded at 8F), remove the companions, keepD.pre-<gen>(the image, or a hard link ofD), renamefallback/DtoD. Every step is idempotent.records the fallback's additions when its swap is interrupted and resumed; fb-sweepplan|*.upgraded-<gen>.jsonvia tmp and rename. It lists the additions (created databases) and, asremoveops, legacy sources that are gone. The plan carries the same ops; removing an absent file is a no-op.names only the databases it created as trial additions…; fb-sweepapplied|*.pre-*images (never this build's or a pinned one), older applied records and the work record.prunes only owned file generations…Launcher after two failed trial starts (
git-release-launcher.ts; this build's launcher only, see the first hop below):<file>.pre-<gen>with ctime at or after the trial, plus the config image.openclaw triage.openclaw.schemaVersions.node:sqliteis available.git-release.test.ts):stays on the new release when no pre-image…,…content version is newer behind an older header,…declares no schemas,…cannot be read,reverts only when the upgraded config has its image,reverts when the only newer database is one the revert removes(also its WAL),stays forward when Doctor moved a legacy source… (applied record / interrupted inventory),removes a store an interrupted in-place run created when it reverts,reads a restored image together with the WAL preserved beside it,stays forward when an upgrade record cannot be read,switches back and restores the pre-image…,stays on the new release when the image it would restore is newer too,resumes an interrupted rollback…,keeps a family's restored WAL….Landing round on
d533da100e2: verdictsEach "real" verdict comes with a test that fails on
d533da100e2and passes on this head. Thestate-upgrade.test.tsandgit-release.test.tsruns were swapped to thed533da100e2source to show the failure.state-upgrade.ts:600-606atd533da100e2). Real.stops the fallback with the live WAL intact when SQLite cannot fold it in. A reader's open snapshot keeps a committedupdate_runsrow only in the WAL.git-release-launcher.ts:161-165). Real.state.schema.contentVersion. Anything unreadable blocks the revert.stays forward when the shared content version is newer behind an older header,…when a database it would leave cannot be read,…when the previous release declares no schemas.:609-619). Real: the rebuild read the image, while Doctor had already archived the moved sources.keeps rows Doctor committed before the chain failed in the fallback rebuild.:453-463). Real: the resume set was "still outdated or imaged".keeps a database it started on without an image in a resumed run. That refusal now reports that nothing can be restored instead of restoring a partial set.:528-533). Real:copyFileSynccarried the target's 0644.keeps the config image private when the config is a link to a shared file.:503-515). Real for a skipped image; fixed. The old launcher restores the images, so only a skipped image was unsafe.resumes only with images…asserts the hook fires once.git-release-launcher.ts:233-240). Real.reverts when the only newer database is one the revert removes.:705-709). Real: the durable plan held only replacements.records the fallback's additions when its swap is interrupted and resumed. It interrupts the swap's first rename, then resumes.state-upgrade-tree.ts:450-459). Real: only the top-level error was inspected.skips the image when a copy layer wraps a full disk.Two extra changes, found while writing the state machine:
Rating round on
fa77fc2f102(this PR's own round): verdictsThat round rated F / F / F with nine findings. Fixed failing-first on
2ab365b0946, each red againstfa77fc2f102:jobs.jsonarchived as.migrated). Real. The fix is described under the next round's item 3, which replaced this round's first attempt (renaming.migratedarchives back, which missed other owners' archive names).copies only when Doctor owns the image (…, outside the start's discovery=true).reads a restored image together with the WAL preserved beside it.images a config privately, and never writes through a linked one (linked: true), using a read-only link target.resumes only with images the interrupted run published, never a leftover.stays forward when an upgrade record cannot be read.reverts when the only newer database is one the revert removes.config/test-lines-allocations/201716-in-place-state-upgrade.txtwith that reason.Rating round on
2ab365b0946(this PR's own round): verdictsThat round rated F / F / F with six findings. Each fix below fails on
2ab365b0946and passes on this head:restore.jsonis written first, and the resume scan finishes it before anything else.finishes a refusal's restore that a stop interrupted before anything else, which stops at the second image rename.settleRunningGitReleaseTrialis asserted incopies only when Doctor owns the image (…, outside=true)..migrated-<stamp>-<id>for auth profiles). Real.removeop that blocks every revert. An interrupted run's inventory is read the same way by the launcher.keeps the state migrated when Doctor moved a legacy source…,stays forward when Doctor moved a legacy source… (applied record / interrupted inventory)..sqlitefiles absent from an interrupted run's inventory as additions, and a refusal restore removes the run's created databases.removes a store an interrupted in-place run created when it reverts.Product question it raised: boot repair still changes workspace files in place that neither a refusal nor a revert restores. The coordinator accepted this narrower revert for this PR ("state the narrower revert plainly"); it is stated under User Impact and in the docs.
Evidence
In-place kill sweep through the real
gateway runbootupdate_runsrow written before the restart.integrity_checkis ok.user_versionequalsschema_metaand is exactly the old or the new version.d533da100e2).Fallback kill sweep (new)
ChainStepError, so the generic rebuild runs (fallback-driver.mtscallsupgradeStateDirectorywithcreateDoctorChainand throws after Doctor).plan.json;gatewaystart with no fault must finish, serve, reach v40/v43, and keep every witness row.mode: fallback, at v40/v43, with the images at v22/v27, and serves.9061cf9fc6f; rerun pending on this head.Real updater into this build (macOS launchd Git source checkout install, release mode)
openclaw update --channel dev --yes.6691acae(the last commit before the 42 → 43 agent-schema bump) + fix: Git checkout updates no longer fail before the new release starts on a schema change or a busy database #201463 + fix: Git checkout updates across a schema change no longer end as post-update-failed after the new release starts #201600 + this PR's launcher, built. The launcher is written by the installed updater, so only an updater that ships it can run the new rule.d533da100e2: exit 0, schema 43, trial settled, writer alive, runsucceeded)update_runsrows the updater wrote just before the restart survive:keeps the update run … (fallback)andkeeps rows Doctor committed …, and the fallback sweep witness).Not proven or not changed
autoreviewdoes not run on this machine; an independent reviewer agent and ClawSweeper rating rounds reviewed the diff instead.