Skip to content

fix: check update database safety before stopping the Gateway - #204752

Merged
obviyus merged 12 commits into
mainfrom
update-state-boundary
Nov 24, 2026
Merged

obviyus merged 12 commits into
mainfrom
update-state-boundary

Conversation

@obviyus

@obviyus obviyus commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Release validation and state migration walked different database inventories. Registered external stores could escape rollback coverage, while a healthy closed WAL database without SHM could fail check-release.

Closes #204394. Closes #204227.
Related: #204775, #204502, #204095, #204127.

User Impact

User impact: release preparation checks the databases the migration owner actually knows about, before stopping the serving Gateway. Unsupported recovery paths are refused with the affected database and a next step. Healthy closed WAL databases use the existing artifact-preserving inspection fallback.

No update is refused by database size. The SQLite/PostgreSQL budget refusal, its rate constant and its size-admission tests/docs have been removed per the approved state-model decision. Ordinary non-trial starts remain unrestricted by size.

Newly refused users are those with a pending schema migration and a registered/configured database outside the state directory, deeper than the frozen launcher's four-directory limit, symlinked/separately mounted, or below its skipped git-install/npm/node_modules/tmp/logs directories. Their old Gateway stays serving. The reason names the database and says to move it to a real covered directory (for agents: agents//agent/openclaw-agent.sqlite), update its registration/configuration, and retry. This recovery-layout refusal remains until the separately sequenced restore-manifest cutover; it does not apply when no schema migration is pending. Missing unconfigured retained registrations do not block an unrelated update.

Why This Change Was Made

discoverDatabases owns the inventory, metadata projection and copy eligibility. check-release no longer has a second scanner or direct readonly_shm opener. The copier consumes the authoritative target paths and retains its copy-coverage assertion. The obsolete success-notice recorder and the in-place PostgreSQL trial notice path are removed.

This PR intentionally does not add a manifest writer, CoW/in-place migration model, reader-floor logic or Doctor-chain rewrite. The manifest writer follows as its own small PR; the larger state-model cutover is separate.

Evidence

  • Pinned base d4c6c46e32ae: initial owner/release-check regressions produced12 intended failures and4 passes. AWS base proof.

Real-route proof on merged head5f8ce752

Both legs were rerun after the run.ts conflict resolution, on separate AWS leases using product-installed native services and the qualification kit's TLS/registry fixture preserving the exact public latest URL. No package-spec override or app-state injection.

  • Genuine published stable2026.11.7 → merged head: run, exit0, product 520d08a2-52a0-4999-a9ae-d3fda7d098f6, api/succeeded. Exact-head serving build verified (fixture package2026.11.9-first-hop.0). State36→41 and dormant agent38→43; the cleanly closed WAL-mode agent had no SHM before candidate inspection and was accepted. Wall227.986s, sampled outage94.229s.
  • Merged head → same-head schema42 successor: run, exit0. External agent store refused before stop: product 80cdfd2d-1350-44ed-a0f2-245ca1ac490d, release-check-failed. PID25851/schema41 unchanged; all278 readiness samples healthy (250ms interval). Validation took1.620s after staging. The actual Settings→Updates page and update status --json showed the affected path, move/update-registration/retry instructions, and “The current version is still running.”

Private receipts: StateBoundary-proof/{mergedwal-result.json,mergedwal-receipt.tgz,merged-proof.tgz,merged-complete.tgz,merged-settings.txt,merged-settings.webp}. These boundary legs are not a one-minute-outage or crash-rollback qualification.

Production tokei on the PR's six production TypeScript files after merging main336e9314: 2,540 → 2,557 (+17), excluding tests/support/harness.

Review repair: ordinary PostgreSQL startup

Review-repair head: cbe972b00e5e32cd0585713b032c53d773be7acb. A local-review finding caught protected-copy CREATE admission accidentally applying outside a release trial. PostgreSQL protected-copy targets and prerequisites now apply only to pending/trial starts; manual package upgrades retain the existing in-place migration owner, original namespace and ordinary startup availability.

The existing owner table covers restricted-role ordinary startup versus protected-trial preflight refusal before mutation. Merged-head AWS owner/build check passed 118 tests including large-postgres, gateway-trial and prepare-failure; three live-PG cases were skipped without a conformance connection. Full build and pack passed. The restricted-role case models the copy prerequisite at the upgrade boundary; it is not new live-PG serving proof. Existing protected-copy live-PG fixtures explicitly declare a pending trial.

Main integration

Current head: 5f8ce7521eec58f2c98bf39f250922ecef3f967f, merging main336e9314. Conflicts were only docs/install/updating.md and src/update/run.ts. The update owner retained main's under-lock trial admission and single failure settlement, and C's obsolete success-reason recorder stays deleted. Documentation retains both main's early-recovery contract and C's shared inventory/no-size policy.

