Skip to content

feat(backup): add PostgreSQL local companion checkpoints - #189685

Merged
roboclaw-bot merged 12 commits into
mainfrom
openclaw/postgres-local-companion
Oct 31, 2026
Merged

roboclaw-bot merged 12 commits into
mainfrom
openclaw/postgres-local-companion

Conversation

@roboclaw-bot

@roboclaw-bot roboclaw-bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

PostgreSQL installations need local restart checkpoints without exporting and later rolling back their live database rows.

User Impact

openclaw backup create --local-companion --verify captures local files, fixed-local credentials, and PostgreSQL anchors. Verification and staging restore work while PostgreSQL is offline; activation reconnects to the same stores/namespaces and current rows. restore --local-companion also works through --from and refuses ordinary archives before extraction.

This is not disaster recovery. All portable families must select PostgreSQL. Local files roll back; PostgreSQL rows do not. Stop the Gateway before activation, keep the matching database available, and do not run original/restored installations concurrently with the same credentials. Legacy-audit migration inputs and saved PostgreSQL export directories are refused. Source-preserving capture keeps row IDs and may retain free-page bytes; it is not a secure-deletion export. Ordinary backups retain exports, online capture, sanitization, and fresh-namespace recovery.

Why This Change Was Made

The manifest profile/anchor inventory lets the existing verifier reject store/namespace mismatches, sidecars, and undeclared exports offline. Existing credential owners preserve fixed-local credentials and rebind them to the matching anchor. Generic acquisition remains owned by #189638, now landed on main as f33e48e6720fe0b7b8ba2801096f532275cd08a5. This PR targets main and contains only PR6 changes; the squashed dependency is not duplicated in its diff.

Adapted from Galin's source commit, with contributor credit retained. No externally-quiesced capture API, PostgreSQL import/rollback path, new production manager, or competing state owner is added.

Evidence

Main integration after PR4 landing

Merged pinned main f33e48e6720fe0b7b8ba2801096f532275cd08a5 into the existing publication lineage after the stacked PR automatically retargeted to main. Resolved only six duplicate preservation-option hunks in two files, retaining the reviewed companion behavior. The main-targeted diff is exactly the 19 PR6 files, with no PR4-only test/support/allocation delta. backup-create.ts is byte-identical to the Diamond-reviewed version; snapshot planning retains main’s existing weak-owner-map allocation helper instead of the equivalent local helper.

Inspected relevant main authority changes: pairing wait-observation labels, worker-identity detection (not the operator client path), and an early refusal to issue a token for a missing paired device. Token verification/revocation and the companion credential-restore owner are unchanged. The original actual Gateway/PostgreSQL and stable-upgrade evidence remains bound to its recorded source, not relabeled as a new-head execution.

Affected gates: 66 tests passed in 7 files / 2 shards (capture and ordinary controls, archive completeness, credential promotion, source aliases, pairing worker, weak-map contract); wrapper 133.64s, native preparation 71.00s. Core and infra test typechecks passed; targeted type-aware lint had zero warnings/errors; formatting and diff checks passed. Fresh independent P0–P2 autoreview of committed f0d71193a94d178b486623b929b9b2a63ae3f7f4 against pinned main completed source verification with the full PR6 delta and 18 frozen owner contracts: scoped-clean, no actionable findings. It did not independently rerun tests or live PostgreSQL. New exact-head PR CI is required. No product scope or test-budget expansion was added for this integration.

Integrated production CLI / Gateway / PostgreSQL

Built through the supported owner at exact source 399a3cfc1ab391ae5c17b85350aa2b7c1aabde6e; all build stamps/build-info matched. The subsequent merge 6818508e3090855e6478358b3897f62f323ac4e4 changes exactly two inherited test/support files and their allocation. At Diamond-reviewed head 9bbf226cf8db03c4ed0b96effc4143d296620c2a, all production inputs were byte-identical to that tested runtime. The later main integration is qualified separately above; no fresh live PostgreSQL run on the new head is claimed. PostgreSQL 17.11 ran only in a disposable task-owned container/database; no live user state or Gateway was touched. No model inference is claimed for this authentication/RPC boundary.

  1. Two distinct clients authenticated with native device tokens and exercised protected device-pairing RPCs. The built CLI captured backup create --local-companion --verify while the Gateway ran: one matching PostgreSQL anchor, zero export capsules.
  2. After capture, the admitted administrator used device.token.revoke on the second client and changed a real PostgreSQL-backed label to current-after-capture.
  3. Stopped/joined Gateway and PostgreSQL; confirmed PostgreSQL connection refusal. Built CLI offline verify and restore --local-companion returned ok:true. Promoted only the task-owned restored tree, with both services stopped. Read-only whole-row hashes/counts matched for two native identities, two tokens, and one native exec socket credential; the PostgreSQL anchor matched exactly.
  4. Restarted the same database and a new Gateway on the restored tree. The captured allowed token authenticated and completed a protected rename. The captured token revoked after capture was rejected with AUTH_DEVICE_TOKEN_MISMATCH during connection authentication, before its attempted protected rename. An independently admitted read proved the forbidden label was never written. The post-capture label survived activation; the store anchor and every non-system namespace matched. No PostgreSQL import, new namespace, or rollback occurred during companion restore.
  5. Stopped/joined all task services. The expected negative authentication message is evidence, not a failed test.

