Skip to content

fix(gateway): upgrade state in place at start instead of refusing for copy space - #201716

Closed
fuller-stack-dev wants to merge 24 commits into
openclaw:mainfrom
fuller-stack-dev:fix/gateway-boot-migrates-in-place
Closed

fuller-stack-dev wants to merge 24 commits into
openclaw:mainfrom
fuller-stack-dev:fix/gateway-boot-migrates-in-place

Conversation

@fuller-stack-dev

@fuller-stack-dev fuller-stack-dev commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

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:

  1. It copied every migration input of the state directory, which on a real install includes large trees such as Codex session history.
  2. It ran Doctor on the copy and swapped the results into place.

That had two costs:

  • Space. The copy demanded twice its own size in free space. On a replica-shaped install with about 70 GiB to copy and about 100 GiB free, the new build refused to start, and the Git release launcher then switched back.
  • Extra copies. Doctor inside the shadow also took its own original-state capture and full pre-migration backups.

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

  • No refusal for snapshot space. The Gateway now upgrades state in place.
  • One image per outdated database, plus the config. Before migrating, the start keeps each as <file>.pre-<buildId>:
    • a copy-on-write clone where the filesystem supports one, which takes about no space;
    • otherwise a byte copy, made only when it still leaves the migration its room;
    • otherwise no image, with a warning. Once that migration commits, the previous release cannot be restored.
  • Revert only on evidence. A Git release trial that fails twice switches back only on positive evidence that the previous release opens what the revert leaves. Otherwise it stays on the new release, says why, and points to openclaw triage.
  • A narrower revert.
    • It restores the outdated databases and the config from their images.
    • It removes the databases the run created.
    • It stays forward when Doctor moved a legacy source the previous release reads (for example cron/jobs.json).
    • It no longer restores other files Doctor changed in place, such as migrated workspace or legacy files. The old copy-and-swap restored those too.
  • Fallback is the only path that replaces a database file. That is the generic rebuild after a failed Doctor chain. A successful start migrates state/openclaw.sqlite in 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:

  • migrate in place;
  • keep a pre-image only for outdated databases (clone or skip);
  • never refuse a start for snapshot space;
  • revert only onto a build that opens the state.

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:

  • delete or replace a file 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.

The state machine section lists every file family and step against that rule.

Boot upgrade (src/state/state-upgrade.ts, state-upgrade-tree.ts)

  • Images. Under the start's exclusive custody, each outdated database is checkpointed through SQLite and imaged by the repository's native clone (copySqliteFile, @openclaw/fs-safe).
    • A byte copy is made only when it leaves the migration its room.
    • An image that cannot be taken is skipped with a warning, including on a full disk reported through a wrapping error.
    • A leftover image from a finished run is replaced only by renaming the complete new image over it.
    • The config image is written 0600, read through a symlink.
  • Chain. Doctor runs on the live state. The 2× copy budget, the shadow copy and its code (copyTree, diffTree, prefix rewriting) are gone.
  • Resume record. The work directory holds a durable inventory: the files before Doctor, the databases the run started on and the images it published.
    • A start that dies or fails after its migration began keeps the record.
    • The next start reruns the chain on every database the run started on, imaged or not, against the images that run recorded. It never images such a database again or trusts a same-named leftover.
    • An interrupted record is removed only after the new one holds its facts.
  • Fallback. It rebuilds each outdated database from the live file as the chain left it, so rows Doctor already imported stay; the image stays the rollback baseline.
    • First it folds an imaged database's live WAL in through SQLite. If SQLite reports the checkpoint busy or refuses the mode switch, the start stops with every file in place.
    • It swaps through the durable plan, which now also carries the run's additions.
  • Config refusal. The state is put back only as a complete set: images of every database the run started on and of an unlinked config, and no legacy source Doctor moved. It is put back through a durable restore.json that 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.
  • Additions. Only databases the run created, and their companions, are recorded for the launcher.
  • No image, no trial. When a database the run starts on has no image, the start ends the Git release trial (the existing settle operation) before anything migrates. Doctor does the same when it finds a pending store outside the start's discovery, since no launcher restores Doctor's backup of it. This is what makes the first hop safe under an older launcher.
  • Custody. The start holds schema-maintenance ownership and lends it to the Doctor child. If another process takes it in between, this start stops and leaves the upgrade to that process.