AWS PostgreSQL schema regeneration completed with a zero-byte diff. Its first wrapper failed only downloading an obsolete artifact path; the generator completed successfully and the correct empty patch/log were collected with the passing owner/build run. Both affected real-route legs passed on this merged head, as recorded above.

Class C caller-only integration for StateBoundary.
Delete competing schema/registry inspection and trial-time in-place migration notice.
Requires the matching preflightStateUpgrade inventory return contract; integration owner runs validation with that implementation.
Class C follow-on caller integration for StateBoundary.
Remove the second shared-state snapshot and metadata read; consume the inventory owner result.
Extend the existing artifact-preservation regression to clean WAL stores without SHM. Validation belongs to the complete Class C branch.
- Refuse uncovered or over-budget migration inventories before stopping the serving Gateway.
- Reuse artifact-preserving inspection and the same inventory for metadata, copy scope, and trial admission.
- Preserve ordinary non-trial migration-on-open and remove trial-time in-place PostgreSQL notices.
- Keep the copy coverage assertion while removing its obsolete requiredSqlite option.
- Pass the authoritative discovered targets without building a second inventory.
- Apply private artifact-preserving reads only in release preflight; ordinary boot reuses bounded read-only inspection.
- Ignore missing unconfigured registrations while preserving configured bootstrap targets and unresolved journals.
- Use the complete real-row Doctor throughput without subtracting startup time.
- Keep reserved-name lookup static, avoid parameter mutation, and disambiguate the upgrade refusal.
- Preserve explicit branch blocks in the WAL regression.
Class C caller follow-on: the unified inventory removed the only external listStateDatabases reader.
LSP reports only its declaration and internal disk-space caller; preserve that function and caller. No local tests run.
@clawsweeper

clawsweeper Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Nov 24, 2026
- The copier only needs paths; remove its erased dependency on the database inventory module.
- Break the Madge type-edge cycle without changing emitted runtime behavior.
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 24, 2026
@clawsweeper

clawsweeper Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR unifies database inventory and refuses unsafe schema-changing release updates before stopping the serving Gateway.

Example: An update needs a schema migration and includes a 7 GiB PostgreSQL store.

  • Before: The copy estimate exceeds ten minutes, so the trial proceeds with in-place migration without automatic data rollback.
  • After: Preparation refuses the update while the old Gateway continues serving and links to the manual migration procedure.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The source design is coherent and no actionable introduced bug was found, but required runtime and existing-state upgrade qualification remain incomplete.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A failed update can leave agent data changed outside rollback coverage, while healthy closed WAL databases can prevent update preparation.
Reason: Both failures have concrete evidence, and the maintainer-author explicitly accepts the narrower automatic-update admission policy.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this maintainer-authored PR addresses current update-safety defects, and source review found no discrete introduced bug.

Priority: P1
Reviewed head: 64cda098850e3e36df994671c0e95c71d119d87f

Before merge

  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Complete the repository-required shipped update qualification, including closed-WAL CLI acceptance, unsafe-store refusal with the old Gateway still serving, schema-changing recovery with original data intact, and latest-stable upgrade coverage across the documented service/container lanes; redact credentials and non-public endpoints.
Agent review details

How this fits together

The release checker passes configuration and database facts to the startup-upgrade inventory, which determines whether the candidate can migrate private copies recoverable by the resident launcher.

flowchart TD
  A[Update request] --> B[Candidate release checker]
  B --> C[State database inventory]
  C --> D[Recovery and budget admission]
  D --> E[Refuse while old Gateway serves]
  D --> F[Private startup migration]
  F --> G[Launcher commit or rollback]
Loading

Technical review

Best possible solution:

Use the existing inventory to admit only recoverable release trials while preserving ordinary non-trial migration.

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

Current-main discovery and rollback boundaries establish the external-store failure path, and the linked WAL report supplies a stock-CLI reproduction; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The smallest complete repair belongs in the existing discovery owner: inventory every migration target, share exclusions with copying, reject uncovered trials, and reuse artifact-preserving reads; the diff follows that design without adding another recovery mechanism.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 2ec310e264ab.