Sanitized terminal results; successful proof commands exited 0:

BOTH_DISTINCT_DEVICE_TOKENS_AUTHORIZED_BEFORE_CAPTURE
CHECKPOINT_CREDENTIALS_ANCHOR_NAMESPACE_WITNESS_RECORDED
BUILT_CLI_COMPANION_CAPTURE_VERIFIED
POST_CAPTURE_REVOCATION_AND_CURRENT_ROW_COMMITTED
POSTGRES_CONFIRMED_OFFLINE
backup verify: ok=true profile=local-companion
backup restore: ok=true profile=local-companion
OFFLINE_PROMOTION_EXACT_CREDENTIAL_ROWS_SOCKET_SECRET_SAME_ANCHOR_OK
ACTIVATED_ALLOWED_AUTH_AND_PROTECTED_EFFECT_OK
CAPTURED_REVOKED_CLIENT_REFUSED_BEFORE_PROTECTED_EFFECT
CURRENT_POSTGRES_AUTHORITY_AND_ROW_NOT_ROLLED_BACK
RECONNECTED_SAME_ANCHOR_AND_ALL_NAMESPACES_OK

Latest-stable existing-data compatibility

Installed actual latest stable v2026.10.9 with the maintained installer in a separate task prefix, isolating released dependencies from this checkout. Its real Gateway/public SDK produced a paired identity/token, protected rename, and nondefault timezone. On the same state without resetting/reseeding, current Doctor migrated shared schema 20 → 36 and the native credential store; original identity/token whole-row hashes matched. The original token authenticated to the exact candidate Gateway, read the retained setting, and completed a protected rename. After the supported SQLite → PostgreSQL port, that same released credential authenticated against PostgreSQL and read the retained setting.

LATEST_STABLE_AUTH_PROTECTED_EFFECT_SETTINGS_OK
LATEST_STABLE_CREDENTIALS_SETTINGS_PROTECTED_EFFECT_AFTER_UPGRADE_OK
RELEASED_CLIENT_AUTHENTICATES_AGAINST_CURRENT_POSTGRES

Stable had no PostgreSQL/native-client-store selection: this proves actual stable SQLite/native-credential upgrade, followed by a supported port before capture, not stable PostgreSQL migration. First Doctor invocation hit its outer command budget after migration; state was reconciled before idempotent resumption, which completed. No product watchdog was weakened.

Automated proof and finding disposition

  • Hosted tuple-inference P2 fixed with named fields, no casts/suppressions. Combined infra test typecheck passes.
  • Actual baseline-failure logs classified: relocated errno cast replaced with existing hasErrnoCode; duplicated PRAGMA site replaced with existing read-only helper, preserving both guards. Generated assertion baseline pruned through its owner (one obsolete allowance removed); dialect sites decrease 3 → 1. Both ratchets pass. Test-line CI already passed: 328 governed lines plus two inventory lines explains the review's +330 surface. Unique allocation remains 328.
  • Post-PR4 integration run: 45 tests passed / 3 files: source-preservation WAL/DELETE, companion capture, full archive completeness. Wrapper 170.02s, native preparation 106.55s, Vitest 39.19s; combined infra typecheck/diff checks pass.
  • Repair run: 59 tests / 3 files passed, wrapper 385.03s including 219.92s preparation; targeted type-aware lint zero warnings/errors, formatting/diff checks pass. Earlier unchanged-consumer evidence: 17 focused tests plus alias regression, covering credential promotion, remote/offline refusal, identity/namespace/profile/sidecar/export damage, ordinary WAL and mixed-engine controls. Synthetic anchors are not counted as real PostgreSQL proof.
  • The inherited resource.sock failure is fixed by feat(backup): preserve source artifacts for internal captures #189638 and integrated without duplicating the patch. Personally inspected exact test-only diff and owner evidence: 241 passing tests / 16 consumer groups, original-base red controls, real CLI round trip, clean independent review.
  • Independent P0–P2 autoreview completed the full feature with frozen credential owner context and fresh follow-up repair review; source verification completed and no actionable findings remained. The dependency's full review is also clean. No pending runtime proof was credited by those reviews; the actual evidence above now closes that gap.

