Skip to content

fix(update): keep the Gateway available after failed PostgreSQL updates - #204502

Merged
obviyus merged 21 commits into
mainfrom
fix/postgres-protected-trial
Nov 24, 2026
Merged

obviyus merged 21 commits into
mainfrom
fix/postgres-protected-trial

Conversation

@obviyus

@obviyus obviyus commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #204363

What Problem This Solves

A PostgreSQL update can migrate its data and then crash. Restoring the previous package alone leaves that package unable to read the newer schema, so no Gateway serves.

User Impact

Protected release trials migrate private server-side copies and publish their anchors only after validation. Failed trials select the original data with the previous release. SQLite agent databases under PostgreSQL shared state are protected in the same private pass.

The restart is longer. Plan for both server copies, indexes, WAL, temporary work and retained generations. Namespace names change on schema-changing updates; namespace-bound reporting, dump and grant-management scripts must use the current anchor. Source access grants and schema-local defaults are carried and verified, including grant options and column permissions.

Why This Change Was Made

This extends the existing startup copy-and-swap owner, exact server carrier and durable file plan. It removes the PostgreSQL-anchor version-zero exclusion and its mixed-engine skip. It adds no application schema/version change, trial format, launcher SQL, public flag, timeout or retry loop. There is no portable-export or unprotected in-place fallback for protected stores.

The first verified server copy is the migration destination, not a frozen capture followed by a second restore. A separate frozen-export manifest would misdescribe a namespace that is about to migrate, so retention uses the existing preserved anchors, store UUID and exact role ownership. Normal frozen captures retain their isolation.

Shared state uses that server carrier too. The older backup owner withheld it because credential rollback needed exported shared-state rows; c2 instead retains those rows in the untouched original namespace, selected by the preserved anchor. That removes the need for a portable shared-state export in the protected trial without removing ordinary captures for uncovered stores.

Compatibility and inventory source notes

The physical PostgreSQL version is read in state-upgrade-databases.ts:83–92. Its independent family-version filter replaces the old shared-state version-zero early return, so SQLite agents are not skipped when state uses PostgreSQL. Genuine fresh SQLite version-zero catalogs remain bootstrap-owned.

v2026.8.1-beta.1 and beta.2 wrote absolute registry paths. Schema 9 in #124728 rewrites eligible in-tree rows to relative paths (migration lines 269–278); beta.3 and stable include it, and PostgreSQL starts at schema 24. No new reader rebase or row rewriting is needed.

Result Wording

  • Preparation runs while the previous Gateway serves; a missing CREATE grant names the exact administrator SQL before stopping it.
  • Candidate boot logs: “Preparing a protected PostgreSQL copy for OpenClaw … The previous data will stay available for recovery.”
  • A healthy candidate keeps the normal update-success message.
  • A recovered failed trial keeps the shared serving-version result and retry/report next action. Current versions also show the already-recorded exit-78 startup cause detail, including the server-space remedy.
  • Namespace cleanup failure keeps the recovery pair and logs a warning; it never fails a serving release.
  • Larger stores keep the existing in-place migration path, with this recorded notice: “This PostgreSQL store (X GiB) is too large to copy within the update window. It is migrated in place, without automatic data rollback. Back it up first: https://docs.openclaw.ai/install/updating#rollback”.

Evidence

Product qualification and final-head CI are complete: 89 checks passed, none failed or pending. Actual rollback and pre-stop privilege-refusal screenshots and corrected space-remedy and successful in-place screenshots are attached. The corrected normal CLI update exits 0; it supersedes the recorded pre-fix helper timeout. Every AWS lease was released with --wait, and task tunnels were stopped.

Final head: 5bbf3e6712d04546a8a8d639188976be606c7ef5. CI attempt 2 and the CI gate passed. One Doctor process-custody cleanup test failed on the first attempt; its single authorized same-head retry passed. No cleanup guard, assertion or product timeout was weakened.

  • Complete AWS qualification archive builds and package checks passed: pristine reporter41 plus next42 and post-migration-crash42 fixtures from ad7e628030. run_9f2fdf8a02d2aad39a29f67029739435, exit 0. The large-mode fixture also built from 513b774d28 (run_b92c7c5b1893ded6f4b4c02bbe3e8058, exit 0). Schema 42 and the lowered large-mode threshold are disposable qualification overlays, not shipped schema or policy changes.

  • PostgreSQL 16 focused owner run run_0a734ee4124db7308ba39734795af613: 7/7 pass on ad7e6280300163cf55c97987ca36229427a6e236. Includes a non-superuser runtime owner, real reader and column-only roles, grant options, default grants for later tables, unchanged originals, both historical v39 layouts, mixed engines, frozen-launcher file recovery and owned namespace pruning.

  • The new startup regression is red on base 0956e14e6814: three intended assertion failures (PG-shared cases return current; configured-agent case falls back), not import/setup failures. run_f03e6807f052b8bee5d12ce55a5a1bd9.

  • Reader access is red on pre-ACL 997e3bd583: actual PostgreSQL 42501 permission denied for schema after source-owner checks, cloning and physical validation. run_374698ce02d32a9c790a68028b747f1c.

  • The same deterministic 100-session/10,752-message/42 MiB prose recipe measured 22.030 s for one direct state+agent copy (7.831 s state, 14.181 s agent), versus 44.9 s for the earlier server capture+restore. This is prior-head primitive evidence at 4a2ac42861; physical sizes were 109,199,360 B and 109,256,704 B, respectively. It excludes migration and Gateway readiness and is not a fleet-percentile claim.

  • Implementation-head actual 1 GiB copy (ad7e628030): 91.312 s summed API calls (state 6.295 s, agent 85.018 s); 94.903 s enclosing interval includes receipt/bookkeeping. Fixture: 1,000 sessions, 114,688 messages, 448 MiB prose, 1,074,192,384 physical bytes. Actual in-clone ANALYZE was 8.923 ms / 924.153 ms; COMMIT→statistics COMMIT 15 ms / 929 ms, with no statement-cap hit. Same AWS c7a.8xlarge/32 CPUs/PG16.15 loopback environment. run_ea0ba8f4997497d5471b2514409ac2c1. Copy interval alone uses 7.91% of the existing budget; migration and readiness are not included.

  • Implementation-head static quality (ad7e628030): core and test typechecks, lint, format parity, line-cap, SQL-worker/dialect and import-cycle guards passed. That earlier check:changed run reported an unchanged UI dead export; the UI file and the main-only plugin-npm-prepared-release-retained-producer.test.ts ratchet finding were left unchanged. run_a6eca5556aa261ea23377fa7ef465043. Final CI above is green.

  • Additional AWS owner checks run_5bfc8d62fbe03884f89f1e074d773274, exit 0: real PostgreSQL mixed-engine migration/rollback/prune including a retained JSON configuration file (3/3), measured size-mode selection (2/2), core typecheck and database-worker ratchet (166→166 live SQL calls). The earlier bounded update/report/Doctor/startup set passed 102 tests before static checks found the explicit-return and duplicate-query issues now corrected; its obsolete static continuation was stopped.

  • Corrected reporter/candidate full builds passed on 056e58a1f6 (run_1600dd89588952b226d0c9a1c1464616, including 83 report/startup-progress owner tests) and 816d247a8e (run_1806f6db08bd5a5b96115f85fc7371c0).

  • Real PG16 terminal-row regression: with the metadata guard removed, the live-custody test receives undefined instead of its terminal record; fixed code passes. run_d6d5571a1f215a87f5595a2d208c00c7, exit 0. The test overlay SHA-256 9e183ef1082b9919f31565434c84e98bd9f36efdae23ae3eebcf1029ada42a1e matches the committed test.

  • Historical BLOB corpus: 40910f1112 (before the trace change) and f5b0f14e05 fail on the premature Uint8Array path; main 87f5739fbc passes (comparison run). The corrected eea155e5d7 full runtime build and corpus case pass, including all original database .pre- hashes: run_036ade5c82663f841278cda6d372825b, exit 0.

Linux / PostgreSQL 16 live outcomes

Times are measured HTTP unavailability, with the sampled upper bound in parentheses—not total package-install time.