Provenance checked

  • Startup copy-and-swap and recovery generations keeps the original intent (ef930eb: Migrate private copies, preserve originals, and recover interrupted publication instead of modifying live databases in place.)
  • Bounded copy scope and large ancillary SQLite exclusion changes intended behavior with a stated reason (618bf31: Avoid copying unrelated bulk state and retain ownership-bounded publication and pruning; this PR keeps ancillary exclusions but requires inventoried agent stores because Doctor may repair them.)
  • Release-check database scanner keeps the original intent (be5f7fa: Check candidate compatibility offline without migrating live state; unified artifact-preserving inventory retains that purpose and fixes incomplete-WAL-family handling.)
  • Over-budget PostgreSQL in-place trial fallback changes intended behavior with a stated reason (c7b132a: Keep large-store updates available without copy-only prerequisites; this PR explicitly chooses pre-stop refusal and documented offline maintenance to preserve trial recovery guarantees.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 6747b1e adds src/state/state-upgrade.ts:75 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6747b1ec5ae3; files: src/state/state-upgrade.ts)
  • Peter Steinberger: Raw commit 618bf31 adds src/state/state-upgrade-tree.ts:158 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 618bf31e4e84; files: src/state/state-upgrade-tree.ts)

PR surface

Source +21, Tests +250, Docs +40. Total +311 across 14 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 6 253 232 +21
Tests 6 287 37 +250
Docs 2 69 29 +40
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 609 298 +311

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P1: The PR addresses unsafe failed-update recovery and a reported update rejection involving a healthy WAL database.
  • add merge-risk: 🚨 compatibility: Schema-changing automatic updates intentionally stop accepting uncovered layouts and over-budget stores; the maintainer-authored body explicitly accepts this change.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.

Label justifications:

  • P1: The PR addresses unsafe failed-update recovery and a reported update rejection involving a healthy WAL database.
  • merge-risk: 🚨 compatibility: Schema-changing automatic updates intentionally stop accepting uncovered layouts and over-budget stores; the maintainer-authored body explicitly accepts this change.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 24, 2026, 11:46 AM ET / 16:46 UTC.