Remaining observations and accepted limits

Prior head 494226b9 CI's compact-small-18 failure is the now-integrated missing broker socket repair. Its separate copied-harness E2E failed with retryable Model runtime changed before this turn started; that fixture does not exercise backup/restore. No fix or baseline attribution is claimed for that observation; current-head CI must be inspected. An earlier broad Node ordinary-WAL timeout at 120s and cleanup cascades remain recorded; later Bun success is not claimed as its fix. The earlier pre-integration two-anchor PostgreSQL exercise is supplementary only.

Initial final-flow setup gave two clients identical silent-pairing metadata, so the owner correctly pruned the superseded client before revocation. Distinct client display names repaired the fixture, then a new archive was captured only after both explicit tokens authenticated. No authorization guard/scope was relaxed; original stable-token compatibility had already passed independently.

Combined-stack follow-up: the separately prepared SQLite-only migration PR must reject postgresAnchors as well as PostgreSQL exports; that guard is absent from the pinned main base. Parent coordinates that integration and serialized landing. Current-head CI remains required. The original hosted Diamond 5/6 assessment is retained at 9bbf226c; no new hosted assessment is claimed or requested solely for this mechanical main integration.

Worked on by

roboclaw-bot and others added 4 commits October 31, 2026 18:16
Worked on by:
- @galiniliev

Co-authored-by: galiniliev <[email protected]>
OpenClaw-Publication: 13c22d85-5d08-4693-a372-4f031d1e46e8
Capture local files and fixed-local credentials with validated PostgreSQL anchors, then verify and restore offline without exporting, importing, or rolling back PostgreSQL rows. Reuse the source-preserving backup owner and rebind credentials to the same store identities.

Co-authored-by: galiniliev <[email protected]>
Worked on by:
- @galiniliev

Co-authored-by: galiniliev <[email protected]>
OpenClaw-Publication: b1627006-23a2-496a-8b7b-df1b1dcc5a04
@clawsweeper

clawsweeper Bot commented Oct 31, 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 cli CLI command changes commands Command implementations labels Oct 31, 2026
@roboclaw-bot
roboclaw-bot changed the base branch from main to openclaw/backup-preserve-source October 31, 2026 19:03
@roboclaw-bot
roboclaw-bot marked this pull request as ready for review October 31, 2026 19:04
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 31, 2026
@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR adds PostgreSQL companion checkpoints that restore local files and credentials while reconnecting to existing database rows.

Example: A device label changes to current-after-capture after a companion checkpoint is created.

  • Before: Ordinary PostgreSQL backup recovery restores captured rows into fresh namespaces.
  • After: Companion restore retains the existing namespace and current-after-capture label while restoring captured local files.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) The focused feature reuses established owners, resolves the previous finding, and supplies production-path authorization and latest-stable compatibility proof; current-head CI remains pending.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Sanitized terminal output from the built CLI, isolated Gateway, and PostgreSQL 17.11 covers capture, PostgreSQL-offline verification and restore, credential preservation, allowed protected effects, rejection of a post-capture revoked client before its effect, and retention of current rows and namespaces; the tested production inputs remain unchanged at this head.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: PostgreSQL users need local restart checkpoints without exporting or later rolling back live database rows.
Reason: The maintainer-authored direction supplies a distinct operator capability with explicit activation limits and preserves ordinary disaster recovery.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR adds a distinct checkpoint capability absent from main; the previous fixture finding is fixed, and no new actionable defect was found.

Priority: P2
Reviewed head: 9bbf226cf8db03c4ed0b96effc4143d296620c2a

Before merge

None.

Findings

None.

Agent review details

How this fits together

The backup CLI passes filesystem resources and database identities through existing capture, archive verification, and staging restore owners, producing restored local state bound to the original PostgreSQL stores.

flowchart TD
A[Backup CLI] --> B[Resource inventory]
B --> C[Local snapshots and PostgreSQL anchors]
C --> D[Companion archive]
D --> E[Offline verification]
E --> F[Staging restore and credential rebinding]
F --> G[Existing PostgreSQL stores]
Loading

Technical review

Best possible solution:

Land the explicit companion profile through the existing backup and credential owners after the stacked dependency and required checks clear.

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

This is a feature addition; source inspection confirms main's ordinary recovery uses exports, while the supplied production CLI trace exercises companion capture, offline restore, and activation.

Is this the best way to solve the issue?

