Repository navigation
feat(backup): restore PostgreSQL stores into a staging database for restore drills - #194808
Conversation
- backup restore --postgres-connection-env <name> imports PostgreSQL stores, and cleans up failed imports, through the DSN in that env var - only database.postgres.connection in the in-memory captured config is replaced; family selections, schemaPrefix and the restored openclaw.json stay as archived - refuses an invalid name, an unset variable, or an archive without PostgreSQL stores before extracting anything - --from restores forward the flag; output names the variable - docs: backup and PostgreSQL restore guides
|
🦞👀 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: needs maintainer review before merge. What this changesAdds an environment-variable flag that directs PostgreSQL archive imports and failure cleanup to a separate database while preserving archived configuration. Example: Restore a production archive with --postgres-connection-env DRILL_STAGING_PG_DSN.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR provides a useful, maintainer-approved restore capability still missing from main; no actionable defects were found at the requested head. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe backup CLI verifies and extracts an archive, then the offline database owner resolves captured configuration and imports PostgreSQL stores through existing providers, returning matching anchors and activation guidance. flowchart TD
A[Backup restore CLI] --> B[Archive verification]
B --> C[Fresh staging directory]
C --> D[Offline database owner]
E[Operator environment variable] --> D
D --> F[PostgreSQL import and cleanup]
F --> G[Verified anchors and archived config]
Technical reviewBest possible solution: Retain the narrow override in the existing offline restore owner, with shared import and cleanup routing and explicit activation guidance. Do we have a high-confidence way to reproduce the issue? Current-main CLI and offline-selection source establish the missing independent destination; supplied built-CLI output demonstrates the limitation and after-change behavior without a reviewer rerun. Is this the best way to solve the issue? The change is the smallest complete implementation of the accepted direction: replace one in-memory connection reference and reuse existing selection, import, verification, and cleanup owners. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 432c81856071. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +63, Tests +109, Docs +14, Other +2. Total +188 across 10 files. Added test files: 0. View PR surface stats
Preflight sourceSource 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
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
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 HistoryReviewed November 13, 2026, 3:13 AM ET / 08:13 UTC (Revision 3). |
…ride - --postgres-connection-env now builds its env SecretRef after reading the captured config, with resolveDefaultSecretProviderAlias(config, "env") - an archive with secrets.defaults.env = "primary" and no provider named default now imports through primary, keeping its allowlist - PostgreSQL archive restore test covers that custom-alias archive - docs: name the provider and allowlist the variable is read through
- record 89 net test lines for the --postgres-connection-env coverage: PostgreSQL override and custom env-alias restore scenarios, flag refusals and --from forwarding
|
@clawsweeper re-review
|
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review Please review exact head |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…estore drills (openclaw#194808) * feat(backup): restore PostgreSQL stores into a staging database - backup restore --postgres-connection-env <name> imports PostgreSQL stores, and cleans up failed imports, through the DSN in that env var - only database.postgres.connection in the in-memory captured config is replaced; family selections, schemaPrefix and the restored openclaw.json stay as archived - refuses an invalid name, an unset variable, or an archive without PostgreSQL stores before extracting anything - --from restores forward the flag; output names the variable - docs: backup and PostgreSQL restore guides * fix(backup): honor the archived env provider default for restore override - --postgres-connection-env now builds its env SecretRef after reading the captured config, with resolveDefaultSecretProviderAlias(config, "env") - an archive with secrets.defaults.env = "primary" and no provider named default now imports through primary, keeping its allowlist - PostgreSQL archive restore test covers that custom-alias archive - docs: name the provider and allowlist the variable is read through * test(backup): allocate test lines for restore connection override - record 89 net test lines for the --postgres-connection-env coverage: PostgreSQL override and custom env-alias restore scenarios, flag refusals and --from forwarding * test(backup): cover failed PostgreSQL destination restore cleanup --------- Co-authored-by: Vincent Koc <[email protected]>
…law#194384) * docs: clarify PostgreSQL conformance coverage * fix(cron): keep one-shot finalization working on PostgreSQL 16 * test(database): reuse cron conformance for JSON conversion regression * test(postgres): accept fractional explain row counts (cherry picked from commit 7ab0143) Release adaptation: Only engine-owned jsonValue and retained cron enabled JSON replacement; preserve native boolean type with PG16 explicit ::json and SQLite json(). Omit unrelated PG docs/EXPLAIN test edits; retained one-shot enabled-transition caller present on baseline. Follow-up dispositions: e029e18 docs: document isolated PostgreSQL restore drills (openclaw#202704); 49f0740 fix(database): report disabled memory after a port (openclaw#202630); a80b564 fix: keep database workers healthy after silent connection loss (openclaw#201856); 3d91af2 fix(config): reject reserved PostgreSQL schema prefixes (openclaw#202097); 835d722 fix: catch incompatible ownership before porting to SQLite (openclaw#202101); 67796a6 fix: keep scheduled Git backups current on PostgreSQL (openclaw#201870); cc849dd fix: recover lease heartbeats after a PostgreSQL connection loss (openclaw#201858); 6594caf fix: prepare macOS runtime pins without the PostgreSQL secret (openclaw#202102); 6ca56cd docs: clarify PostgreSQL storage and backup coverage (openclaw#202086); a079190 fix(postgres): chat history slows under concurrent reads (openclaw#190129); 2ff4256 feat(database): keep PostgreSQL rollback captures in PostgreSQL (openclaw#196236); 96c685b feat(backup): restore PostgreSQL stores into a staging database for restore drills (openclaw#194808); fb83d65 fix: reduce transcript allocation when preparing native context seeds; 71ec4d2 fix(config): keep Workboard PostgreSQL upgrades readable (openclaw#194648); b6ed907 perf(sessions): persist active transcript facts for hydration (openclaw#193682) Validation: Baseline cron generated json(bound text) on PostgreSQL where json(text) is unavailable; helper and focused boolean regression retained. Exact PostgreSQL16 server proof unavailable; focused SQLite/helper tests queued. diff check passed. Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit 38fdd9b52704d588d9ca24ef8e391d644961c985) (cherry picked from commit fb935e6912388314851b05cb698ef038b83bbd07)
Closes #182772
Decision recorded: env-only PostgreSQL restore destination override.
Maintainer acceptance recorded on 2026-11-13: after the recommended design and its limits were presented, continuation was authorized. Proceed with the recommended env-only flag below; archived config stays unchanged and activation remains explicit. Existing SecretRef provider allowlists and normal authentication remain enforced. Required review and validation still apply.
--postgres-connection-env <name>. Every PostgreSQL import, and the cleanup after a failed import, uses the DSN in that environment variable. Nothing else changes: the archived family selections andschemaPrefixstill apply, and the restoredopenclaw.jsonstays byte-identical to the archived one. The output names the variable and says to point the archived connection at the same server before activation. No new config keys, and the DSN never goes on the command line. The output deliberately names only the variable, not the server identity (host, database, user), so the DSN is never parsed or printed.openclaw.json. Activation would then follow the restore destination automatically, but restore would have to rewrite captured config, including$includefiles, so the restored config would no longer match the archive under test. This can be added later on top of this flag if maintainers want it.file:,exec:, JSON) instead of an env var name. This is more flexible but needs a new CLI SecretRef syntax. An env var already covers file and exec setups: the operator can export the staging DSN for one command.restore_<uuid>naming). That is a separate decision, as the issue review noted.What Problem This Solves
Restore drills of a PostgreSQL archive write full copies of every store into the production database when the archived connection is a file or exec SecretRef, because
backup restorecan only import through the connection recorded in the archive.User Impact
User impact: operators can verify a production archive by restoring it into a staging database. Production rows and schemas are not touched, and neither is the production secret file:
Restores without the flag behave as before. The flag is rejected when the variable is unset or the archive has no PostgreSQL stores, and nothing is extracted in that case.
Why This Change Was Made
Restore already validates the archived config in its own offline scope and resolves the import connection from it. The flag replaces only
database.postgres.connectionin that in-memory copy with an env SecretRef for the named variable. The reference is built after the archived config is read, with the existingresolveDefaultSecretProviderAlias(config, "env"), so it goes through the archived config's default env provider (secrets.defaults.env, ordefaultwhen none is set) and that provider's allowlist, the same way a hand-written default env ref would. Imports, verification and failed-import cleanup all read the same scope, so they all go to the same destination. Cleanup uses that shared scope too. The maintainer correction adds a forced failed-import regression with the override set, proving that destination namespaces and the incomplete target are cleaned while the source namespace inventory stays unchanged. The restoring host's own state ownership check still uses the live config, so a staging DSN cannot be confused with the host's live database.--fromrestores forward the flag too.Activation stays explicit. If the restored state is used with the archived connection still pointing at the original server, the anchors name a
restore_<uuid>namespace that does not exist there. State ownership then refuses with the existingMissing PostgreSQL metadata; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.error, and nothing is created on that server (checked in the CLI run below).Evidence
Through the built CLI, using the same base (
72b51fb6089) with and without this change. The setup is one PostgreSQL 17 server with two fresh databases: A, the "production" database behind a file SecretRef, and B, the staging database, whose DSN is supplied only through the environment. Each run starts a scratch install on A (doctor --non-interactive), records three backup runs as sample rows, runsbackup create --verify, then restores with the flag and again without it. The table comparisons count rows and hash the ordered row text of every table.Before (base build):
After (this branch):
openclaw_schema_metais compared on store, version and store id because one of its hash columns depends on the schema name. A's ownbackup_runstable gains the archive's run record after capture, so B is compared with A as it was at archive time.Tests, red on the base and green with the change:
src/infra/database-engine/archive-restore.postgres.test.ts, newoverridescenario: the archived connection still resolves to the source database and the flag points at a separate recovery database. It checks every store's rows on the recovery server, that the source server gets norestore_*namespace, and that the restored config bytes match the archive. On the base, the import goes to the source database and the recovery-server check fails (relation "restore_….user_profiles" does not exist). With the change all 5 scenarios pass.Same file, new
override-aliasscenario: the archive setssecrets.defaults.env = "primary"withproviders.primary = { source: "env", allowlist: [...] }and no provider nameddefault. On the previous head of this branch the restore fails withdatabase.postgres.connection SecretRef is unresolved (env:default:OPENCLAW_ARCHIVE_TEST_RECOVERY_PG)(1 failed, 5 passed). With the fix all 6 scenarios pass, in two runs.src/commands/backup-restore.test.ts: the flag rejects an invalid name, an unset variable, and a SQLite-only archive before anything is extracted. Red on the base (the restore resolved), green with the change (20 passed).src/cli/program/register.backup.offsite.test.ts:--fromrestores forward the flag. Red on the base (unknown option), green with the change (4 passed).Maintainer correction:
override-cleanupforces a later unavailable database family after an earlier store has imported. On the signed correctionbaaae4f0cfee309921906aa3d76471012b2938ae, the two focused real-PostgreSQL 17.11 recovery cases passed. Disabling destination cleanup made the negative control fail on the exact destination namespace inventory. The final source has seven PostgreSQL restore scenarios; the six-scenario suite results and timings above/below describe the preceding head. This focused correction does not claim preservation of populated source rows.Test cost: the final change adds 109 net test lines, recorded in
config/test-lines-allocations/backup-restore-postgres-connection-env.txt. The PostgreSQL scenarios prove that imports, verification and failed-import cleanup reach the override server and that a custom env provider alias resolves. The unit cases cover the refusals and--fromforwarding. Wall time with--maxWorkers=1:backup-restore.test.ts38 s,register.backup.offsite.test.ts17 s,archive-restore.postgres.test.ts96 s through the database conformance runner (Vitest duration 91 s for all 6 scenarios; the two override scenarios take 5.8 s and 5.7 s).Also run:
oxfmt --checkandoxlinton the changed files,pnpm tsgo:core,pnpm tsgo:core:test,pnpm check:import-cycles,pnpm check:test-lines-ratchet(merged with current main),git diff --check, andsrc/secrets/resolve.test.ts(33 passed). Docs:docs/cli/backup.mdanddocs/gateway/postgresql.mddescribe the flag next to the existing "point that secret at the recovery server" guidance, anddocs/cli/backup.mdnames the provider and allowlist the variable is read through.Risk: low. The flag is opt-in, and the code path without it is unchanged. The override uses the archived config's default env secret provider, so if that provider has an allowlist that does not list the variable, the restore stops with the usual SecretRef error and the target is cleaned. The built-CLI run above used an archive without custom secret providers; the custom-alias case is covered by the PostgreSQL restore test.