- Keep the single inventory and release scanner removal without refusing updates by size.
- Read clean absent/empty-WAL metadata through the existing immutable read-only inspection owner.
- Preserve safe private fallback for nonempty WAL families without SHM.
- Preserve the already-tested inventory/WAL behavior while dropping size admission.
- Keep bounded-reader and manifest work out of this scope-reduction push.
@obviyus obviyus changed the title fix: refuse unsafe database updates before stopping the Gateway fix: check update database safety before stopping the Gateway Nov 24, 2026
- Keep ordinary PostgreSQL starts on the existing in-place migration owner without copy-only CREATE privileges.
- Exercise restricted-role admission versus ordinary startup and mark protected-copy fixtures as trials.
# Conflicts:
#	docs/install/updating.md
#	src/update/run.ts
@obviyus
obviyus merged commit 270aae3 into main Nov 24, 2026
130 checks passed
@obviyus
obviyus deleted the update-state-boundary branch November 24, 2026 19:43
@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Landed.

  • Problem: the update decided which databases to protect in several places, so some stores the new version migrates were not in the protected set, and PostgreSQL had a second in-place path for large stores. A cleanly closed SQLite database without a shared-memory file also failed the release check ([Bug]: update check-release rejects a cleanly closed WAL-mode agent database when its SHM file is absent #204227).
  • Fix: one inventory decides what the update migrates and protects. A store the rollback cannot restore (outside the state directory, too deep, or behind a symlink) is refused in the release check, before the old Gateway stops, with the reason in Settings and update status. No store is refused for its size. A closed WAL database without a shared-memory file is accepted. Outside a trial, a normal start migrates as before.
  • Proof: published 2026.11.7 → this head on Linux completed with a closed WAL database; this head → a schema-step successor refused an external store while the old Gateway kept serving (same PID, all readiness samples healthy). Owner tests and the full build passed.

tideclaw-bot pushed a commit that referenced this pull request Nov 25, 2026
Release validation and state migration walked different database inventories. Registered external stores could escape rollback coverage, while a healthy closed WAL database without SHM could fail `check-release`.

Closes #204394. Closes #204227.
Related: #204775, #204502, #204095, #204127.

User impact: release preparation checks the databases the migration owner actually knows about, before stopping the serving Gateway. Unsupported recovery paths are refused with the affected database and a next step. Healthy closed WAL databases use the existing artifact-preserving inspection fallback.

**No update is refused by database size.** The SQLite/PostgreSQL budget refusal, its rate constant and its size-admission tests/docs have been removed per the approved state-model decision. Ordinary non-trial starts remain unrestricted by size.

Newly refused users are those with a pending schema migration and a registered/configured database outside the state directory, deeper than the frozen launcher's four-directory limit, symlinked/separately mounted, or below its skipped git-install/npm/node_modules/tmp/logs directories. Their old Gateway stays serving. The reason names the database and says to move it to a real covered directory (for agents: agents/<agent-id>/agent/openclaw-agent.sqlite), update its registration/configuration, and retry. This recovery-layout refusal remains until the separately sequenced restore-manifest cutover; it does not apply when no schema migration is pending. Missing unconfigured retained registrations do not block an unrelated update.

`discoverDatabases` owns the inventory, metadata projection and copy eligibility. `check-release` no longer has a second scanner or direct `readonly_shm` opener. The copier consumes the authoritative target paths and retains its copy-coverage assertion. The obsolete success-notice recorder and the in-place PostgreSQL trial notice path are removed.

This PR intentionally does not add a manifest writer, CoW/in-place migration model, reader-floor logic or Doctor-chain rewrite. The manifest writer follows as its own small PR; the larger state-model cutover is separate.

- Pinned base `d4c6c46e32ae`: initial owner/release-check regressions produced12 intended failures and4 passes. [AWS base proof](https://crabbox.openclaw.ai/portal/runs/run_9a0a8afeaa9a1af9caa2385e34602eac).

Both legs were rerun after the `run.ts` conflict resolution, on separate AWS leases using product-installed native services and the qualification kit's TLS/registry fixture preserving the exact public latest URL. No package-spec override or app-state injection.

- **Genuine published stable2026.11.7 → merged head:** [run](https://crabbox.openclaw.ai/portal/runs/run_846f96823734c8f716089e1b2ce03148), exit0, product `520d08a2-52a0-4999-a9ae-d3fda7d098f6`, `api/succeeded`. Exact-head serving build verified (fixture package2026.11.9-first-hop.0). State36→41 and dormant agent38→43; the cleanly closed WAL-mode agent had no SHM before candidate inspection and was accepted. Wall227.986s, sampled outage94.229s.
- **Merged head → same-head schema42 successor:** [run](https://crabbox.openclaw.ai/portal/runs/run_47605dc74641c05448ec970d6e8fdf12), exit0. External agent store refused before stop: product `80cdfd2d-1350-44ed-a0f2-245ca1ac490d`, `release-check-failed`. PID25851/schema41 unchanged; all278 readiness samples healthy (250ms interval). Validation took1.620s after staging. The actual Settings→Updates page and `update status --json` showed the affected path, move/update-registration/retry instructions, and “The current version is still running.”

Private receipts: `StateBoundary-proof/{mergedwal-result.json,mergedwal-receipt.tgz,merged-proof.tgz,merged-complete.tgz,merged-settings.txt,merged-settings.webp}`. These boundary legs are not a one-minute-outage or crash-rollback qualification.

Production `tokei` on the PR's six production TypeScript files after merging main336e9314: **2,540 → 2,557 (+17)**, excluding tests/support/harness.

Review-repair head: `cbe972b00e5e32cd0585713b032c53d773be7acb`. A local-review finding caught protected-copy CREATE admission accidentally applying outside a release trial. PostgreSQL protected-copy targets and prerequisites now apply only to pending/trial starts; manual package upgrades retain the existing in-place migration owner, original namespace and ordinary startup availability.

The existing owner table covers restricted-role ordinary startup versus protected-trial preflight refusal before mutation. [Merged-head AWS owner/build check](https://crabbox.openclaw.ai/portal/runs/run_93771e93ed0d283deb95854a692042ea) passed **118 tests** including large-postgres, gateway-trial and prepare-failure; three live-PG cases were skipped without a conformance connection. Full build and pack passed. The restricted-role case models the copy prerequisite at the upgrade boundary; it is not new live-PG serving proof. Existing protected-copy live-PG fixtures explicitly declare a pending trial.

Current head: `5f8ce7521eec58f2c98bf39f250922ecef3f967f`, merging main336e9314. Conflicts were only `docs/install/updating.md` and `src/update/run.ts`. The update owner retained main's under-lock trial admission and single failure settlement, and C's obsolete success-reason recorder stays deleted. Documentation retains both main's early-recovery contract and C's shared inventory/no-size policy.

AWS PostgreSQL schema regeneration completed with a zero-byte diff. Its first wrapper failed only downloading an obsolete artifact path; the generator completed successfully and the correct empty patch/log were collected with the passing owner/build run. Both affected real-route legs passed on this merged head, as recorded above.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 270aae3)

Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 25, 2026
…aw#204752)

## What Problem This Solves

Release validation and state migration walked different database inventories. Registered external stores could escape rollback coverage, while a healthy closed WAL database without SHM could fail `check-release`.

Closes openclaw#204394. Closes openclaw#204227.
Related: openclaw#204775, openclaw#204502, openclaw#204095, openclaw#204127.

## User Impact

User impact: release preparation checks the databases the migration owner actually knows about, before stopping the serving Gateway. Unsupported recovery paths are refused with the affected database and a next step. Healthy closed WAL databases use the existing artifact-preserving inspection fallback.

**No update is refused by database size.** The SQLite/PostgreSQL budget refusal, its rate constant and its size-admission tests/docs have been removed per the approved state-model decision. Ordinary non-trial starts remain unrestricted by size.

Newly refused users are those with a pending schema migration and a registered/configured database outside the state directory, deeper than the frozen launcher's four-directory limit, symlinked/separately mounted, or below its skipped git-install/npm/node_modules/tmp/logs directories. Their old Gateway stays serving. The reason names the database and says to move it to a real covered directory (for agents: agents/<agent-id>/agent/openclaw-agent.sqlite), update its registration/configuration, and retry. This recovery-layout refusal remains until the separately sequenced restore-manifest cutover; it does not apply when no schema migration is pending. Missing unconfigured retained registrations do not block an unrelated update.

## Why This Change Was Made

`discoverDatabases` owns the inventory, metadata projection and copy eligibility. `check-release` no longer has a second scanner or direct `readonly_shm` opener. The copier consumes the authoritative target paths and retains its copy-coverage assertion. The obsolete success-notice recorder and the in-place PostgreSQL trial notice path are removed.

This PR intentionally does not add a manifest writer, CoW/in-place migration model, reader-floor logic or Doctor-chain rewrite. The manifest writer follows as its own small PR; the larger state-model cutover is separate.

## Evidence

- Pinned base `ad98b9e7f734`: initial owner/release-check regressions produced12 intended failures and4 passes. [AWS base proof](https://crabbox.openclaw.ai/portal/runs/run_9a0a8afeaa9a1af9caa2385e34602eac).

## Real-route proof on merged head5f8ce752

Both legs were rerun after the `run.ts` conflict resolution, on separate AWS leases using product-installed native services and the qualification kit's TLS/registry fixture preserving the exact public latest URL. No package-spec override or app-state injection.

- **Genuine published stable2026.11.7 → merged head:** [run](https://crabbox.openclaw.ai/portal/runs/run_846f96823734c8f716089e1b2ce03148), exit0, product `520d08a2-52a0-4999-a9ae-d3fda7d098f6`, `api/succeeded`. Exact-head serving build verified (fixture package2026.11.9-first-hop.0). State36→41 and dormant agent38→43; the cleanly closed WAL-mode agent had no SHM before candidate inspection and was accepted. Wall227.986s, sampled outage94.229s.
- **Merged head → same-head schema42 successor:** [run](https://crabbox.openclaw.ai/portal/runs/run_47605dc74641c05448ec970d6e8fdf12), exit0. External agent store refused before stop: product `80cdfd2d-1350-44ed-a0f2-245ca1ac490d`, `release-check-failed`. PID25851/schema41 unchanged; all278 readiness samples healthy (250ms interval). Validation took1.620s after staging. The actual Settings→Updates page and `update status --json` showed the affected path, move/update-registration/retry instructions, and “The current version is still running.”

Private receipts: `StateBoundary-proof/{mergedwal-result.json,mergedwal-receipt.tgz,merged-proof.tgz,merged-complete.tgz,merged-settings.txt,merged-settings.webp}`. These boundary legs are not a one-minute-outage or crash-rollback qualification.

Production `tokei` on the PR's six production TypeScript files after merging main336e9314: **2,540 → 2,557 (+17)**, excluding tests/support/harness.

## Review repair: ordinary PostgreSQL startup

Review-repair head: `cbe972b00e5e32cd0585713b032c53d773be7acb`. A local-review finding caught protected-copy CREATE admission accidentally applying outside a release trial. PostgreSQL protected-copy targets and prerequisites now apply only to pending/trial starts; manual package upgrades retain the existing in-place migration owner, original namespace and ordinary startup availability.

The existing owner table covers restricted-role ordinary startup versus protected-trial preflight refusal before mutation. [Merged-head AWS owner/build check](https://crabbox.openclaw.ai/portal/runs/run_93771e93ed0d283deb95854a692042ea) passed **118 tests** including large-postgres, gateway-trial and prepare-failure; three live-PG cases were skipped without a conformance connection. Full build and pack passed. The restricted-role case models the copy prerequisite at the upgrade boundary; it is not new live-PG serving proof. Existing protected-copy live-PG fixtures explicitly declare a pending trial.

## Main integration

Current head: `5f8ce7521eec58f2c98bf39f250922ecef3f967f`, merging main336e9314. Conflicts were only `docs/install/updating.md` and `src/update/run.ts`. The update owner retained main's under-lock trial admission and single failure settlement, and C's obsolete success-reason recorder stays deleted. Documentation retains both main's early-recovery contract and C's shared inventory/no-size policy.

AWS PostgreSQL schema regeneration completed with a zero-byte diff. Its first wrapper failed only downloading an obsolete artifact path; the generator completed successfully and the correct empty patch/log were collected with the passing owner/build run. Both affected real-route legs passed on this merged head, as recorded above.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 25, 2026
## What Problem This Solves

The launcher currently guesses restore coverage by scanning `.pre-<generation>` files. That freezes directory depth, excluded names and ctime policy into the installed launcher. This is the candidate-writer stage of replacing that knowledge with explicit restore intent (related #204394, #204752, #204775, #198389 and #204095).

## User Impact

The active candidate writes `<prefix>/releases/<target-release-id>/.restore` as `{v:1,runId,files:[{live,preimage}]}` before publishing its replayable swap plan or canonical schema/config changes. The trial's existing target release owns the receipt by construction; run IDs are recorded, not compared. Paths are absolute; null pre-images explicitly remove new files and SQLite WAL/SHM/journal/seal companions.

Under exclusive custody, SQLite originals are checkpointed and closed, then their complete main files are hard-linked as adjacent run-bound images. Publication renames a different prepared inode over the live path; it does not modify the image. Normal adjacent images add no database byte copy. The fallback copies bytes only if the filesystem rejects hard linking, recording its cause. No new size admission or disk-copy reservation is added.

Retries within that prepared release reuse immutable images; another release cannot reuse its receipt, including a retry prepared by old2026.11.15 code. A changed or missing restore plan refuses instead of re-imaging mutated state. Known no-upgrade trials record an empty plan under the same exclusive owner. Ordinary non-trial starts are unchanged. Cleanup consumes only the manifest captured by its own candidate process after confirmed committed IPC, never rereading a slot or matching IDs.

## Scope and Compatibility

Legacy `.pre-<generation>` files and `Trial.config` remain in use: today's launcher continues to work and ignores the new manifest. This PR does not enable external stores yet, change the launcher reader, add reader floors, or start in-place migrations. A hard-linked image is valid for this rename-based swap only; the later in-place cutover must use its approved clone/copy pre-image primitive.

The state owner is the only manifest/image writer. UpdateOwner supplied both revisions of the committed-IPC cleanup caller; no `src/update/` file was edited directly here. Receipts stay with their prepared releases. Old retained-image cleanup errors cannot block a different release's no-upgrade preparation; the A-delayed/B-safe regression remains and also deletes A's receipt before invoking its captured cleanup.

## Evidence

On `8b410b54`, isolated AWS checks passed **88 owner tests**; baseline5e5ecba4 failed exactly the two selected missing-manifest/order regressions. The JSON gate positively verified those causes, not an arbitrary exit. A recovered OOM-interrupted broad run was not claimed green. On `cb5abca7`, **35 changed-owner tests**, assertion safety, SQLite worker/dialect guards, core types and targeted production lint passed on32GiB. Targeted test lint found a shadowing fixture variable, now renamed through LSP. CI's Bun lane exposed an orderly `process.exit(0)` WAL fixture; it now uses a real forced crash and retains the physical WAL/data assertions. This review repair also removes stale-run comparisons by per-release scope and captured cleanup. No manual proof on the new scope has run while the required predecessor PRs are pending.

One-worker AWS wall times at8b410b54: writer63.535s, startup63.798s, swap-owner73.935s. The first writer suite included51.888s compiled-worker preparation; the native filesystem/WAL assertions themselves are small. Current-head CI owns its fresh check results.

The real filesystem WAL/config fixtures asserted hard links with zero byte copies; the forced `EXDEV` fixture exercised one actual copy fallback. No genuine cross-device failure was observed. Adjacent images normally share their source's filesystem; individually mounted files or unsupported hard linking can require the fallback. This is not a population-frequency estimate.

**Must not land before #204868 (custody), then #204866 (install owner).** Per the lead's sequence, merge main once after both land, then run the native crash/full-package qualification on that integrated head. No further manual writer proof will run before that point. The hard-link immutability assumption requires custody; checkpointing alone is not claimed to fix the previously observed malformed rollback. The in-place/floor stage separately waits for ReaderFloor.

## Size

`tokei` on all four touched production files, including the update caller, against integrated main25efa334: **1,058 → 1,388 (+330)**. Tests: **+479 net lines**, with a 79-line excess allocation for distinct WAL, durable-ordering, retry, frozen rollback, symlink, captured cleanup and startup contracts. No competing legacy reader is deleted in this explicitly sequenced writer-first stage; its removal belongs to the following reader PR.

## Conflict Integration

Merged main25efa334 once to clear the named conflict. Resolutions retained main's config/include inventory and external/workspace/missing-include fixtures together with the managed-trial manifest case. No `src/update/` conflict or direct edit was involved. No manual proof was run. The later main merge and native crash qualification still wait for the predecessor landing order above.

Co-authored-by: Ayaan Zaidi <[email protected]>
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
## What Problem This Solves

The launcher currently guesses restore coverage by scanning `.pre-<generation>` files. That freezes directory depth, excluded names and ctime policy into the installed launcher. This is the candidate-writer stage of replacing that knowledge with explicit restore intent (related openclaw#204394, openclaw#204752, openclaw#204775, openclaw#198389 and openclaw#204095).

## User Impact

The active candidate writes `<prefix>/releases/<target-release-id>/.restore` as `{v:1,runId,files:[{live,preimage}]}` before publishing its replayable swap plan or canonical schema/config changes. The trial's existing target release owns the receipt by construction; run IDs are recorded, not compared. Paths are absolute; null pre-images explicitly remove new files and SQLite WAL/SHM/journal/seal companions.

Under exclusive custody, SQLite originals are checkpointed and closed, then their complete main files are hard-linked as adjacent run-bound images. Publication renames a different prepared inode over the live path; it does not modify the image. Normal adjacent images add no database byte copy. The fallback copies bytes only if the filesystem rejects hard linking, recording its cause. No new size admission or disk-copy reservation is added.

Retries within that prepared release reuse immutable images; another release cannot reuse its receipt, including a retry prepared by old2026.11.15 code. A changed or missing restore plan refuses instead of re-imaging mutated state. Known no-upgrade trials record an empty plan under the same exclusive owner. Ordinary non-trial starts are unchanged. Cleanup consumes only the manifest captured by its own candidate process after confirmed committed IPC, never rereading a slot or matching IDs.

## Scope and Compatibility

Legacy `.pre-<generation>` files and `Trial.config` remain in use: today's launcher continues to work and ignores the new manifest. This PR does not enable external stores yet, change the launcher reader, add reader floors, or start in-place migrations. A hard-linked image is valid for this rename-based swap only; the later in-place cutover must use its approved clone/copy pre-image primitive.

The state owner is the only manifest/image writer. UpdateOwner supplied both revisions of the committed-IPC cleanup caller; no `src/update/` file was edited directly here. Receipts stay with their prepared releases. Old retained-image cleanup errors cannot block a different release's no-upgrade preparation; the A-delayed/B-safe regression remains and also deletes A's receipt before invoking its captured cleanup.

## Evidence

On `8b410b54`, isolated AWS checks passed **88 owner tests**; baseline5e5ecba4 failed exactly the two selected missing-manifest/order regressions. The JSON gate positively verified those causes, not an arbitrary exit. A recovered OOM-interrupted broad run was not claimed green. On `cb5abca7`, **35 changed-owner tests**, assertion safety, SQLite worker/dialect guards, core types and targeted production lint passed on32GiB. Targeted test lint found a shadowing fixture variable, now renamed through LSP. CI's Bun lane exposed an orderly `process.exit(0)` WAL fixture; it now uses a real forced crash and retains the physical WAL/data assertions. This review repair also removes stale-run comparisons by per-release scope and captured cleanup. No manual proof on the new scope has run while the required predecessor PRs are pending.

One-worker AWS wall times at8b410b54: writer63.535s, startup63.798s, swap-owner73.935s. The first writer suite included51.888s compiled-worker preparation; the native filesystem/WAL assertions themselves are small. Current-head CI owns its fresh check results.

The real filesystem WAL/config fixtures asserted hard links with zero byte copies; the forced `EXDEV` fixture exercised one actual copy fallback. No genuine cross-device failure was observed. Adjacent images normally share their source's filesystem; individually mounted files or unsupported hard linking can require the fallback. This is not a population-frequency estimate.

**Must not land before openclaw#204868 (custody), then openclaw#204866 (install owner).** Per the lead's sequence, merge main once after both land, then run the native crash/full-package qualification on that integrated head. No further manual writer proof will run before that point. The hard-link immutability assumption requires custody; checkpointing alone is not claimed to fix the previously observed malformed rollback. The in-place/floor stage separately waits for ReaderFloor.

## Size

`tokei` on all four touched production files, including the update caller, against integrated main25efa334: **1,058 → 1,388 (+330)**. Tests: **+479 net lines**, with a 79-line excess allocation for distinct WAL, durable-ordering, retry, frozen rollback, symlink, captured cleanup and startup contracts. No competing legacy reader is deleted in this explicitly sequenced writer-first stage; its removal belongs to the following reader PR.

## Conflict Integration

Merged main25efa334 once to clear the named conflict. Resolutions retained main's config/include inventory and external/workspace/missing-include fixtures together with the managed-trial manifest case. No `src/update/` conflict or direct edit was involved. No manual proof was run. The later main merge and native crash qualification still wait for the predecessor landing order above.

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
## What Problem This Solves

The launcher currently guesses restore coverage by scanning `.pre-<generation>` files. That freezes directory depth, excluded names and ctime policy into the installed launcher. This is the candidate-writer stage of replacing that knowledge with explicit restore intent (related #204394, #204752, #204775, #198389 and #204095).

## User Impact

The active candidate writes `<prefix>/releases/<target-release-id>/.restore` as `{v:1,runId,files:[{live,preimage}]}` before publishing its replayable swap plan or canonical schema/config changes. The trial's existing target release owns the receipt by construction; run IDs are recorded, not compared. Paths are absolute; null pre-images explicitly remove new files and SQLite WAL/SHM/journal/seal companions.

Under exclusive custody, SQLite originals are checkpointed and closed, then their complete main files are hard-linked as adjacent run-bound images. Publication renames a different prepared inode over the live path; it does not modify the image. Normal adjacent images add no database byte copy. The fallback copies bytes only if the filesystem rejects hard linking, recording its cause. No new size admission or disk-copy reservation is added.

Retries within that prepared release reuse immutable images; another release cannot reuse its receipt, including a retry prepared by old2026.11.15 code. A changed or missing restore plan refuses instead of re-imaging mutated state. Known no-upgrade trials record an empty plan under the same exclusive owner. Ordinary non-trial starts are unchanged. Cleanup consumes only the manifest captured by its own candidate process after confirmed committed IPC, never rereading a slot or matching IDs.

## Scope and Compatibility

Legacy `.pre-<generation>` files and `Trial.config` remain in use: today's launcher continues to work and ignores the new manifest. This PR does not enable external stores yet, change the launcher reader, add reader floors, or start in-place migrations. A hard-linked image is valid for this rename-based swap only; the later in-place cutover must use its approved clone/copy pre-image primitive.

The state owner is the only manifest/image writer. UpdateOwner supplied both revisions of the committed-IPC cleanup caller; no `src/update/` file was edited directly here. Receipts stay with their prepared releases. Old retained-image cleanup errors cannot block a different release's no-upgrade preparation; the A-delayed/B-safe regression remains and also deletes A's receipt before invoking its captured cleanup.

## Evidence

On `8b410b54`, isolated AWS checks passed **88 owner tests**; baseline5e5ecba4 failed exactly the two selected missing-manifest/order regressions. The JSON gate positively verified those causes, not an arbitrary exit. A recovered OOM-interrupted broad run was not claimed green. On `cb5abca7`, **35 changed-owner tests**, assertion safety, SQLite worker/dialect guards, core types and targeted production lint passed on32GiB. Targeted test lint found a shadowing fixture variable, now renamed through LSP. CI's Bun lane exposed an orderly `process.exit(0)` WAL fixture; it now uses a real forced crash and retains the physical WAL/data assertions. This review repair also removes stale-run comparisons by per-release scope and captured cleanup. No manual proof on the new scope has run while the required predecessor PRs are pending.

One-worker AWS wall times at8b410b54: writer63.535s, startup63.798s, swap-owner73.935s. The first writer suite included51.888s compiled-worker preparation; the native filesystem/WAL assertions themselves are small. Current-head CI owns its fresh check results.

The real filesystem WAL/config fixtures asserted hard links with zero byte copies; the forced `EXDEV` fixture exercised one actual copy fallback. No genuine cross-device failure was observed. Adjacent images normally share their source's filesystem; individually mounted files or unsupported hard linking can require the fallback. This is not a population-frequency estimate.

**Must not land before #204868 (custody), then #204866 (install owner).** Per the lead's sequence, merge main once after both land, then run the native crash/full-package qualification on that integrated head. No further manual writer proof will run before that point. The hard-link immutability assumption requires custody; checkpointing alone is not claimed to fix the previously observed malformed rollback. The in-place/floor stage separately waits for ReaderFloor.

## Size

`tokei` on all four touched production files, including the update caller, against integrated main25efa334: **1,058 → 1,388 (+330)**. Tests: **+479 net lines**, with a 79-line excess allocation for distinct WAL, durable-ordering, retry, frozen rollback, symlink, captured cleanup and startup contracts. No competing legacy reader is deleted in this explicitly sequenced writer-first stage; its removal belongs to the following reader PR.

## Conflict Integration

Merged main25efa334 once to clear the named conflict. Resolutions retained main's config/include inventory and external/workspace/missing-include fixtures together with the managed-trial manifest case. No `src/update/` conflict or direct edit was involved. No manual proof was run. The later main merge and native crash qualification still wait for the predecessor landing order above.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 31c4e6b)

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[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

docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L

Projects

None yet

1 participant