Case / update run Observed result Unavailable seconds
Healthy 3216f87a New namespace, schema 42, unchanged selected table counts; custom reader and default grants still work 93.443 (93.945)
Crash after private migration 8f78b578 Original namespace/schema 41 and old T serve; Control UI and rollback status reachable 109.198 (109.700)
Missing CREATE 06cfa933 Refuses before stop with exact grant; old boot ID unchanged No unavailable samples
Real space refusal 124b69ae PG 53100 from a 64 MiB tablespace against a >100 MiB source; exit 78, schema-41 reporter serves; Settings and CLI name the space problem and remedy 26.559 (27.063)
During server copy Backend transaction aborts after one interruption; retry succeeds 102.281 (102.785)
After private anchor, before live publication c2462582 One interruption; retry succeeds 105.403 (105.906)
Corrected large-store CLI 26687f74 Exit 0, same namespace 41→42, real migration witness; notice in CLI, status and Settings 20.602 (21.106)

The corrected large-store run is run_f6ff27e1f1f6dbf9ee1c96dfbd330585, exit 0. A qualification-only lowered threshold selects that branch on a small store; production policy is unchanged.

Cleanup was proved by byte-identical replay of the existing durable plan, not a claim that the earlier ad7 retry pruned successfully. Namespace inventory 32→30: only failed state restore_ea858c2cbd3241ee9273fb6fee420cdd and agent restore_b5af9a52198b4d87b57fcc3d8f755721 were dropped. Live restore_a8c51d96f8d34ebd8fba8966297a85b3 / restore_b3ce0081721947ef946c5abf222f6d21 and originals pgcrash_state_4f1e55aebce84abd / pgcrash_agent_889dbaaff3c64c0d stayed intact. No manual DROP or invented plan operations were used.

Cleanup observation: run_d5c7866cee8a21eb5dd5e79f78ce1a64.

Plugin maintenance still reports the existing engine-selection warning in these fixtures; core success is not relabelled or hidden. The recorded space cause retains a descriptor warning and generic triage wording alongside the visible free-space remedy.

Large-store Decision and Named Limits

  • Final decision: preparation reads the physical sizes of the namespaces that would be copied. At the measured simplification of 90 s/GiB, an estimate of at most 600 s selects c2, leaving half of the existing 20-minute deadline for a retry. Above it, the existing in-place path remains available, without copy-only privilege requirements. Blocking updates would be worse than main for these users. This constant replaces a per-server rate estimate and should be revisited when actual larger-store rates are measured; there is no new user flag, configuration, timer or persisted field.
  • A crash before a durable plan discards the private shadow and copies again on the second start. Both starts share that deadline; a large-store retry can expire safely and return to the old version. After publication, the next start sees the target version and reuses the selected namespace.
  • Post-COMMIT, at most ~10 s of planner statistics run before the private anchor is recorded. A crash there can leave one unreferenced namespace requiring manual cleanup. The COMMIT→statistics call precedes the private anchor write. The bound is the existing postgres-planner-statistics.ts:16 statement timeout, not a new timer. No new marker was added.
  • Deep, external and symlinked paths outside the installed launcher's recoverable inventory keep their ordinary Doctor captures but do not gain automatic data rollback here (#204394).
  • A serving T that predates the generic exit-78 report projection still has its old first-hop message. Preparation-time permission refusal keeps its named reason; newer serving versions show recorded boot-refusal detail.
  • An older preparer also does not persist the candidate's new informational size notice from a successful check. Candidate boot logs the in-place selection, but the large-store CLI/status notice proof starts an updated schema-41 reporter. This first-hop limitation does not change the older updater's baseline in-place behavior.
  • Trial-only writes are discarded on rollback. A PostgreSQL outage is not repaired by restoring anchors; readiness, not a file-level rolled-back label, confirms recovery.
  • Already-stranded installations without a preserved original namespace still require a compatible build or a verified matched backup. Never lower schema markers or drop uncertain namespaces to force startup.

Final-head Scope and Test Budget

ad7e628030..056e58a1f6 adds physical-size selection and the existing persisted diagnostic notice for the large in-place branch. Below the threshold, the protected copy/migration path is unchanged. Live qualification found retained JSON configuration files reaching the PostgreSQL anchor reader during pruning; the final head filters that existing list once, covered by the real rollback/prune test. Actual disk-space refusal also exposed two diagnostic issues: the report preferred a truncated prefix over the full recorded stderr tail, and normal startup progress printed completion lines after a failed start. The final head uses the existing bounded tail and emits completion only for successful startup phases, leaving the refusal last; CLI finalization is unchanged. Other changes reuse the schema owner's typed content-version reader, make undefined preflight success explicit, compute retention once, correct the docs, and remove 136 redundant wiring-test lines. Mode selection, corrected cleanup and final cause visibility require their own final-source live proof; ad7 live runs do not prove those changes.

Final head 5bbf3e6712 has the 816d247a8e package runtime plus the SQLite-only legacy-safe discovery correction proved by the BLOB corpus. Remaining changes are the verified test overlay, a test-local rename/import correction, allocation notes and documentation. No PostgreSQL runtime change is excluded from the final 816 package proof.

The CLI failure was a physical-read mismatch, not an uncompleted notice: a real PostgreSQL run was finished/succeeded, but update.runs.get read the SQLite anchor and returned run:null, so the existing follower timed out. The shortcut predates this PR (1a74a80617cf, #191332). The earlier PostgreSQL trial used Settings to start updates and openclaw update status to inspect them; it did not exercise foreground CLI following. The fix changes the reader owner, not polling, deadlines or the public protocol.

For historical BLOB registry paths, the existing preflight reader leaves non-string rows to Doctor. Both main and ops databases in the corpus are independently discovered at agents/<id>/agent/openclaw-agent.sqlite; the existing corpus test hashes every original database and checks its .pre- original (test/state-upgrade.e2e.test.ts:189,247–248). Non-default legacy BLOB registrations that fall outside that discovery remain a named #204394 limitation, not a new coercion or refusal.

Remaining test allocation (approved after those cuts):

  • Real PostgreSQL ACL/non-superuser tests preserve reader access, ownership, grant options and historical layouts.
  • Mixed-engine migration failure and crash recovery prove originals survive and only owned unreferenced namespaces are pruned.
  • Copy-refusal tests prove preparation fails before stop with an actionable cause.
  • Generic report projection and one nested startup-progress regression (tracing off/on) prove recorded boot-refusal remedies remain the final visible cause.
  • One parameterized size-routing test proves under/over selection, the notice and retained SQLite protection.
  • One real PostgreSQL terminal-read regression exercises the physical command path used by the CLI follower, rather than the SQLite anchor.

Production delta against the base: +1192/−234, net +958 lines across 27 files. The growth covers physical-engine inventory/validation, transactional access-right preservation, paired namespace retention, measured mode selection and refusal-output ordering. Existing duplicate private PostgreSQL capture work is removed; standalone and uncovered-store captures remain.

- Clone PostgreSQL namespaces before private startup migrations and publish validated anchors.
- Retain owned namespace generations for file-only rollback and cleanup.
- Refuse unprotected preparation and show recorded startup refusal details.
- Derive private coverage from existing root and anchor identity facts.
- Leave deep and external stores on their existing Doctor capture path.
- Carry namespace, table, column, sequence and schema-default ACLs inside the existing copy transaction.
- Verify normalized ownership, grantors and grant options before commit.
- Preserve frozen capture isolation and admit historical source layouts before adding the ACL hook.
- Let strict aclexplode treat absent column grants as empty instead of constructing a zero-dimensional ACL array.
…mission

- Ignore empty column ACLs, not engine-private transport metadata shape.
- Keep explicit column grants mandatory and cover canonical engine seal columns.
- Include the exact three-line LSP rename from the reported no-shadow diagnostic.
@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 commands Command implementations size: XL labels Nov 24, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug 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 migrates private PostgreSQL copies and preserves anchors so failed release trials can select the original databases.

Example: A PostgreSQL release trial migrates schema 41 to 42, then crashes.

  • Before: The previous release restarts against schema 42 and cannot serve.
  • After: The launcher restores anchors selecting the unchanged schema-41 namespaces.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful recovery design with meaningful carrier coverage, but an existing-config startup regression, a diff-caused guard failure, and incomplete serving-path qualification prevent a pass.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A failed PostgreSQL update can restore the previous package while leaving its databases unreadable, so no Gateway serves.
Reason: The maintainer-authored direction addresses a demonstrated recovery failure using existing owners; its explicitly open large-store tradeoff remains separate.

Merge readiness

⛔ Blocked before merge - 4 items remain

This PR addresses a current PostgreSQL rollback gap, but its new inventory can prevent valid existing configurations from starting.

Priority: P1
Reviewed head: ad7e6280300163cf55c97987ca36229427a6e236
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Is mandatory PostgreSQL copying within the existing 20-minute trial budget acceptable for large supported installations?
  • Recommendation: Accept bounded rollback behavior: Retain the existing deadline and explicitly accept that oversized trials can return safely to the previous release without completing the update.
  • Why: The author explicitly leaves this decision open; the reported 1 GiB primitive measurement excludes migration and readiness and does not establish completion on the largest supported stores.

Before merge

  • Resolve inline environment substitutions before inspecting PostgreSQL (P1) - readUpgradeConfig only parses JSON5 and includes, but its result now supplies the PostgreSQL connection during isStateUpgradePending. With PGHOST=db.example and database.postgres.connection="postgresql://openclaw@${PGHOST}/openclaw", the secret resolver treats the whole DSN as a literal and the database client receives ${PGHOST} unchanged. This inspection runs even when the physical schema is current, so an otherwise valid existing Gateway fails before normal config resolution. Reuse the canonical read-resolution operation with the selected environment before connecting.
  • Carry the SQL ownership classification with the extracted reader (P2) - The extracted readVersion still executes db.prepare, but scripts/check-kysely-guardrails.mts classifies the previous state-upgrade.ts owner and does not classify this new module. Its raw-SQL rule therefore rejects this introduced call, matching the exact-head architecture job's Kysely failure. Move the justified ownership classification with the extraction or use the existing typed query owner; do not bypass the guard by renaming the receiver.
  • Resolve merge risk - The feature owner must accept mandatory server-copy costs within the unchanged 20-minute trial budget, or defer rollout for large stores.
  • 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

  • [P1] Resolve inline environment substitutions before inspecting PostgreSQL — src/state/state-upgrade-databases.ts:176-178
  • [P2] Carry the SQL ownership classification with the extracted reader — src/state/state-upgrade-databases.ts:37-40

Tests

  • Missing end-to-end proof: Complete the required update-contract platform lanes through Gateway update.run, including a real schema migration followed by a crash, previous-release readiness, preserved data, and a latest-stable upgrade.
Agent review details

How this fits together

Gateway startup inventories state and agent stores, prepares private migration inputs, validates them, and publishes anchors through the existing durable file-swap plan.

flowchart TD
A[Prepared release] --> B[Startup inventory]
B --> C[Private PostgreSQL copies]
C --> D[Doctor migrations and validation]
D --> E[Durable anchor swap]
E --> F[Gateway readiness]
E --> G[Failed trial restores original anchors]
Loading

Technical review

Best possible solution:

Keep copy-and-swap as the upgrade owner, reuse canonical config resolution, and establish that failed PostgreSQL trials restore a serving previous release.

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

Current-main source supports the reported migration-then-crash failure because launcher recovery restores files without reversing PostgreSQL migrations; no target code was executed during this review.

Is this the best way to solve the issue?

Extending startup copy-and-swap with the existing PostgreSQL carrier addresses the owning invariant without adding launcher SQL, but startup must consume canonically resolved configuration.

Full review comments:

  • [P1] Resolve inline environment substitutions before inspecting PostgreSQL — src/state/state-upgrade-databases.ts:176-178
    readUpgradeConfig only parses JSON5 and includes, but its result now supplies the PostgreSQL connection during isStateUpgradePending. With PGHOST=db.example and database.postgres.connection="postgresql://openclaw@${PGHOST}/openclaw", the secret resolver treats the whole DSN as a literal and the database client receives ${PGHOST} unchanged. This inspection runs even when the physical schema is current, so an otherwise valid existing Gateway fails before normal config resolution. Reuse the canonical read-resolution operation with the selected environment before connecting.
    Confidence: 0.98
  • [P2] Carry the SQL ownership classification with the extracted reader — src/state/state-upgrade-databases.ts:37-40
    The extracted readVersion still executes db.prepare, but scripts/check-kysely-guardrails.mts classifies the previous state-upgrade.ts owner and does not classify this new module. Its raw-SQL rule therefore rejects this introduced call, matching the exact-head architecture job's Kysely failure. Move the justified ownership classification with the extraction or use the existing typed query owner; do not bypass the guard by renaming the receiver.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Accept the existing trial budget (recommended)
    The feature owner explicitly accepts failed large-store trials returning to the old serving release under the unchanged deadline.
  2. Pause for a large-store approach
    Defer merging until the owner resolves the stated large-store limitation.

Provenance checked

  • PostgreSQL exclusion from startup copy-and-swap changes intended behavior with a stated reason (ef930eb: Version-zero anchors and the lack of a SQLite diagnostics home previously made shadow startup upgrades unsafe for PostgreSQL shared state.)
  • Frozen PostgreSQL captures keeps the original intent (2ff4256: Frozen server captures avoided portable exports while retaining repeatable restore and cleanup custody; the PR preserves that path and separately uses a writable clone for migration.)
  • Owned generation pruning keeps the original intent (618bf31: Pruning was bounded to generations beside published owned files to avoid deleting unrelated state; the extension retains that inventory and adds matched namespace retirement.)
  • Release-trial PostgreSQL rollback limitation changes intended behavior with a stated reason (689d524: Release trials explicitly accepted file-only recovery without PostgreSQL data rollback; this PR explains why private copies make anchor-only rollback possible.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit ef930eb adds src/state/state-upgrade.ts:273 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ef930ebbad77; files: src/state/state-upgrade.ts)
  • Peter Steinberger: Raw commit 618bf31 adds src/state/state-upgrade-tree.ts:605 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 +892, Tests +859, Docs +188. Total +1939 across 35 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 24 1100 208 +892
Tests 6 873 14 +859
Docs 5 269 81 +188
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 35 2242 303 +1939

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.

Review metrics

Metric Value Why it matters
Production versus test changes Production +1100/−208; tests +873/−14 Growth primarily covers physical-engine inventory, exact ACL preservation, and paired namespace retention; those responsibilities belong to the existing upgrade and backup owners.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #204363
Summary: This PR is the candidate repair for PostgreSQL trial rollback; external-store recovery remains separately tracked.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P1: The underlying failed-update outage is concrete, and the patch introduces a startup failure for existing PostgreSQL configurations using inline environment substitutions.
  • add merge-risk: 🚨 compatibility: Existing inline-substitution DSNs can stop working before normal Gateway bootstrap.
  • add merge-risk: 🚨 availability: Mandatory server copying extends restart downtime and shares the existing trial deadline with migration and readiness; large-store acceptance remains explicitly unresolved.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P1: The underlying failed-update outage is concrete, and the patch introduces a startup failure for existing PostgreSQL configurations using inline environment substitutions.
  • merge-risk: 🚨 compatibility: Existing inline-substitution DSNs can stop working before normal Gateway bootstrap.
  • merge-risk: 🚨 availability: Mandatory server copying extends restart downtime and shares the existing trial deadline with migration and readiness; large-store acceptance remains explicitly unresolved.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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, 3:47 AM ET / 08:47 UTC.

- Select protected PostgreSQL copies only when the measured estimate leaves room for a retry; retain baseline in-place migration and persist its backup notice otherwise.
- Preserve typed SQLite reads, compute generation retention once, and remove redundant wiring tests.
- Only SQLite anchors can protect PostgreSQL namespaces; retained configuration files must not enter the physical anchor reader.
- Extend the existing real PostgreSQL rollback/prune proof with a retained JSON configuration file.
- Keep the existing undefined success result explicit on every path so native SDK declaration compilation accepts the new optional notice.
- Remove the duplicate typed query from upgrade discovery and use the existing schema-admission row reader.
- Keep the existing 500-character report bound while taking the end of the recorded tail, where the process prints its fatal cause and remedy.
- Cover debug output followed by the PostgreSQL disk-space remedy in the existing generic projection regression.
- Prefer the full recorded stderr tail over its truncated detail preview.
- Emit completed startup progress only after successful work, preserving the final refusal and remedy without changing CLI exit finalization.
- Exercise nested bootstrap/dispatch refusal with tracing disabled and enabled.
@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label Nov 24, 2026
@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Observed PostgreSQL 16 qualification lanes: failed post-migration trial restores the previous serving Gateway; missing CREATE privilege refuses during preparation with the exact grant. These screenshots do not claim completion of the still-pending final space-diagnostic and cleanup lanes.

Settings after automatic rollback to the previous serving Gateway

Settings shows the preparation refusal and exact PostgreSQL CREATE grant

- Rename the nested prune fixture local; no runtime or assertion changes.
- Exclude PostgreSQL from the SQLite clean-close metadata shortcut; an anchor is not the application catalog.
- Exercise a terminal PostgreSQL update record through reconciliation admission after native readers close.
- Reuse the registry owner preflight target reader so historical BLOB paths remain migration-owned instead of reaching path resolution before migration.
- Default in-tree agent discovery still protects both agent databases in the existing historical BLOB corpus.
- Correct the new physical-read regression import; the production PostgreSQL guard is unchanged.
- Retain an actual Gateway file owner after closing native readers so the regression reaches the SQLite metadata shortcut that hid terminal PostgreSQL rows.
- Use the production native process-birth reader in the real file-custody fixture so the ownership precondition is verified, not unknown.
…dance

- Qualify copy-only rollback and namespace-rotation guarantees in the recovery, CLI and engine reference pages.
- Link larger stores to the existing in-place policy and its explicit no-data-rollback warning.
@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Completed PostgreSQL 16 qualification: real server disk exhaustion (53100) rolls back to the serving schema-41 reporter and shows the free-space remedy in Settings and update status. The large-store branch was exercised with a qualification-only lowered threshold: normal CLI update exits 0, the same namespace migrates 41→42, and Settings records the no-automatic-data-rollback notice. The plugin-maintenance warning remains visible; core update success is not hidden or relabelled.

Settings shows the real PostgreSQL disk-space refusal, remedy and previous serving version

Settings shows successful in-place update and explicit no-automatic-data-rollback notice

@obviyus
obviyus merged commit c7b132a into main Nov 24, 2026
266 of 268 checks passed
@obviyus
obviyus deleted the fix/postgres-protected-trial branch November 24, 2026 11:56
@obviyus

obviyus commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Landed.

  • Problem: on PostgreSQL, an update whose new version crashed after migrating the schema left no Gateway running. The launcher restored the old release's files, but the schema stayed migrated, so the old release refused to start (update: on PostgreSQL, a crash after migration leaves no Gateway running #204363).
  • Fix: on its first start, the new version copies the PostgreSQL state into a private namespace on the server, migrates only the copy, checks it (rows, ownership and access rights), and only then switches to it. A failed trial switches back to the untouched original, so the previous release serves. Missing permissions are refused before the old Gateway stops, with the grant to add. A full disk ends in a rollback that names the space problem. Stores too large to copy within the update window are migrated in place as before, and the update output says so. Copies from failed trials are removed by the normal cleanup.
  • Also fixed: openclaw update on a PostgreSQL install could report "did not finish in time" after a successful update (read shortcut from fix(update): avoid snapshot failures in live recovery checks #191332).
  • Proof: live AWS runs on PostgreSQL 16 for a normal update, crash and rollback, permission and disk-space refusals, crashes during and after the copy, cleanup, a large store, and an old 2026.7.1 state; 1 GiB copy in 91 s.

Known limits, named in the PR: agent databases outside the state directory are not protected (#204394); an older serving release shows the generic retry text instead of the specific cause.

obviyus added a commit that referenced this pull request Nov 24, 2026
## 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-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 `d4c6c46e32ae`: 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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 25, 2026
…es (#204502)

Closes #204363

## What Problem This Solves

A PostgreSQL update can migrate its data and then crash. Restoring the previous package alone leaves that package unable to read the newer schema, so no Gateway serves.

## User Impact

Protected release trials migrate private server-side copies and publish their anchors only after validation. Failed trials select the original data with the previous release. SQLite agent databases under PostgreSQL shared state are protected in the same private pass.

The restart is longer. Plan for both server copies, indexes, WAL, temporary work and retained generations. Namespace names change on schema-changing updates; namespace-bound reporting, dump and grant-management scripts must use the current anchor. Source access grants and schema-local defaults are carried and verified, including grant options and column permissions.

## Why This Change Was Made

This extends the existing startup copy-and-swap owner, exact server carrier and durable file plan. It removes the PostgreSQL-anchor version-zero exclusion and its mixed-engine skip. It adds no application schema/version change, trial format, launcher SQL, public flag, timeout or retry loop. There is no portable-export or unprotected in-place fallback for protected stores.

The first verified server copy is the migration destination, not a frozen capture followed by a second restore. A separate frozen-export manifest would misdescribe a namespace that is about to migrate, so retention uses the existing preserved anchors, store UUID and exact role ownership. Normal frozen captures retain their isolation.

Shared state uses that server carrier too. The older backup owner withheld it because credential rollback needed exported shared-state rows; c2 instead retains those rows in the untouched original namespace, selected by the preserved anchor. That removes the need for a portable shared-state export in the protected trial without removing ordinary captures for uncovered stores.

<details>
<summary>Compatibility and inventory source notes</summary>

The physical PostgreSQL version is read in [`state-upgrade-databases.ts:83–92`](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/state/state-upgrade-databases.ts#L83-L92). Its [independent family-version filter](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/state/state-upgrade-databases.ts#L152-L153) replaces the old shared-state version-zero early return, so SQLite agents are not skipped when state uses PostgreSQL. Genuine fresh SQLite version-zero catalogs remain bootstrap-owned.

`v2026.8.1-beta.1` and `beta.2` wrote absolute registry paths. Schema 9 in [#124728](#124728) rewrites eligible in-tree rows to relative paths ([migration lines 269–278](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/state/openclaw-state-db-schema-repair.ts#L269-L278)); `beta.3` and stable include it, and PostgreSQL starts at schema 24. No new reader rebase or row rewriting is needed.

</details>

## Result Wording

- Preparation runs while the previous Gateway serves; a missing CREATE grant names the exact administrator SQL before stopping it.
- Candidate boot logs: “Preparing a protected PostgreSQL copy for OpenClaw … The previous data will stay available for recovery.”
- A healthy candidate keeps the normal update-success message.
- A recovered failed trial keeps the shared serving-version result and retry/report next action. Current versions also show the already-recorded exit-78 startup cause detail, including the server-space remedy.
- Namespace cleanup failure keeps the recovery pair and logs a warning; it never fails a serving release.
- Larger stores keep the existing in-place migration path, with this recorded notice: “This PostgreSQL store (X GiB) is too large to copy within the update window. It is migrated in place, without automatic data rollback. Back it up first: https://docs.openclaw.ai/install/updating#rollback”.

## Evidence

**Product qualification and final-head CI are complete: 89 checks passed, none failed or pending.** Actual [rollback and pre-stop privilege-refusal screenshots](#204502 (comment)) and [corrected space-remedy and successful in-place screenshots](#204502 (comment)) are attached. The corrected normal CLI update exits **0**; it supersedes the recorded pre-fix helper timeout. Every AWS lease was released with `--wait`, and task tunnels were stopped.

Final head: `5bbf3e6712d04546a8a8d639188976be606c7ef5`. [CI attempt 2](https://github.com/openclaw/openclaw/actions/runs/45379513209/attempts/2) and the [CI gate](https://github.com/openclaw/openclaw/actions/runs/45386761656) passed. One Doctor process-custody cleanup test failed on the first attempt; its [single authorized same-head retry](https://github.com/openclaw/openclaw/actions/runs/45379513209/job/138411642189) passed. No cleanup guard, assertion or product timeout was weakened.

- Complete AWS qualification archive builds and package checks passed: pristine reporter41 plus next42 and post-migration-crash42 fixtures from `ad7e628030`. [run_9f2fdf8a02d2aad39a29f67029739435](https://crabbox.openclaw.ai/portal/runs/run_9f2fdf8a02d2aad39a29f67029739435), exit 0. The large-mode fixture also built from `513b774d28` ([run_b92c7c5b1893ded6f4b4c02bbe3e8058](https://crabbox.openclaw.ai/portal/runs/run_b92c7c5b1893ded6f4b4c02bbe3e8058), exit 0). Schema 42 and the lowered large-mode threshold are disposable qualification overlays, not shipped schema or policy changes.

- PostgreSQL 16 focused owner run [run_0a734ee4124db7308ba39734795af613](https://crabbox.openclaw.ai/portal/runs/run_0a734ee4124db7308ba39734795af613): **7/7 pass** on `ad7e6280300163cf55c97987ca36229427a6e236`. Includes a non-superuser runtime owner, real reader and column-only roles, grant options, default grants for later tables, unchanged originals, both historical v39 layouts, mixed engines, frozen-launcher file recovery and owned namespace pruning.
- The new startup regression is red on base `0956e14e6814`: three intended assertion failures (PG-shared cases return current; configured-agent case falls back), not import/setup failures. [run_f03e6807f052b8bee5d12ce55a5a1bd9](https://crabbox.openclaw.ai/portal/runs/run_f03e6807f052b8bee5d12ce55a5a1bd9).
- Reader access is red on pre-ACL `997e3bd583`: actual PostgreSQL `42501 permission denied for schema` after source-owner checks, cloning and physical validation. [run_374698ce02d32a9c790a68028b747f1c](https://crabbox.openclaw.ai/portal/runs/run_374698ce02d32a9c790a68028b747f1c).
- The same deterministic 100-session/10,752-message/42 MiB prose recipe measured **22.030 s** for one direct state+agent copy (7.831 s state, 14.181 s agent), versus **44.9 s** for the earlier server capture+restore. This is prior-head primitive evidence at `4a2ac42861`; physical sizes were 109,199,360 B and 109,256,704 B, respectively. It excludes migration and Gateway readiness and is not a fleet-percentile claim.
- Implementation-head actual 1 GiB copy (`ad7e628030`): **91.312 s** summed API calls (state 6.295 s, agent 85.018 s); **94.903 s** enclosing interval includes receipt/bookkeeping. Fixture: 1,000 sessions, 114,688 messages, 448 MiB prose, 1,074,192,384 physical bytes. Actual in-clone ANALYZE was **8.923 ms / 924.153 ms**; COMMIT→statistics COMMIT **15 ms / 929 ms**, with no statement-cap hit. Same AWS c7a.8xlarge/32 CPUs/PG16.15 loopback environment. [run_ea0ba8f4997497d5471b2514409ac2c1](https://crabbox.openclaw.ai/portal/runs/run_ea0ba8f4997497d5471b2514409ac2c1). Copy interval alone uses 7.91% of the existing budget; migration and readiness are not included.
- Implementation-head static quality (`ad7e628030`): core and test typechecks, lint, format parity, line-cap, SQL-worker/dialect and import-cycle guards passed. That earlier `check:changed` run reported an unchanged UI dead export; the UI file and the main-only `plugin-npm-prepared-release-retained-producer.test.ts` ratchet finding were left unchanged. [run_a6eca5556aa261ea23377fa7ef465043](https://crabbox.openclaw.ai/portal/runs/run_a6eca5556aa261ea23377fa7ef465043). Final CI above is green.
- Additional AWS owner checks [run_5bfc8d62fbe03884f89f1e074d773274](https://crabbox.openclaw.ai/portal/runs/run_5bfc8d62fbe03884f89f1e074d773274), exit 0: real PostgreSQL mixed-engine migration/rollback/prune including a retained JSON configuration file (**3/3**), measured size-mode selection (**2/2**), core typecheck and database-worker ratchet (**166→166** live SQL calls). The earlier bounded update/report/Doctor/startup set passed **102 tests** before static checks found the explicit-return and duplicate-query issues now corrected; its obsolete static continuation was stopped.
- Corrected reporter/candidate full builds passed on `056e58a1f6` ([run_1600dd89588952b226d0c9a1c1464616](https://crabbox.openclaw.ai/portal/runs/run_1600dd89588952b226d0c9a1c1464616), including **83** report/startup-progress owner tests) and `816d247a8e` ([run_1806f6db08bd5a5b96115f85fc7371c0](https://crabbox.openclaw.ai/portal/runs/run_1806f6db08bd5a5b96115f85fc7371c0)).
- Real PG16 terminal-row regression: with the metadata guard removed, the live-custody test receives `undefined` instead of its terminal record; fixed code passes. [run_d6d5571a1f215a87f5595a2d208c00c7](https://crabbox.openclaw.ai/portal/runs/run_d6d5571a1f215a87f5595a2d208c00c7), exit 0. The test overlay SHA-256 `9e183ef1082b9919f31565434c84e98bd9f36efdae23ae3eebcf1029ada42a1e` matches the committed test.
- Historical BLOB corpus: `40910f1112` (before the trace change) and `f5b0f14e05` fail on the premature `Uint8Array` path; main `87f5739fbc` passes ([comparison run](https://crabbox.openclaw.ai/portal/runs/run_bd406b7313533d912b0cf2724017665e)). The corrected `eea155e5d7` full runtime build and corpus case pass, including **all original database `.pre-` hashes**: [run_036ade5c82663f841278cda6d372825b](https://crabbox.openclaw.ai/portal/runs/run_036ade5c82663f841278cda6d372825b), exit 0.

### Linux / PostgreSQL 16 live outcomes

Times are measured HTTP unavailability, with the sampled upper bound in parentheses—not total package-install time.

| Case / update run | Observed result | Unavailable seconds |
| --- | --- | --- |
| [Healthy `3216f87a`](https://crabbox.openclaw.ai/portal/runs/run_348b18b19173c81569cb78f95c97723b) | New namespace, schema 42, unchanged selected table counts; custom reader and default grants still work | 93.443 (93.945) |
| [Crash after private migration `8f78b578`](https://crabbox.openclaw.ai/portal/runs/run_a61b9c3d4becc39890a1efc1f29939c5) | Original namespace/schema 41 and old T serve; Control UI and rollback status reachable | 109.198 (109.700) |
| [Missing CREATE `06cfa933`](https://crabbox.openclaw.ai/portal/runs/run_a98b7abc71e6338fce59695e96e535c6) | Refuses before stop with exact grant; old boot ID unchanged | No unavailable samples |
| [Real space refusal `124b69ae`](https://crabbox.openclaw.ai/portal/runs/run_6c1b9afbbcdcf7e53cdcb9e3205c2fd3) | PG `53100` from a 64 MiB tablespace against a >100 MiB source; exit 78, schema-41 reporter serves; Settings and CLI name the space problem and remedy | 26.559 (27.063) |
| [During server copy](https://crabbox.openclaw.ai/portal/runs/run_e1068fb7d19e614c83fb4895f8118d84) | Backend transaction aborts after one interruption; retry succeeds | 102.281 (102.785) |
| [After private anchor, before live publication `c2462582`](https://crabbox.openclaw.ai/portal/runs/run_13461405a6ea35983c16ded96c9a2d79) | One interruption; retry succeeds | 105.403 (105.906) |
| [Corrected large-store CLI `26687f74`](https://crabbox.openclaw.ai/portal/runs/run_f6ff27e1f1f6dbf9ee1c96dfbd330585) | **Exit 0**, same namespace 41→42, real migration witness; notice in CLI, status and Settings | 20.602 (21.106) |

The corrected large-store run is [run_f6ff27e1f1f6dbf9ee1c96dfbd330585](https://crabbox.openclaw.ai/portal/runs/run_f6ff27e1f1f6dbf9ee1c96dfbd330585), exit 0. A qualification-only lowered threshold selects that branch on a small store; production policy is unchanged.

Cleanup was proved by **byte-identical replay of the existing durable plan**, not a claim that the earlier ad7 retry pruned successfully. Namespace inventory **32→30**: only failed state `restore_ea858c2cbd3241ee9273fb6fee420cdd` and agent `restore_b5af9a52198b4d87b57fcc3d8f755721` were dropped. Live `restore_a8c51d96f8d34ebd8fba8966297a85b3` / `restore_b3ce0081721947ef946c5abf222f6d21` and originals `pgcrash_state_4f1e55aebce84abd` / `pgcrash_agent_889dbaaff3c64c0d` stayed intact. No manual `DROP` or invented plan operations were used.

Cleanup observation: [run_d5c7866cee8a21eb5dd5e79f78ce1a64](https://crabbox.openclaw.ai/portal/runs/run_d5c7866cee8a21eb5dd5e79f78ce1a64).

Plugin maintenance still reports the existing engine-selection warning in these fixtures; core success is not relabelled or hidden. The recorded space cause retains a descriptor warning and generic triage wording alongside the visible free-space remedy.

## Large-store Decision and Named Limits

- **Final decision:** preparation reads the physical sizes of the namespaces that would be copied. At the measured simplification of **90 s/GiB**, an estimate of **at most 600 s** selects c2, leaving half of the existing 20-minute deadline for a retry. Above it, the existing in-place path remains available, without copy-only privilege requirements. Blocking updates would be worse than main for these users. This constant replaces a per-server rate estimate and should be revisited when actual larger-store rates are measured; there is no new user flag, configuration, timer or persisted field.
- A crash before a durable plan discards the private shadow and copies again on the second start. Both starts share that deadline; a large-store retry can expire safely and return to the old version. After publication, the next start sees the target version and reuses the selected namespace.
- **Post-COMMIT, at most ~10 s of planner statistics run before the private anchor is recorded. A crash there can leave one unreferenced namespace requiring manual cleanup.** The [COMMIT→statistics call](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/infra/database-engine/port.worker.ts#L707-L712) precedes the [private anchor write](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/snapshot/database-backup.operations.ts#L441-L456). The bound is the existing `postgres-planner-statistics.ts:16` statement timeout, not a new timer. No new marker was added.
- Deep, external and symlinked paths outside the installed launcher's recoverable inventory keep their ordinary Doctor captures but do not gain automatic data rollback here ([#204394](#204394)).
- A serving T that predates the generic exit-78 report projection still has its old first-hop message. Preparation-time permission refusal keeps its named reason; newer serving versions show recorded boot-refusal detail.
- An older preparer also does not persist the candidate's new informational size notice from a successful check. Candidate boot logs the in-place selection, but the large-store CLI/status notice proof starts an updated schema-41 reporter. This first-hop limitation does not change the older updater's baseline in-place behavior.
- Trial-only writes are discarded on rollback. A PostgreSQL outage is not repaired by restoring anchors; readiness, not a file-level rolled-back label, confirms recovery.
- Already-stranded installations without a preserved original namespace still require a compatible build or a verified matched backup. Never lower schema markers or drop uncertain namespaces to force startup.

## Final-head Scope and Test Budget

`ad7e628030..056e58a` adds physical-size selection and the existing persisted diagnostic notice for the large in-place branch. Below the threshold, the protected copy/migration path is unchanged. Live qualification found retained JSON configuration files reaching the PostgreSQL anchor reader during pruning; the final head filters that existing list once, covered by the real rollback/prune test. Actual disk-space refusal also exposed two diagnostic issues: the report preferred a truncated prefix over the full recorded stderr tail, and normal startup progress printed completion lines after a failed start. The final head uses the existing bounded tail and emits completion only for successful startup phases, leaving the refusal last; CLI finalization is unchanged. Other changes reuse the schema owner's typed content-version reader, make undefined preflight success explicit, compute retention once, correct the docs, and remove 136 redundant wiring-test lines. Mode selection, corrected cleanup and final cause visibility require their own final-source live proof; ad7 live runs do not prove those changes.

Final head `5bbf3e6712` has the `816d247a8e` package runtime plus the SQLite-only legacy-safe discovery correction proved by the BLOB corpus. Remaining changes are the verified test overlay, a test-local rename/import correction, allocation notes and documentation. No PostgreSQL runtime change is excluded from the final 816 package proof.

The CLI failure was a physical-read mismatch, not an uncompleted notice: a real PostgreSQL run was `finished/succeeded`, but `update.runs.get` read the SQLite anchor and returned `run:null`, so the existing follower timed out. The shortcut predates this PR (`1a74a80617cf`, #191332). The earlier PostgreSQL trial used Settings to start updates and `openclaw update status` to inspect them; it did not exercise foreground CLI following. The fix changes the reader owner, not polling, deadlines or the public protocol.

For historical BLOB registry paths, the existing preflight reader leaves non-string rows to Doctor. Both `main` and `ops` databases in the corpus are independently discovered at `agents/<id>/agent/openclaw-agent.sqlite`; the existing corpus test hashes **every** original database and checks its `.pre-` original (`test/state-upgrade.e2e.test.ts:189,247–248`). Non-default legacy BLOB registrations that fall outside that discovery remain a named #204394 limitation, not a new coercion or refusal.

Remaining test allocation (approved after those cuts):
- Real PostgreSQL ACL/non-superuser tests preserve reader access, ownership, grant options and historical layouts.
- Mixed-engine migration failure and crash recovery prove originals survive and only owned unreferenced namespaces are pruned.
- Copy-refusal tests prove preparation fails before stop with an actionable cause.
- Generic report projection and one nested startup-progress regression (tracing off/on) prove recorded boot-refusal remedies remain the final visible cause.
- One parameterized size-routing test proves under/over selection, the notice and retained SQLite protection.
- One real PostgreSQL terminal-read regression exercises the physical command path used by the CLI follower, rather than the SQLite anchor.

Production delta against the base: **+1192/−234, net +958 lines across 27 files**. The growth covers physical-engine inventory/validation, transactional access-right preservation, paired namespace retention, measured mode selection and refusal-output ordering. Existing duplicate private PostgreSQL capture work is removed; standalone and uncovered-store captures remain.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit c7b132a)
Co-authored-by: RomneyDa <[email protected]>
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
…es (openclaw#204502)

Closes openclaw#204363

## What Problem This Solves

A PostgreSQL update can migrate its data and then crash. Restoring the previous package alone leaves that package unable to read the newer schema, so no Gateway serves.

## User Impact

Protected release trials migrate private server-side copies and publish their anchors only after validation. Failed trials select the original data with the previous release. SQLite agent databases under PostgreSQL shared state are protected in the same private pass.

The restart is longer. Plan for both server copies, indexes, WAL, temporary work and retained generations. Namespace names change on schema-changing updates; namespace-bound reporting, dump and grant-management scripts must use the current anchor. Source access grants and schema-local defaults are carried and verified, including grant options and column permissions.

## Why This Change Was Made

This extends the existing startup copy-and-swap owner, exact server carrier and durable file plan. It removes the PostgreSQL-anchor version-zero exclusion and its mixed-engine skip. It adds no application schema/version change, trial format, launcher SQL, public flag, timeout or retry loop. There is no portable-export or unprotected in-place fallback for protected stores.

The first verified server copy is the migration destination, not a frozen capture followed by a second restore. A separate frozen-export manifest would misdescribe a namespace that is about to migrate, so retention uses the existing preserved anchors, store UUID and exact role ownership. Normal frozen captures retain their isolation.

Shared state uses that server carrier too. The older backup owner withheld it because credential rollback needed exported shared-state rows; c2 instead retains those rows in the untouched original namespace, selected by the preserved anchor. That removes the need for a portable shared-state export in the protected trial without removing ordinary captures for uncovered stores.

<details>
<summary>Compatibility and inventory source notes</summary>

The physical PostgreSQL version is read in [`state-upgrade-databases.ts:83–92`](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/state/state-upgrade-databases.ts#L83-L92). Its [independent family-version filter](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/state/state-upgrade-databases.ts#L152-L153) replaces the old shared-state version-zero early return, so SQLite agents are not skipped when state uses PostgreSQL. Genuine fresh SQLite version-zero catalogs remain bootstrap-owned.

`v2026.8.1-beta.1` and `beta.2` wrote absolute registry paths. Schema 9 in [openclaw#124728](openclaw#124728) rewrites eligible in-tree rows to relative paths ([migration lines 269–278](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/state/openclaw-state-db-schema-repair.ts#L269-L278)); `beta.3` and stable include it, and PostgreSQL starts at schema 24. No new reader rebase or row rewriting is needed.

</details>

## Result Wording

- Preparation runs while the previous Gateway serves; a missing CREATE grant names the exact administrator SQL before stopping it.
- Candidate boot logs: “Preparing a protected PostgreSQL copy for OpenClaw … The previous data will stay available for recovery.”
- A healthy candidate keeps the normal update-success message.
- A recovered failed trial keeps the shared serving-version result and retry/report next action. Current versions also show the already-recorded exit-78 startup cause detail, including the server-space remedy.
- Namespace cleanup failure keeps the recovery pair and logs a warning; it never fails a serving release.
- Larger stores keep the existing in-place migration path, with this recorded notice: “This PostgreSQL store (X GiB) is too large to copy within the update window. It is migrated in place, without automatic data rollback. Back it up first: https://docs.openclaw.ai/install/updating#rollback”.

## Evidence

**Product qualification and final-head CI are complete: 89 checks passed, none failed or pending.** Actual [rollback and pre-stop privilege-refusal screenshots](openclaw#204502 (comment)) and [corrected space-remedy and successful in-place screenshots](openclaw#204502 (comment)) are attached. The corrected normal CLI update exits **0**; it supersedes the recorded pre-fix helper timeout. Every AWS lease was released with `--wait`, and task tunnels were stopped.

Final head: `5bbf3e6712d04546a8a8d639188976be606c7ef5`. [CI attempt 2](https://github.com/openclaw/openclaw/actions/runs/45379513209/attempts/2) and the [CI gate](https://github.com/openclaw/openclaw/actions/runs/45386761656) passed. One Doctor process-custody cleanup test failed on the first attempt; its [single authorized same-head retry](https://github.com/openclaw/openclaw/actions/runs/45379513209/job/138411642189) passed. No cleanup guard, assertion or product timeout was weakened.

- Complete AWS qualification archive builds and package checks passed: pristine reporter41 plus next42 and post-migration-crash42 fixtures from `ad7e628030`. [run_9f2fdf8a02d2aad39a29f67029739435](https://crabbox.openclaw.ai/portal/runs/run_9f2fdf8a02d2aad39a29f67029739435), exit 0. The large-mode fixture also built from `513b774d28` ([run_b92c7c5b1893ded6f4b4c02bbe3e8058](https://crabbox.openclaw.ai/portal/runs/run_b92c7c5b1893ded6f4b4c02bbe3e8058), exit 0). Schema 42 and the lowered large-mode threshold are disposable qualification overlays, not shipped schema or policy changes.

- PostgreSQL 16 focused owner run [run_0a734ee4124db7308ba39734795af613](https://crabbox.openclaw.ai/portal/runs/run_0a734ee4124db7308ba39734795af613): **7/7 pass** on `ad7e6280300163cf55c97987ca36229427a6e236`. Includes a non-superuser runtime owner, real reader and column-only roles, grant options, default grants for later tables, unchanged originals, both historical v39 layouts, mixed engines, frozen-launcher file recovery and owned namespace pruning.
- The new startup regression is red on base `5c569ef59a78`: three intended assertion failures (PG-shared cases return current; configured-agent case falls back), not import/setup failures. [run_f03e6807f052b8bee5d12ce55a5a1bd9](https://crabbox.openclaw.ai/portal/runs/run_f03e6807f052b8bee5d12ce55a5a1bd9).
- Reader access is red on pre-ACL `997e3bd583`: actual PostgreSQL `42501 permission denied for schema` after source-owner checks, cloning and physical validation. [run_374698ce02d32a9c790a68028b747f1c](https://crabbox.openclaw.ai/portal/runs/run_374698ce02d32a9c790a68028b747f1c).
- The same deterministic 100-session/10,752-message/42 MiB prose recipe measured **22.030 s** for one direct state+agent copy (7.831 s state, 14.181 s agent), versus **44.9 s** for the earlier server capture+restore. This is prior-head primitive evidence at `4a2ac42861`; physical sizes were 109,199,360 B and 109,256,704 B, respectively. It excludes migration and Gateway readiness and is not a fleet-percentile claim.
- Implementation-head actual 1 GiB copy (`ad7e628030`): **91.312 s** summed API calls (state 6.295 s, agent 85.018 s); **94.903 s** enclosing interval includes receipt/bookkeeping. Fixture: 1,000 sessions, 114,688 messages, 448 MiB prose, 1,074,192,384 physical bytes. Actual in-clone ANALYZE was **8.923 ms / 924.153 ms**; COMMIT→statistics COMMIT **15 ms / 929 ms**, with no statement-cap hit. Same AWS c7a.8xlarge/32 CPUs/PG16.15 loopback environment. [run_ea0ba8f4997497d5471b2514409ac2c1](https://crabbox.openclaw.ai/portal/runs/run_ea0ba8f4997497d5471b2514409ac2c1). Copy interval alone uses 7.91% of the existing budget; migration and readiness are not included.
- Implementation-head static quality (`ad7e628030`): core and test typechecks, lint, format parity, line-cap, SQL-worker/dialect and import-cycle guards passed. That earlier `check:changed` run reported an unchanged UI dead export; the UI file and the main-only `plugin-npm-prepared-release-retained-producer.test.ts` ratchet finding were left unchanged. [run_a6eca5556aa261ea23377fa7ef465043](https://crabbox.openclaw.ai/portal/runs/run_a6eca5556aa261ea23377fa7ef465043). Final CI above is green.
- Additional AWS owner checks [run_5bfc8d62fbe03884f89f1e074d773274](https://crabbox.openclaw.ai/portal/runs/run_5bfc8d62fbe03884f89f1e074d773274), exit 0: real PostgreSQL mixed-engine migration/rollback/prune including a retained JSON configuration file (**3/3**), measured size-mode selection (**2/2**), core typecheck and database-worker ratchet (**166→166** live SQL calls). The earlier bounded update/report/Doctor/startup set passed **102 tests** before static checks found the explicit-return and duplicate-query issues now corrected; its obsolete static continuation was stopped.
- Corrected reporter/candidate full builds passed on `056e58a1f6` ([run_1600dd89588952b226d0c9a1c1464616](https://crabbox.openclaw.ai/portal/runs/run_1600dd89588952b226d0c9a1c1464616), including **83** report/startup-progress owner tests) and `816d247a8e` ([run_1806f6db08bd5a5b96115f85fc7371c0](https://crabbox.openclaw.ai/portal/runs/run_1806f6db08bd5a5b96115f85fc7371c0)).
- Real PG16 terminal-row regression: with the metadata guard removed, the live-custody test receives `undefined` instead of its terminal record; fixed code passes. [run_d6d5571a1f215a87f5595a2d208c00c7](https://crabbox.openclaw.ai/portal/runs/run_d6d5571a1f215a87f5595a2d208c00c7), exit 0. The test overlay SHA-256 `9e183ef1082b9919f31565434c84e98bd9f36efdae23ae3eebcf1029ada42a1e` matches the committed test.
- Historical BLOB corpus: `40910f1112` (before the trace change) and `f5b0f14e05` fail on the premature `Uint8Array` path; main `47b6dfba22` passes ([comparison run](https://crabbox.openclaw.ai/portal/runs/run_bd406b7313533d912b0cf2724017665e)). The corrected `eea155e5d7` full runtime build and corpus case pass, including **all original database `.pre-` hashes**: [run_036ade5c82663f841278cda6d372825b](https://crabbox.openclaw.ai/portal/runs/run_036ade5c82663f841278cda6d372825b), exit 0.

### Linux / PostgreSQL 16 live outcomes

Times are measured HTTP unavailability, with the sampled upper bound in parentheses—not total package-install time.

| Case / update run | Observed result | Unavailable seconds |
| --- | --- | --- |
| [Healthy `3216f87a`](https://crabbox.openclaw.ai/portal/runs/run_348b18b19173c81569cb78f95c97723b) | New namespace, schema 42, unchanged selected table counts; custom reader and default grants still work | 93.443 (93.945) |
| [Crash after private migration `8f78b578`](https://crabbox.openclaw.ai/portal/runs/run_a61b9c3d4becc39890a1efc1f29939c5) | Original namespace/schema 41 and old T serve; Control UI and rollback status reachable | 109.198 (109.700) |
| [Missing CREATE `06cfa933`](https://crabbox.openclaw.ai/portal/runs/run_a98b7abc71e6338fce59695e96e535c6) | Refuses before stop with exact grant; old boot ID unchanged | No unavailable samples |
| [Real space refusal `124b69ae`](https://crabbox.openclaw.ai/portal/runs/run_6c1b9afbbcdcf7e53cdcb9e3205c2fd3) | PG `53100` from a 64 MiB tablespace against a >100 MiB source; exit 78, schema-41 reporter serves; Settings and CLI name the space problem and remedy | 26.559 (27.063) |
| [During server copy](https://crabbox.openclaw.ai/portal/runs/run_e1068fb7d19e614c83fb4895f8118d84) | Backend transaction aborts after one interruption; retry succeeds | 102.281 (102.785) |
| [After private anchor, before live publication `c2462582`](https://crabbox.openclaw.ai/portal/runs/run_13461405a6ea35983c16ded96c9a2d79) | One interruption; retry succeeds | 105.403 (105.906) |
| [Corrected large-store CLI `26687f74`](https://crabbox.openclaw.ai/portal/runs/run_f6ff27e1f1f6dbf9ee1c96dfbd330585) | **Exit 0**, same namespace 41→42, real migration witness; notice in CLI, status and Settings | 20.602 (21.106) |

The corrected large-store run is [run_f6ff27e1f1f6dbf9ee1c96dfbd330585](https://crabbox.openclaw.ai/portal/runs/run_f6ff27e1f1f6dbf9ee1c96dfbd330585), exit 0. A qualification-only lowered threshold selects that branch on a small store; production policy is unchanged.

Cleanup was proved by **byte-identical replay of the existing durable plan**, not a claim that the earlier ad7 retry pruned successfully. Namespace inventory **32→30**: only failed state `restore_ea858c2cbd3241ee9273fb6fee420cdd` and agent `restore_b5af9a52198b4d87b57fcc3d8f755721` were dropped. Live `restore_a8c51d96f8d34ebd8fba8966297a85b3` / `restore_b3ce0081721947ef946c5abf222f6d21` and originals `pgcrash_state_4f1e55aebce84abd` / `pgcrash_agent_889dbaaff3c64c0d` stayed intact. No manual `DROP` or invented plan operations were used.

Cleanup observation: [run_d5c7866cee8a21eb5dd5e79f78ce1a64](https://crabbox.openclaw.ai/portal/runs/run_d5c7866cee8a21eb5dd5e79f78ce1a64).

Plugin maintenance still reports the existing engine-selection warning in these fixtures; core success is not relabelled or hidden. The recorded space cause retains a descriptor warning and generic triage wording alongside the visible free-space remedy.

## Large-store Decision and Named Limits

- **Final decision:** preparation reads the physical sizes of the namespaces that would be copied. At the measured simplification of **90 s/GiB**, an estimate of **at most 600 s** selects c2, leaving half of the existing 20-minute deadline for a retry. Above it, the existing in-place path remains available, without copy-only privilege requirements. Blocking updates would be worse than main for these users. This constant replaces a per-server rate estimate and should be revisited when actual larger-store rates are measured; there is no new user flag, configuration, timer or persisted field.
- A crash before a durable plan discards the private shadow and copies again on the second start. Both starts share that deadline; a large-store retry can expire safely and return to the old version. After publication, the next start sees the target version and reuses the selected namespace.
- **Post-COMMIT, at most ~10 s of planner statistics run before the private anchor is recorded. A crash there can leave one unreferenced namespace requiring manual cleanup.** The [COMMIT→statistics call](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/infra/database-engine/port.worker.ts#L707-L712) precedes the [private anchor write](https://github.com/openclaw/openclaw/blob/ad7e6280300163cf55c97987ca36229427a6e236/src/snapshot/database-backup.operations.ts#L441-L456). The bound is the existing `postgres-planner-statistics.ts:16` statement timeout, not a new timer. No new marker was added.
- Deep, external and symlinked paths outside the installed launcher's recoverable inventory keep their ordinary Doctor captures but do not gain automatic data rollback here ([openclaw#204394](openclaw#204394)).
- A serving T that predates the generic exit-78 report projection still has its old first-hop message. Preparation-time permission refusal keeps its named reason; newer serving versions show recorded boot-refusal detail.
- An older preparer also does not persist the candidate's new informational size notice from a successful check. Candidate boot logs the in-place selection, but the large-store CLI/status notice proof starts an updated schema-41 reporter. This first-hop limitation does not change the older updater's baseline in-place behavior.
- Trial-only writes are discarded on rollback. A PostgreSQL outage is not repaired by restoring anchors; readiness, not a file-level rolled-back label, confirms recovery.
- Already-stranded installations without a preserved original namespace still require a compatible build or a verified matched backup. Never lower schema markers or drop uncertain namespaces to force startup.

## Final-head Scope and Test Budget

`ad7e628030..056e58a` adds physical-size selection and the existing persisted diagnostic notice for the large in-place branch. Below the threshold, the protected copy/migration path is unchanged. Live qualification found retained JSON configuration files reaching the PostgreSQL anchor reader during pruning; the final head filters that existing list once, covered by the real rollback/prune test. Actual disk-space refusal also exposed two diagnostic issues: the report preferred a truncated prefix over the full recorded stderr tail, and normal startup progress printed completion lines after a failed start. The final head uses the existing bounded tail and emits completion only for successful startup phases, leaving the refusal last; CLI finalization is unchanged. Other changes reuse the schema owner's typed content-version reader, make undefined preflight success explicit, compute retention once, correct the docs, and remove 136 redundant wiring-test lines. Mode selection, corrected cleanup and final cause visibility require their own final-source live proof; ad7 live runs do not prove those changes.

Final head `5bbf3e6712` has the `816d247a8e` package runtime plus the SQLite-only legacy-safe discovery correction proved by the BLOB corpus. Remaining changes are the verified test overlay, a test-local rename/import correction, allocation notes and documentation. No PostgreSQL runtime change is excluded from the final 816 package proof.

The CLI failure was a physical-read mismatch, not an uncompleted notice: a real PostgreSQL run was `finished/succeeded`, but `update.runs.get` read the SQLite anchor and returned `run:null`, so the existing follower timed out. The shortcut predates this PR (`ba58d6a00b17`, openclaw#191332). The earlier PostgreSQL trial used Settings to start updates and `openclaw update status` to inspect them; it did not exercise foreground CLI following. The fix changes the reader owner, not polling, deadlines or the public protocol.

For historical BLOB registry paths, the existing preflight reader leaves non-string rows to Doctor. Both `main` and `ops` databases in the corpus are independently discovered at `agents/<id>/agent/openclaw-agent.sqlite`; the existing corpus test hashes **every** original database and checks its `.pre-` original (`test/state-upgrade.e2e.test.ts:189,247–248`). Non-default legacy BLOB registrations that fall outside that discovery remain a named openclaw#204394 limitation, not a new coercion or refusal.

Remaining test allocation (approved after those cuts):
- Real PostgreSQL ACL/non-superuser tests preserve reader access, ownership, grant options and historical layouts.
- Mixed-engine migration failure and crash recovery prove originals survive and only owned unreferenced namespaces are pruned.
- Copy-refusal tests prove preparation fails before stop with an actionable cause.
- Generic report projection and one nested startup-progress regression (tracing off/on) prove recorded boot-refusal remedies remain the final visible cause.
- One parameterized size-routing test proves under/over selection, the notice and retained SQLite protection.
- One real PostgreSQL terminal-read regression exercises the physical command path used by the CLI follower, rather than the SQLite anchor.

Production delta against the base: **+1192/−234, net +958 lines across 27 files**. The growth covers physical-engine inventory/validation, transactional access-right preservation, paired namespace retention, measured mode selection and refusal-output ordering. Existing duplicate private PostgreSQL capture work is removed; standalone and uncovered-store captures remain.

Co-authored-by: Ayaan Zaidi <[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]>
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 gateway Gateway runtime 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. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

update: on PostgreSQL, a crash after migration leaves no Gateway running

1 participant