The smallest coherent implementation adds profile and anchor metadata to existing owners, preserves ordinary recovery, and reuses credential matching rather than introducing a parallel recovery manager.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced feature boundary: The pinned introduced diff adds an explicit companion profile, requires PostgreSQL selection for portable families, and leaves ordinary PostgreSQL export capture on its existing path. (src/infra/backup-create.ts:306, 9bbf226cf8db)
  • Offline archive validation: Companion verification checks captured store and namespace identities, rejects sidecars and undeclared exports, and credits verified anchors toward database coverage. (src/commands/backup-verify.ts:226, 9bbf226cf8db)
  • Updated authority and compatibility proof: The public PR body supplies sanitized built-CLI, Gateway, and PostgreSQL output covering offline restore, allowed protected effects, rejection of a token revoked after capture, unchanged current rows, and actual v2026.10.9 credential/settings upgrade followed by a supported PostgreSQL port. (9bbf226cf8db)
  • Runtime proof remains applicable: The comparison from tested source 399a3cf to the reviewed head changes only two inherited test/support files within production source directories, corroborating the recorded unchanged production inputs. (9bbf226cf8db)
  • Previous finding resolved: The companion fixture now iterates named file/id object fields, removing the string-array indexed-access type defect identified in the previous review. (src/infra/backup-local-companion.test.ts:35, 9bbf226cf8db)
  • Accepted operator tradeoffs and contributor credit: The collaborator-authored direction explicitly accepts local-file rollback without PostgreSQL rollback, retained credentials, possible free-page bytes, and exclusive activation; it credits galiniliev's source contribution and builds on feat(backup): preserve source artifacts for internal captures #189638. Public docs: docs/cli/backup.md. (docs/cli/backup.md:107, 9bbf226cf8db)

PR surface

Source +277, Tests +330, Docs +27, Other +1. Total +635 across 19 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 11 577 300 +277
Tests 5 425 95 +330
Docs 1 27 0 +27
Config 0 0 0 0
Generated 0 0 0 0
Other 2 10 9 +1
Total 19 1039 404 +635

Review metrics

Metric Value Why it matters
New CLI option One flag exposed on create and restore --local-companion selects checkpoint creation or requires that archive profile during restore.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This optional PostgreSQL checkpoint capability has a limited, explicit operating scope.
  • merge-risk: 🚨 security-boundary: The profile deliberately preserves socket credentials and rebinds credential admission; the accepted operating limits and supplied allowed/revoked-client proof address the identified boundary.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-31T19:22:10.592Z sha 375da8c :: needs real behavior proof before merge. :: [P2] Preserve tuple types in the companion fixture

Reviewed October 31, 2026, 4:54 PM ET / 20:54 UTC (Revision 2).

roboclaw-bot and others added 6 commits October 31, 2026 19:53
Keep fixture fields concretely typed, reuse the SQLite inspection pragma owner, and replace the moved errno assertion with its existing guard. Prune the retired assertion allowance through the ratchet generator.

Co-authored-by: galiniliev <[email protected]>
Worked on by:
- @galiniliev

Co-authored-by: galiniliev <[email protected]>
OpenClaw-Publication: 3ce080ef-b111-4629-91b6-3cb40fedc152
Keep per-case native socket custody until state readers and the broker join.
Start preservation proof cold under short roots so the socket-path fallback
cannot hide the removed-socket regression.

Co-authored-by: galiniliev <[email protected]>
Worked on by:
- @galiniliev

Co-authored-by: galiniliev <[email protected]>
OpenClaw-Publication: 8d66e0e9-1742-4a32-b7ef-5349abb5dece
Merge verified PR4 head 9bac5c2.
Only inherited test/support files and their allocation change; production
inputs remain identical to the real Gateway/PostgreSQL proof at 399a3cf.

Co-authored-by: galiniliev <[email protected]>
Worked on by:
- @galiniliev

Co-authored-by: galiniliev <[email protected]>
OpenClaw-Publication: e3e68a2c-75f4-4114-83c2-8f240cd55c0c
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 31, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 31, 2026
Base automatically changed from openclaw/backup-preserve-source to main October 31, 2026 21:28
@github-actions

github-actions Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 19661b05bf5689a559293660afe9ce2aa4b605d0
  • Maintainer: @roboclaw-bot
  • Repository role: maintain

These security sensitive changes were made:

  • src/infra/client-credential-restore.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

roboclaw-bot and others added 2 commits October 31, 2026 21:42
Merge pinned main f33e48e after PR4
landed by squash. Resolve only duplicate preservation-option hunks while
retaining the reviewed companion flow and main weak-owner map reuse.
The main-targeted diff contains only the 19 PR6 files; no PR4-only delta.

Retain Diamond review and live PostgreSQL proof at 9bbf226/399a3cfc
as their original source-bound evidence; current-head CI remains required.

Co-authored-by: galiniliev <[email protected]>
Worked on by:
- @galiniliev

Co-authored-by: galiniliev <[email protected]>
OpenClaw-Publication: d663c56a-c58f-4e07-8718-6d7aa9283a28
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 merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. security-sensitive-changed size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants