Repository navigation
fix(backup): restore every PostgreSQL store from archives and Git - #174744
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8230d12818
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const { createConfigIO } = await import("../config/config.js"); | ||
| const { config } = await createConfigIO({ | ||
| observe: false, | ||
| pluginValidation: "core-only", | ||
| }).readConfigFileSnapshot(); |
There was a problem hiding this comment.
Load the recovery config under offline custody
readConfigFileSnapshot() can return { valid: false }, but this code ignores that flag and passes the rejected configuration to PostgreSQL backup/restore workers; it also captures the config before runWithLocalStateOwner acquires custody, so an edit during admission can make the operation create or discard schemas on a stale destination. Previously the callback consumed scope.config, whose lazy loadConfig() runs under the owner assertion and rejects invalid configuration; retain that owner-scoped behavior while avoiding state-dependent plugin validation.
AGENTS.md reference: AGENTS.md:L65-L70
Useful? React with 👍 / 👎.
|
Codex review: blocked before merge. What this changesRestore declared PostgreSQL archive stores through existing providers, give Git stores distinct identities, and verify Git exports without creating namespaces. Example: Recover an archive containing shared state and Workboard into a separate PostgreSQL database.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 1 item remains Keep open: this PR repairs documented PostgreSQL recovery gaps, and the previous code findings are addressed. No new introduced defect was confirmed; honor the maintainer’s request to leave it unmerged. Priority: P1 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherThe backup CLI connects archive and Git artifact readers to database-family providers; captured configuration and matched exports enter, and verified recovery namespaces plus local anchors leave. flowchart TD
A[Backup CLI] --> B[Archive or Git inventory]
B --> C[Matched artifact verification]
C --> D[Offline recovery owner]
D --> E[Database family providers]
E --> F[Fresh PostgreSQL namespaces]
F --> G[Matching anchors and recovered config]
Technical reviewBest possible solution: Keep capsule provenance with the producer and restore every declared store through its existing provider before publishing recovered anchors and configuration. Do we have a high-confidence way to reproduce the issue? Current-main source confirms extraction without PostgreSQL rehydration, colliding additional-store identities, and verification through restore; supplied real-server integration results exercise the repaired paths, but no target code was executed during this review. Is this the best way to solve the issue? The implementation addresses the owning boundaries coherently: producer-recorded capsule provenance, existing family providers, offline configuration validation, staged publication, and local artifact verification. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 83fab6f21417. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +609, Tests +1622, Docs +71, Other -1. Total +2301 across 39 files. Added test files: 3. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (3 earlier review cycles)
Reviewed October 17, 2026, 12:16 AM ET / 04:16 UTC (Revision 4). |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e356c8c01a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const entry = byPath.get(required); | ||
| if (!entry || !isRegularArchiveFile(entry.type)) { | ||
| throw new Error(`PostgreSQL backup is missing a regular matched artifact: ${required}`); |
There was a problem hiding this comment.
Verify PostgreSQL artifacts before reporting backup success
When a PostgreSQL capsule contains all four regular files, this loop accepts it without validating the export manifest, artifact hashes, or anchor binding. The later SQLite pass only inspects portable images associated with global/agent owners, so plugin stores are not content-checked at all, and a valid-SQLite tamper or mismatched anchor can also pass for core stores. Consequently backup verify and backup create --verify can report success for a backup that preparePostgresRestore later rejects during disaster recovery; run matched-envelope verification for every declared capsule here.
Useful? React with 👍 / 👎.
| const id = primary | ||
| ? family | ||
| : `${family}${resourceId ? `__${resourceId}` : ""}__${createHash("sha256") | ||
| .update(resourcePath) | ||
| .digest("hex")}`; | ||
| databases.push({ path: file, identity: { role: "generic", id } }); |
There was a problem hiding this comment.
Prune PostgreSQL scopes removed from an all-store backup
When a discovered store disappears between two git create --all runs, no new manifest is produced for its stores/<id> scope, but the cleanup path still calls only prepareStaleAgentUpdates and never reconciles generic scopes. The old store therefore remains in HEAD and continues to be selectable by --store, making the newest supposedly complete backup expose stale data as current; reconcile the existing stores/ scopes against the full discovered scope set.
Useful? React with 👍 / 👎.
| const directoryPath = path.posix.dirname(entry.normalized); | ||
| const envelope = parsePostgresEnvelope(value, path.posix.basename(directoryPath)); |
There was a problem hiding this comment.
Avoid rejecting legacy archives for PostgreSQL lookalikes
For legacy archives, an ordinary file named *.postgres/manifest.json is ignored only when JSON parsing fails or source.engine differs; once it contains { "source": { "engine": "postgres" } }, parsePostgresEnvelope runs outside the catch and any missing field rejects the entire archive. Thus an unrelated plugin/user manifest with that minimal shape prevents verification and restore of an otherwise valid older backup, despite the adjacent compatibility comment; only claim the directory after the complete envelope shape has been recognized without turning malformed lookalikes into archive failures.
Useful? React with 👍 / 👎.
|
@clawsweeper re-review The final follow-ups at The full local archive → wipe → recovery-database restore → real Gateway-start proof passed, including five families, two Matrix roots, legacy capsules, and failed-restore namespace cleanup. The existing format-2 export and matching-provider requirement are unchanged; the optional archive inventory preserves legacy archive reads. The PR includes existing-format and opaque SQLite preservation proof, and does not claim a new cross-schema upgrade contract. The body records the local timing/deadline evidence. Final-head CI is running. |
|
🦞👀 Re-review progress:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7ae1b4e124
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ...["manifest.json", "anchor.sqlite", "database.sqlite"].map((name) => | ||
| path.posix.join(directoryPath, name), | ||
| ), |
There was a problem hiding this comment.
Reject SQLite sidecars beside PostgreSQL artifacts
When a restored archive contains an undeclared database.sqlite-wal beside this required portable image, verification accepts it and extraction preserves it. restorePostgresBackup then opens database.sqlite normally in read-only mode, so SQLite can consume committed rows from that WAL; the envelope hashes only the main file, and user-backup restore does not compare the resulting table verification. Thus a tampered archive can pass verification yet silently import unmanifested data into PostgreSQL. This remains possible even after adding the matched-envelope verification requested in the earlier review because that verifier also ignores sidecars.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
openclaw/src/snapshot/git-backup.ts
Line 372 in ae6ffcb
When --all processes a configured PostgreSQL agent whose anchor is readable but whose server/provider export fails, dumpGitBackupDatabase() rejects outside the degradation try block. This aborts the entire backup instead of preserving that agent's previous scope, warning, and continuing with the other databases as the documented --all behavior promises; include PostgreSQL capture in the same per-agent failure boundary.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dab0f53f30
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bdbf473841
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
#174744 and #174859 landed together; the consolidated lstatIfExists helper is always bigint and takes one argument, so tsgo failed on main. Co-authored-by: steipete <[email protected]>
…enclaw#174744) * fix(backup): restore every PostgreSQL store from archives and Git Rehydrate captured state, agents, plugin families and retained Matrix roots through their providers before publishing matched anchors. Preserve distinct Git resource identities, expose store selectors, and verify matched exports without allocating server namespaces. * fix(backup): establish PostgreSQL selection in cold CLI workers * test(backup): align discovery and CLI fixtures with restore contracts * fix(backup): validate recovery config under offline custody * fix(backup): verify PostgreSQL capsules and prune stale stores * fix(backup): retain degraded PostgreSQL agent scopes * fix(backup): bind PostgreSQL Git capsules to their scope * fix(backup): reject undeclared PostgreSQL archive stores * fix(backup): restore archived family selection under custody * test(backup): separate archive restore proof scenarios * fix(backup): bind archive imports to generated capsules * fix(backup): reject capsule sidecars and restore config aliases
What Problem This Solves
Full archive restore extracted PostgreSQL exports without recreating their namespaces. Git
--allcould collide discovered stores, and Git verification allocated a namespace it did not remove. The proposed archive import path also needed provenance: a valid export copied into a workspace must not be mistaken for a generated capsule and consumed.User Impact
New archives record every generated PostgreSQL capsule by archive-relative path and the SHA-256 of its exact manifest. That manifest binds the store UUID, namespace, and artifact hashes. Verification and restore use this capture-time list. Unlisted capsule-shaped files remain opaque user data: they are neither imported nor consumed.
Declared PostgreSQL stores restore through their existing providers into fresh namespaces: state, agents, Workboard, Logbook, Team Reports, and retained Matrix roots. Every store verifies before matching anchors publish. Recovery configuration and its captured includes are validated under offline custody; the existing family-selection owner prepares engines from that recovered configuration. The recovered configuration publishes last. Failures clean prepared namespaces and the incomplete target. SQLite stores remain SQLite.
Declared capsules reject SQLite WAL, SHM, and journal sidecars before verification or import, including sidecars beside their outer anchors. The shared matched-export verifier enforces the same self-contained artifact rule for direct import. Captured root config aliases read the archived canonical payload while preserving the original path context for relative includes.
The outer archive's capsule inventory and canonical config-source path are additive; the PostgreSQL capsule format is unchanged. Older archives without the field import only global/agent capsules named by their existing database inventory. Other exports remain byte-identical files. Verification and restore warn operators to re-run backup with this version on the source installation before recovering plugin PostgreSQL stores automatically. A PostgreSQL anchor without an owned matched capsule is refused before application-database checks.
Git backup records distinct registry/plugin resource identities and exposes
--store <id>alongside--globaland--agent. PostgreSQL Git verification checks matched artifacts locally without allocating a namespace. Source bindings reject swapped current captures; historical captures remain readable. Removed-store pruning preserves operator files and history, and degraded agents retain their previous scopes while healthy stores refresh.Why This Change Was Made
Addresses source audit #174642 and the copied-export finding in #174786 (comment). Rebased after #174698 and #174387 merged, dropping the squashed security commits while retaining PR2's family-aware selection and resource discovery.
The producer owns capsule provenance; archive orchestration owns sequencing; existing providers own store restoration and verification. Broad capsule-shape discovery is removed. Manifest encoding and portable archive-path checks use their existing owners. Net production delta: +609 (+945/−336). The additional production code preserves the existing config reader and provider boundaries; it adds no capsule version or database schema.
Evidence
Homebrew PostgreSQL 17 with vector, pg_trgm, and unaccent: the final archive and Git suites passed all five cases in one process (63.705s full-family Gateway recovery, 27.336s mixed-mode alias recovery plus recapture, 18.753s legacy/cleanup, 32.386s discovery/pruning, and 7.046s namespace-free verification/legacy restore). File time was 230.68s including cold compilation; wrapper time was 238.89s. The second-backup collision check moved to the smaller mixed-mode fixture after the prior CI head hit the all-family case deadline; the all-family Gateway proof remains intact. The original 240-second archive and 120-second Git deadlines are unchanged.
Final-head PostgreSQL CI passed all 395 tests, including all five archive/Git cases, four secret-parity cases, and Matrix account-root persistence. The archive cases took 138.905s, 59.216s, and 38.281s in CI; the Git cases took 79.847s and 12.840s, within their original deadlines.
Commands verification/restore suites passed 71 tests with one platform skip; config capture passed 16; the raw-config relative-include regression passed; the matched-envelope suite passed 17. Commands/config/infra types, scoped lint, formatting, and independent isolated P0–P2 review passed. The alias baseline attempt was invalidated during worker compilation before tests, so it is not counted as red proof. These real-server tests exceed the unit-test budget because they cover provider materialization, separate recovery databases, and actual Gateway admission.
Head:
376cbc58ec06441bcb240d868b5421c207e17c17. Final-head CI:The exact-head CI UI failures are admitted under Peter's inherited/causal-path exception. Latest completed scheduled main baseline: run 38999305057, head
c05055d29fa2cbb5c21392f70975f03544021b75. All five failing test files are unchanged in the tested merge and import no PR-changed module. These cases use mocked Gateway data, not archive restore or config recovery.chat-plugin-steering.e2e.test.tsdetails.chat-notice-inline/ Advisor guidance. The main shard passed; no matching-main failure is claimed. Projection, chat-divider, and notice CSS are unchanged; no backup/config recovery path executes.chat-pr-publication-state.e2e.test.tsplugin-skills.e2e.test.tswebkitLineClampis empty instead of2. The main shard passed; no matching-main failure is claimed. Plugin view/CSS and mock-Gateway setup are unchanged.chat-retry-failure.e2e.test.tschat-pull-requests.e2e.test.tsNo UI fixes or CI retries were made. All other CI jobs passed or were intentionally skipped; no fail-fast jobs were cancelled.
The preceding PostgreSQL run exceeded the all-family case deadline and subsequent config/custody checks failed while unfinished test work continued. This head redistributes the second-backup proof to the smaller mixed fixture while retaining all-family Gateway admission and the existing deadlines. ClawSweeper's exact-head review reports no actionable findings. Its release-archive compatibility request is now covered by an actual published
[email protected](latest) installation in a throwaway prefix: non-interactive SQLite onboarding, a local mock-provider turn, full backup with release-side verification, and restoration by this exact PR head'spnpm openclawCLI after aqaRuntimebuild.The released archive's 33 regular files were all retained. Its synthetic assistant reply remained queryable, and all three copied user-export files were byte-identical before and after activation. The existing release-to-current agent-schema migration required
openclaw doctor --fix --non-interactive(v24 to v28); after migration the Gateway passed HTTP health and shut down cleanly. The counted proof used an allowlisted environment, isolated HOME/state/ports, and no configured channels or paid provider calls. An initial fixture inherited channel settings from the shell; it was stopped and excluded, and the complete proof was repeated cleanly. Throwaway package and data paths are removed after proof. No Docker was used.The published stable release is SQLite-only, so released PostgreSQL artifacts remain unavailable; all-family PostgreSQL and legacy capsule behavior is covered by the exact-head 395-test conformance run and the fixture-based legacy tests above.
Landing uses the explicitly authorized inherited/causal-path CI exception above. No fix push or rebase was required.