Doctor (flows/doctor-health.ts, commands/doctor-*.ts)

  • The boot chain already passes the existing hidden internal handoff --state-upgrade-live-state-dir. No new flag, environment variable or config key was added.
  • When that directory is Doctor's own state directory, Doctor takes no original-state capture. It takes no version migration backup set either (preImageOwner: "state-upgrade"), unless a pending store lies outside the start's own discovery (a configured agent directory); then it takes its normal set.
  • The heartbeat retirement backup still runs.
  • Standalone openclaw doctor --fix keeps its backups.

Launcher (src/infra/git-release-launcher.ts)

After two failed starts, before changing anything, it reverts only when all of these hold:

  1. The previous release declares openclaw.schemaVersions.
  2. node:sqlite is available.
  3. The upgrade records and the agent listing are readable, and every database the revert would leave is readable and at or below that release's limit. A restored image with a WAL preserved beside it is read together in a private copy. That is the image it restores, else the live file; for shared state it checks both the header and state.schema.contentVersion, the same admission facts that release applies. Databases the revert removes as additions are skipped.
  4. After an upgrade ran, an unlinked config has an image.
  5. No legacy source the upgrade records (or an interrupted run's inventory) list is gone.

Anything else keeps the service forward, with a message that lists what was not proven. No new .trial field.

Update behavior for published updaters

  • The boot upgrade is new-build code and applies on its first start after any update path.
  • The launcher text is written by the installed updater (publishGitRelease), so this rule applies from the first update after the updater that ships it.
  • First hop. The earlier launcher restores every .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:

  • Each outdated database D, with D-wal, D-shm, D-journal and D.seal.
  • The config C, which can be a symlink.
  • The pre-images D.pre-<gen> and C.pre-<gen>.
  • The resume record .upgrade-<gen>-<pid>-<t>/. It holds inventory.json ({files, outdated, images}), chain.log, the fallback's fallback/ builds, plan.json (fallback only) and restore.json (refusal only).
  • The applied record .upgraded-<gen>.json.
  • Legacy sources Doctor moves into SQLite, and its archives of them (.migrated, .migrated.<n>, .migrated-<stamp>-<id>, by owner). The start never deletes or renames these. A source missing after the run is recorded as a remove op, 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.ts unless another file is named, the kill sweep is "sweep" and the fallback kill sweep is "fb-sweep".

# Step Creates, replaces or deletes If killed right after Restart Test
0 Resume scan Finishes an interrupted restore.json (idempotent). Applies an interrupted durable plan.json (idempotent). Reads an interrupted record of this build and keeps it. Deletes other builds' plan-less records (scratch only). Nothing new. Same scan again. releases retained handles before finishing an interrupted plan; records the fallback's additions when its swap is interrupted and resumed
1 Create the record .upgrade-<gen>-* (empty); fsync of the state directory A plan-less record without an inventory. Resume with nothing changed yet: images are taken or kept, and the chain runs. sweep pre|0
2 Image each outdated D Checkpoints D through SQLite (never deletes D-wal). Writes D.pre-<gen>.partial-<pid> and renames it to D.pre-<gen>, which replaces a finished run's leftover only by that rename. A full disk, wrapped or not, skips the image. On resume, a D the interrupted run started on keeps only the image that run recorded, else none; it is never imaged after it may have changed. Partial or complete image; D unchanged. No inventory yet, so nothing changed: images are retaken. 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…; sweep pre|0/5/20
3 Image C C.pre-<gen>.partial (mode 0600, exclusive create), fsync, rename, fsync of its directory. A full disk skips it. A linked C is never imaged or written: the config writer does not follow a final link. Partial or complete config image; C unchanged. As in 2. images a config privately, and never writes through a linked one; keeps a config outside the state directory as a pre-image
3a End the Git release trial if any D has no image Removes the trial record of the running release (the existing settle operation), before anything migrates. Trial ended; nothing migrated. No launcher counts failed starts, so none reverts onto a release that refuses the state; failures are fixed forward. resumes only with images… (onUnimaged called once)
4 Write the inventory inventory.json ({files, outdated, images}) via tmp, fsync, rename, then fsync of the directory. A record that names the files before Doctor ran, the databases the run started on and the images it published. Reuses both for the additions and the resume set. keeps a database it started on without an image in a resumed run
5 Retire interrupted records Deletes the older records of this build, whose facts are now merged into step 4's record. One record. Resume. keeps its record when the disk fills mid-chain…
6 Normalize text and run the chain (Doctor in place) Doctor's own SQLite transactions on D (each step commits with its version bump), the config rewrite and archives of moved sources. Each D at its old or new version; record present. Reruns the chain on every database the run started on, against the same images. sweep abs|*, wal|*; finishes a chain a kill interrupted…; keeps its record when the disk fills mid-chain…
7 Validate and check conservation Reads only. As in 6. As in 6. sweep
8F Fallback: fold the live WAL of each imaged D SQLite checkpoint plus journal_mode=DELETE. A busy or refused fold stops the start with every file in place. As in 6. As in 6. stops the fallback with the live WAL intact when SQLite cannot fold it in; fb-sweep
9F Fallback: rebuild from the live D as the chain left it Writes fallback/D inside the record and checkpoints it. The live D is unchanged, so Doctor's imports are kept. As in 6, plus scratch output. As in 6; the scratch output is discarded with the old record. keeps rows Doctor committed before the chain failed…; fb-sweep fallback|*
10 Admit the config. On refusal, restore the images. Only a complete set is restored: every database the run started on and an unlinked C have an image, and no file from the inventory is gone. First restore.json (files, suffix, created databases) is written durably. Then for each imaged D it deletes D-wal/-journal/-shm and renames the image over D (fsynced at step 2), restores C, deletes the created databases with their companions, and removes the record. Some D restored, the rest still migrated with their images; restore.json present. The resume scan finishes the restore before anything else. 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…
11 Record diagnostics A row in the live state database (or the fallback's output). As in 6. As in 6 (one more diagnostic row). sweep
12F Fallback: durable plan, then apply it Fsyncs fallback/D, writes plan.json (replace ops, companion removals and the run's additions) via tmp, fsync and rename, then applies it. Apply order: link D-wal to D-wal.pre-<gen> only where D has no image (otherwise it was folded at 8F), remove the companions, keep D.pre-<gen> (the image, or a hard link of D), rename fallback/D to D. Every step is idempotent. Durable plan, partly applied. Applies the same plan to the end and records it (additions included). records the fallback's additions when its swap is interrupted and resumed; fb-sweep plan|*
13 Write the applied record .upgraded-<gen>.json via tmp and rename. It lists the additions (created databases) and, as remove ops, legacy sources that are gone. The plan carries the same ops; removing an absent file is a no-op. Applied record present; work record still present. Chain mode: the record is plan-less, so the chain reruns as a no-op and finishes. Fallback: the plan is reapplied (idempotent). names only the databases it created as trial additions…; fb-sweep applied|*
14 Finish Prunes older generations' .pre-* images (never this build's or a pinned one), older applied records and the work record. Done. Current: nothing to do. 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):

  • The revert set is every <file>.pre-<gen> with ctime at or after the trial, plus the config image.
  • It reverts only when every check below passes. Otherwise the service stays forward, the trial record is removed, and the message lists what was not proven and names openclaw triage.
    1. The previous release declares openclaw.schemaVersions.
    2. node:sqlite is available.
    3. The upgrade records (applied record, plans, interrupted inventories) and the agent directory listing are readable, no legacy source they name is gone, and every database the revert would leave is readable (an image together with the WAL preserved beside it, read in a private copy), at or below the previous release's limit, and, for shared state, has a content version at or below it too. That is the image it restores, else the live file. Databases the revert removes as additions are skipped.
    4. After an upgrade ran, an unlinked config has an image.
  • On revert, it restores state first and moves the link last. An interrupted revert reruns from the recorded restore list.
  • Tests (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: verdicts

Each "real" verdict comes with a test that fails on d533da100e2 and passes on this head. The state-upgrade.test.ts and git-release.test.ts runs were swapped to the d533da100e2 source to show the failure.

  1. Fallback deleted a live WAL when it could not checkpoint it (state-upgrade.ts:600-606 at d533da100e2). Real.
    • Fix: the fallback folds the live WAL in through SQLite and checks the result. If the checkpoint is busy or the mode switch is refused, it stops and deletes nothing.
    • Test: stops the fallback with the live WAL intact when SQLite cannot fold it in. A reader's open snapshot keeps a committed update_runs row only in the WAL.
  2. Launcher read only the header (git-release-launcher.ts:161-165). Real.
    • Fix: shared state is judged by the header and state.schema.contentVersion. Anything unreadable blocks the revert.
    • Tests: 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.
  3. Fallback from the images dropped rows Doctor had imported (:609-619). Real: the rebuild read the image, while Doctor had already archived the moved sources.
    • Fix: the rebuild reads the live databases as the chain left them.
    • Test: keeps rows Doctor committed before the chain failed in the fallback rebuild.
  4. A database without an image was forgotten on resume (:453-463). Real: the resume set was "still outdated or imaged".
    • Fix: the durable inventory records every database the run started on.
    • Test: 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.
  5. Config image not private through a symlink (:528-533). Real: copyFileSync carried the target's 0644.
    • Fix: the image is created 0600 with exclusive create.
    • Test: keeps the config image private when the config is a link to a shared file.
  6. First hop is governed by the old launcher (:503-515). Real for a skipped image; fixed. The old launcher restores the images, so only a skipped image was unsafe.
    • Fix: when a database the run starts on has no image, the start ends the trial before migrating, through the existing settle operation that a serving Gateway already performs.
    • Test: resumes only with images… asserts the hook fires once.
    • Limit: the wiring to the real trial file is not covered by a test.
  7. Launcher counted databases the revert removes (git-release-launcher.ts:233-240). Real.
    • Fix: the additions in the applied record and in interrupted plans are skipped.
    • Test: reverts when the only newer database is one the revert removes.
  8. Fallback additions lost across an interrupted swap (:705-709). Real: the durable plan held only replacements.
    • Fix: the plan carries the additions.
    • Test: records the fallback's additions when its swap is interrupted and resumed. It interrupts the swap's first rename, then resumes.
  9. A wrapped full-disk error aborted the start (state-upgrade-tree.ts:450-459). Real: only the top-level error was inspected.
    • Fix: causes and aggregated errors are walked, for both full disk and the space admission.
    • Test: skips the image when a copy layer wraps a full disk.

Two extra changes, found while writing the state machine:

  • A leftover image of a finished run was deleted before its replacement existed. It is now replaced only by rename.
  • The inventory was not fsynced before the interrupted records were removed. It now is.

Rating round on fa77fc2f102 (this PR's own round): verdicts

That round rated F / F / F with nine findings. Fixed failing-first on 2ab365b0946, each red against fa77fc2f102:

  1. (P1) A refusal or revert dropped Doctor's imported legacy sources (cron jobs.json archived as .migrated). Real. The fix is described under the next round's item 3, which replaced this round's first attempt (renaming .migrated archives back, which missed other owners' archive names).
  2. (P1) First hop with a skipped image. Real; fixed as in item 6 above.
  3. (P1) Doctor's exemption was directory-wide. Real.
    • Fix: Doctor keeps its normal backup set when a pending store lies outside the start's discovery.
    • Test: copies only when Doctor owns the image (…, outside the start's discovery=true).
    • Not changed: the launcher still cannot see an agent database configured outside the state directory. The earlier launcher and the copy-and-swap upgrade had the same gap.
  4. (P1) An image was read without the WAL preserved beside it. Real.
    • Fix: the pair is read together in a private copy.
    • Test: reads a restored image together with the WAL preserved beside it.
  5. (P1) Config symlink handling. Real.
    • Fix: a linked config is neither imaged nor written through, and the launcher does not require its image.
    • Test: images a config privately, and never writes through a linked one (linked: true), using a read-only link target.
  6. (P1) Resume trusted a leftover same-build image. Real.
    • Fix: the inventory records the images the run published; resume keeps only those.
    • Test: resumes only with images the interrupted run published, never a leftover.
  7. (P2) An unreadable inventory was treated as empty. Real.
    • Fix: an unreadable record, plan or agent listing keeps the service forward.
    • Test: stays forward when an upgrade record cannot be read.
  8. (P2) A created database's companions were left behind. Real.
    • Fix: the launcher removes them with the database; the dead companion filter is gone.
    • Test: the WAL assertion in reverts when the only newer database is one the revert removes.
  9. (P2) Test-line budget. Real.
    • Shared test helpers were consolidated.
    • The remaining growth is one test per state-machine row and per launcher rule, recorded in config/test-lines-allocations/201716-in-place-state-upgrade.txt with that reason.

Rating round on 2ab365b0946 (this PR's own round): verdicts

That round rated F / F / F with six findings. Each fix below fails on 2ab365b0946 and passes on this head:

  1. (P1) An interrupted refusal restore consumed images. Real.
    • Fix: a durable restore.json is written first, and the resume scan finishes it before anything else.
    • Test: finishes a refusal's restore that a stop interrupted before anything else, which stops at the second image rename.
  2. (P1) Configured agent stores outside the state directory were outside the launcher's view. Real.
    • Fix: Doctor, as the start's chain, ends the Git release trial before migrating such a store, and keeps its normal backup set.
    • Test: settleRunningGitReleaseTrial is asserted in copies only when Doctor owns the image (…, outside=true).
  3. (P1) Archive names differ by owner (.migrated-<stamp>-<id> for auth profiles). Real.
    • Fix: instead of mirroring each owner's archive naming, the start compares its inventory. A file that existed before Doctor and is gone after is a moved legacy source; it blocks the refusal restore and is recorded as a remove op that blocks every revert. An interrupted run's inventory is read the same way by the launcher.
    • Tests: keeps the state migrated when Doctor moved a legacy source…, stays forward when Doctor moved a legacy source… (applied record / interrupted inventory).
  4. (P2) Stores created before the applied record were missed. Real.
    • Fix: the launcher treats .sqlite files absent from an interrupted run's inventory as additions, and a refusal restore removes the run's created databases.
    • Test: removes a store an interrupted in-place run created when it reverts.
  5. (P1) Directory entries not synced. Real.
    • Fix: the state directory is fsynced after the record is created, and the config's directory after its image.
    • No test; this is a power-loss property.
  6. (P3) Docs overstated the guarantees. Real. The update guide now states Doctor's remaining backups, the complete-set refusal rule, the revert conditions and which launcher governs the first hop.

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 run boot

  • Setup: 37 SIGKILLs on the 2026.10.10 release corpus (state v22, agents v27). The corpus holds about 180,000 transcript rows and an updater update_runs row written before the restart.
  • Kill points:
    • fixed times from 1.25 s to 44 s;
    • 0, 5 and 20 ms after the first image;
    • when the WAL grows and at 30 KB;
    • 0 and 50 ms after the applied record.
  • Checks after every kill:
    1. integrity_check is ok.
    2. user_version equals schema_meta and is exactly the old or the new version.
    3. Every pre-existing witness row is unchanged.
    4. A migrated database equals the uninterrupted run.
  • Each surviving image is intact at the old version. The rerun serves and equals the uninterrupted run.
  • Result on this head: rerun pending on this head (37 of 37 passed on d533da100e2).

Fallback kill sweep (new)

  • Setup: the same corpus. The start's upgrade runs with the real Doctor chain, then an injected ChainStepError, so the generic rebuild runs (fallback-driver.mts calls upgradeStateDirectory with createDoctorChain and throws after Doctor).
  • Kill points:
    • 0 and 50 ms after the first image;
    • 8 to 36 s inside Doctor;
    • 0 to 4 s into the fallback build;
    • 0, 5 and 40 ms after plan.json;
    • 0 and 30 ms after the applied record.
  • Checks: the same checks after the kill. Then the real gateway start with no fault must finish, serve, reach v40/v43, and keep every witness row.
  • An uninterrupted fallback run ends in mode: fallback, at v40/v43, with the images at v22/v27, and serves.
  • Result: 16 of 16 passed on 9061cf9fc6f; rerun pending on this head.

Real updater into this build (macOS launchd Git source checkout install, release mode)

update_runs rows the updater wrote just before the restart survive:

  • the in-place path (sweep witness, unit test);
  • the fallback (unit tests keeps the update run … (fallback) and keeps rows Doctor committed …, and the fallback sweep witness).

Not proven or not changed

  • Doctor's repair-specific backups. The credential cutover image for state below v29 and the legacy cron and session repairs still take their own scoped images. Routing them through the same owner decision is a follow-up.
  • First-hop revert with a skipped image (see "Update behavior").
  • Boot time limit. The 30-minute chain timeout is unchanged. In-place boot is about 50 s for about 230 MB of databases here; 4 GiB was not measured.
  • Platforms. PostgreSQL, Windows, and Linux filesystems without clones were not run. Their byte-copy-or-skip path is covered by unit tests.
  • Review tooling. autoreview does not run on this machine; an independent reviewer agent and ClawSweeper rating rounds reviewed the diff instead.

@clawsweeper

clawsweeper Bot commented Nov 19, 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.

@fuller-stack-dev

Copy link
Copy Markdown
Member Author

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 3b0b7e23f65: refuses, the copy needs 86.4 GB with 31.7 GB free.

pr2-red.mp4

GREEN, head 41ca0dfc663 (same code as the PR head; later commits are main merges): upgrades in place with clone images and serves.

pr2-green.mp4

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation commands Command implementations size: XL labels Nov 19, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head 3679fd381dfb9fcaadcc26680277e07f87a6ce22, but the PR head is now 2f6e22286ef44fcf2ceeac66d356c83bbccff873. Its old verdict and PR readiness labels are no longer current.

Next step
Comment @clawsweeper re-review when the current head is ready; pushes after the first review are not reviewed automatically.

Review history (1 earlier review cycle)
  • reviewed 2026-11-19T08:31:29.729Z sha 3679fd3 :: blocked before merge. :: [P1] Validate the schema of the image selected for rollback | [P1] Keep post-migration WAL out of the earlier pre-image family | [P1] Retain the resume marker when configuration migration is unfinished | [P2] Include WITHOUT ROWID tables in preservation digests

…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.
@fuller-stack-dev
fuller-stack-dev marked this pull request as draft November 19, 2026 10:25
…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.
@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label Nov 19, 2026
@clawsweeper clawsweeper Bot removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 21, 2026
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

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.

obviyus added a commit that referenced this pull request Nov 25, 2026
## 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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 26, 2026
…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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 26, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes commands Command implementations docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant