Skip to content

fix(gateway): copied or restored PostgreSQL home fails its first start - #188949

Closed
etzelm wants to merge 1 commit into
openclaw:mainfrom
etzelm:fix/pg-r2-l1-first-boot-worker
Closed

etzelm wants to merge 1 commit into
openclaw:mainfrom
etzelm:fix/pg-r2-l1-first-boot-worker

Conversation

@etzelm

@etzelm etzelm commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: the Gateway exits on its first start with "PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread" after a PostgreSQL-backed OpenClaw home is copied, moved or restored. The second start works.

User Impact

User impact: a copied, moved or restored PostgreSQL home now starts on the first try. Before this, the first start always failed with a database connection error, and a plain retry worked. That pointed operators at the database, which was not the problem.

Why This Change Was Made

The local client-credential receipt records the path, device and inode of state/openclaw.sqlite (the PostgreSQL anchor file). When the home is copied, moved or restored, those no longer match, so Gateway startup runs client-credential maintenance to rebind the receipt. Near the end of that maintenance, the legacy exec-approval detection reads the canonical exec-approval row from shared state synchronously on the Gateway main thread, without engine admission. On PostgreSQL state the main-thread guard refuses that read and startup fails. The receipt has already been rebound by then, so the next start skips maintenance and works.

The fix wraps that one synchronous detection in withEngineStoreAdmission. The same file already does this for the required-credential source read on PostgreSQL. SQLite behaviour is unchanged: admission only affects the PostgreSQL main-thread guard.

Real behavior proof

Real openclaw gateway run on PostgreSQL. Both builds came from this PR's commits, built the same way, and ran with the same script and the same synthetic home:

  • Before: main 4d2a9f8bb4c47da0daae7fd820cab33fa450ef7b, this PR's parent.
  • After: PR head bb36792e746bf0c22179e4fb2e0c66e1880503cb.

Environment:

  • macOS 27.2 arm64, Node v24.22.2, PostgreSQL 17.11.
  • Database provisioned as in docs/gateway/postgresql.md: the openclaw_runtime role, plus the unaccent, pg_trgm and vector extensions.
  • Loopback only, --auth none. Channels, cron and providers are skipped.
  • No personal data. The home is created fresh for each run.

Steps for each run:

  1. Create a new SQLite home and start the Gateway.
  2. Run openclaw database port --to postgres.
  3. Start on PostgreSQL. The result is ready, and the credential receipt is bound to the anchor inode.
  4. Stop. Back up the home with cp -Rp, delete it, and restore it from the backup. The path stays the same, but the anchor gets a new inode.
  5. First start of the restored home.
  6. Second start.

After each start, the script reads three things from the home: the anchor inode, the client-credential receipt (client/credentials.sqlite), and the device identity.

Step 5: first start of restored home Run 1 Run 2 Run 3
main 4d2a9f8 exit 1, "must run in a worker" exit 1, same exit 1, same
PR bb36792 [gateway] ready, /readyz 200 "ready":true ready, 200 ready, 200

Runs alternated base, head, base, head. On main, step 6 (the plain retry) was ready 3/3. That matches the report: the failed start has already rebound the receipt, so the retry skips maintenance.

On the PR head, the restored home's first start rebinds the receipt to the new anchor inode and keeps the device identity. There are no device tokens in this synthetic home (0 before and after), so only the device identity is shown.

main 4d2a9f8, run 1, steps 3 to 6 (script output excerpt; paths shortened to <work>)
### 3. Gateway start on PostgreSQL (original home)
RESULT: READY after 8s
GET /readyz -> {"ready":true,"coreReady":true,"failing":[],...} (HTTP 200)
anchor <work>/inst/base/home/.openclaw/state/openclaw.sqlite ino 452593436
receipt phase complete sharedFile ./state/openclaw.sqlite ino 452593436
device identity 7aacc2d17e51f1b9...

### 4. back up the stopped home, then restore it from the backup (same path, new inodes)
cp -Rp home backup && rm -rf home && cp -Rp backup home
anchor <work>/inst/base/home/.openclaw/state/openclaw.sqlite ino 452597512
receipt phase complete sharedFile ./state/openclaw.sqlite ino 452593436

### 5. FIRST Gateway start of the restored home
RESULT: NOT READY after 3s (gateway exit code 1)
[openclaw] The CLI command failed.
[openclaw] Reason: Cannot open PostgreSQL connection: PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread; verify database.postgres.connection and server availability.
receipt phase complete sharedFile ./state/openclaw.sqlite ino 452597512

### 6. second Gateway start of the restored home
RESULT: READY after 7s
GET /readyz -> {"ready":true,"coreReady":true,"failing":[],...} (HTTP 200)
PR head bb36792, run 1, steps 3 to 6
### 3. Gateway start on PostgreSQL (original home)
RESULT: READY after 8s
GET /readyz -> {"ready":true,"coreReady":true,"failing":[],...} (HTTP 200)
anchor <work>/inst/head/home/.openclaw/state/openclaw.sqlite ino 452684932
receipt phase complete sharedFile ./state/openclaw.sqlite ino 452684932
device identity f90b4113fd2be01f...
device auth tokens 0

### 4. back up the stopped home, then restore it from the backup (same path, new inodes)
cp -Rp home backup && rm -rf home && cp -Rp backup home
anchor <work>/inst/head/home/.openclaw/state/openclaw.sqlite ino 452707160
receipt phase complete sharedFile ./state/openclaw.sqlite ino 452684932
device identity f90b4113fd2be01f...

### 5. FIRST Gateway start of the restored home
RESULT: READY after 10s
GET /readyz -> {"ready":true,"coreReady":true,"failing":[],...} (HTTP 200)
2026-10-30T23:16:35.569-07:00 [gateway] ready
anchor <work>/inst/head/home/.openclaw/state/openclaw.sqlite ino 452707160
receipt phase complete sharedFile ./state/openclaw.sqlite ino 452707160
device identity f90b4113fd2be01f...
device auth tokens 0

### 6. second Gateway start of the restored home
RESULT: READY after 7s
GET /readyz -> {"ready":true,"coreReady":true,"failing":[],...} (HTTP 200)
Commands (per arm)
git checkout <sha> && pnpm install --frozen-lockfile && pnpm build
openclaw gateway run --port <p> --bind loopback --auth none --tailscale off   # new SQLite home
openclaw database port --to postgres                                          # then database.engine: postgres
openclaw gateway run ...                                                      # ready; stop
cp -Rp home backup && rm -rf home && cp -Rp backup home
openclaw gateway run ...                                                      # first start of the restored home
curl http://127.0.0.1:<p>/readyz

Upgrade from the latest stable release

Latest stable is [email protected] (npm latest; extended-stable is 2026.9.36). That release has no PostgreSQL engine and no client-credential store, so a PostgreSQL home cannot be created on it. The upgrade path therefore starts on SQLite, and a single home goes through every step:

  1. [email protected] from npm: create a two-agent home (main and research, agents.defaults.timeoutSeconds: 900) and start the Gateway. Then, through the running Gateway, add 3 sessions with labels (sessions.create), add 9 messages (chat.inject), and add 2 exec allowlist entries (openclaw approvals allowlist add). Stop.
  2. Upgrade to PR head bb36792: run openclaw doctor --fix --non-interactive (the migration step openclaw update runs; head refuses the 2026.10.9 agent schema v25 until it has run), then the first start on SQLite.
  3. Run openclaw database port --to postgres, then start on PostgreSQL 17.11.
  4. Restore the stopped home from a cp -Rp backup. The anchor gets a new inode. Then the first start of the restored home.

After every start, the script reads /readyz and queries the running Gateway for the seeded sessions (sessions.list), each session's messages (chat.history) and the exec approvals (approvals get). With the Gateway stopped, it reads the settings and the device identity from disk. Each later snapshot is compared field by field with the 2026.10.9 snapshot:

Start Result Settings Sessions, messages Exec allowlist Device identity
1. 2026.10.9 (baseline) ready, /readyz 200 config sha 035bdea6, 2 agents 3 sessions, 3 + 2 + 4 messages 2 entries 4abb951c...
2. head, after doctor (SQLite) ready, 200 same same counts and hashes same patterns and ids same id and key hashes; moved to client/credentials.sqlite
3. head on PostgreSQL ready, 200 same same same same
4. head, restored home, first start ready, 200 same same same same; receipt rebound 455029436 -> 455030393
  • The comparison reported 0 unexpected differences at steps 2, 3 and 4. The only field that changed is the device identity's storage location, because head moves it into client/credentials.sqlite.
  • After step 4, the PostgreSQL schemas hold the data: the agent schemas have 5 and 4 active transcript events, and the state schema has the exec-approvals row.
  • must run in a worker appears in none of these logs.
  • Doctor kept every config key set on 2026.10.9 unchanged. It added meta (migration markers), wizard (last run), and skills.entries with 4 bundled skills disabled. That is head's Doctor behavior, independent of this PR.
Upgrade run, steps 2 to 4 (script output excerpt; paths shortened to <work>)
### 2. upgrade: same home, PR head; openclaw doctor --fix (the schema migration step openclaw update runs), then first start on SQLite
OpenClaw 2026.10.9 (bb36792)
doctor --fix rc=0
RESULT: READY after 7s
GET /readyz -> {'ready': True, 'coreReady': True, 'failing': []} HTTP 200
same   settings / config sha256 (all keys set before the upgrade): "035bdea68bf1637a"
same   settings / agents: ["main", "research"]
same   settings / agents.defaults.timeoutSeconds: 900
same   sessions / agent:main:ops-weekly: "Ops weekly"
same   sessions / agent:main:trip-planning: "Trip planning"
same   sessions / agent:research:papers: "Paper notes"
same   messages / agent:main:ops-weekly / messages: 3
same   messages / agent:main:ops-weekly / sha256(role,text,id): "8bf3796e0c2dfc8f"
same   messages / agent:main:trip-planning / messages: 2
same   messages / agent:main:trip-planning / sha256(role,text,id): "9fbfbc386501d3c9"
same   messages / agent:research:papers / messages: 4
same   messages / agent:research:papers / sha256(role,text,id): "484968ac9e856594"
same   exec approvals / allowlist / main: [["/usr/bin/uptime", "fcacee07"]]
same   exec approvals / allowlist / research: [["~/bin/fetch-papers", "8349259e"]]
moved  device identity / store: "state/openclaw.sqlite" -> "client/credentials.sqlite"
same   device identity / device_id: "4abb951c7bf321f5..."
same   device identity / sha256(public key): "8179dbdce2de996c"
same   device identity / sha256(private key): "8e1780745bc36320"
COMPARE: 0 unexpected differences

### 3. PR head: openclaw database port --to postgres, then start on PostgreSQL
port rc=0
RESULT: READY after 8s
GET /readyz -> {'ready': True, 'coreReady': True, 'failing': []} HTTP 200
(same fields and values as step 2)
COMPARE: 0 unexpected differences
receipt phase complete sharedFile ./state/openclaw.sqlite ino 455029436

### 4. restore the stopped home from a backup (cp -Rp, same path, new anchor inode), FIRST start on PR head
cp -Rp home backup && rm -rf home && cp -Rp backup home
anchor <work>/inst/home/.openclaw/state/openclaw.sqlite ino 455030393
receipt phase complete sharedFile ./state/openclaw.sqlite ino 455029436
RESULT: READY after 7s
GET /readyz -> {'ready': True, 'coreReady': True, 'failing': []} HTTP 200
(same fields and values as step 2)
COMPARE: 0 unexpected differences
receipt phase complete sharedFile ./state/openclaw.sqlite ino 455030393
device identity 4abb951c7bf321f5...

Evidence

  • An earlier run on a real multi-agent home, ported the same way and copied with cp -Rc, matched: main failed the first start 3/3, and the fix was ready 3/3. Stack from the failing start: readCanonicalRow <- hasLegacySqliteExecApprovals <- detectLegacyExecApprovals <- prepareStartupClientCredentials maintenance.
  • The new test startup-client-credentials.gateway.postgres.test.ts runs in the Gateway process role. It replaces the anchor (copy, then rename, so it gets a new inode) and reruns startup credential preparation. It fails on main with the same error and passes with the fix. The existing startup-client-credentials.postgres.test.ts (7 tests) and startup-client-credentials.test.ts (SQLite) pass.
  • pnpm check:changed passes everything except the knip production dead-export scan, which reports src/gateway/plugin-node-capability.ts: prepareClientPluginNodeCapabilities. That scan fails the same way on main, and the failure is unrelated to this change.
Test commands
node scripts/test-database-conformance.mjs --engine postgres --connection <dsn> -- \
  src/commands/startup-client-credentials.gateway.postgres.test.ts \
  src/commands/startup-client-credentials.postgres.test.ts
# main: 1 failed (Cannot open PostgreSQL connection: ... must run in a worker)
# fix:  8 passed
pnpm test src/commands/startup-client-credentials.test.ts test/scripts/database-conformance.test.ts
# 26 passed

- Startup client-credential maintenance reads the canonical exec-approval
  row through detectLegacyExecApprovals on the Gateway main thread without
  engine admission. On PostgreSQL state this throws "PostgreSQL connections
  must run in a worker" and the Gateway exits.
- The path runs only when the credential receipt no longer matches the state
  anchor's path/dev/ino, e.g. after copying, moving or restoring the home.
  The failed start has already rebound the receipt, so the next start works.
- Wrap that synchronous detection in withEngineStoreAdmission, as the same
  file already does for the required-credential source read.
- Add a Gateway-role PostgreSQL test that replaces the anchor and reruns
  startup credential preparation; register it in database conformance.
@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 scripts Repository scripts commands Command implementations size: S labels Oct 31, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment 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

Admit the synchronous exec-approval detection read during startup maintenance so restored PostgreSQL homes start successfully.

Example: Restore a stopped PostgreSQL home whose anchor inode changes from 452684932 to 452707160.

  • Before: The first Gateway start exits with “PostgreSQL connections must run in a worker”; a second start succeeds.
  • After: The first start reaches readiness, rebinds the receipt, and preserves the device identity.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused, correct repair with shipped-entry-point red/green evidence, upgrade continuity, and a distinct production-owner regression.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Supplied logs exercise the changed startup owner through real gateway run on macOS with PostgreSQL 17.11: restored homes fail on the pinned base and reach readiness on the exact head, preserving identity and rebinding the receipt; latest-stable upgrade traces additionally preserve seeded configuration, sessions, messages, and approvals.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A restored PostgreSQL home reports a misleading connection failure and exits on its first Gateway start.
Reason: Restores supported first-start behavior without adding configuration, changing defaults, or introducing another state owner.

Regression provenance

Regression provenance — verified: source commit 5f40d22a366d by Jason (Json); canonical PR #178998 (blame-to-merge-commit).

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a concrete startup failure still present on current main, with a focused patch and convincing supplied behavior proof; no actionable defects found.

Priority: P2
Reviewed head: bb36792e746bf0c22179e4fb2e0c66e1880503cb

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway startup prepares local credentials against the selected shared-state database before serving; maintenance reconciles the credential receipt and checks legacy approvals.

flowchart TD
  A[Gateway startup] --> B[Credential preparation]
  B --> C[Existing maintenance owner]
  C --> D[Credential receipt reconciliation]
  D --> E[Admitted approval detection]
  E --> F[PostgreSQL shared state]
  E --> G[Gateway ready]
Loading

Technical review

Best possible solution:

Land the narrow admission fix and Gateway-role regression through the normal merge gates.

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

The source establishes the unadmitted canonical-read path, and supplied base/head Gateway traces reproduce the reported first-start failure; this read-only review ran no target code.

Is this the best way to solve the issue?

This is the smallest complete fix: admit the existing synchronous maintenance read through its existing owner while preserving normal worker admission and migration policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Startup credential maintenance keeps the original intent (5f40d22: Automatically complete backed-up credential and approval migration before startup while preserving identities and refusing mismatched sources.)
  • Normal credential worker admission keeps the original intent (cca4a17: Remove normal startup SQL from the main thread while retaining required maintenance migration.)
  • PostgreSQL conformance registration keeps the original intent (a3ac586: Shard PostgreSQL conformance by test group; the new regression joins the existing target list.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Jason (Json): Raw commit 5f40d22 adds src/commands/startup-client-credentials.ts:268 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5f40d22a366d; files: src/commands/startup-client-credentials.ts)
  • Peter Steinberger: Raw commit cca4a17 adds src/commands/startup-client-credentials.ts:118 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cca4a1714700; files: src/commands/startup-client-credentials.ts)

PR surface

Source +4, Tests +79, Other +1. Total +84 across 3 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 6 2 +4
Tests 1 79 0 +79
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 3 86 2 +84

Review metrics

Metric Value Why it matters
Production versus regression growth Production/tooling +7/-2 lines; tests +79/-0 lines One real PostgreSQL regression supplies the distinct Gateway process-role boundary that the existing CLI-role suite misses.

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: 🦪 silver shellfish: 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: A copied or restored PostgreSQL home fails its first startup, with a successful plain retry limiting the outage.
  • 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 (3 earlier review cycles)
  • reviewed 2026-10-31T02:09:15.008Z sha bb36792 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-31T06:57:51.238Z sha bb36792 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-31T07:51:38.658Z sha bb36792 :: needs maintainer review before merge. :: none

Reviewed October 31, 2026, 4:45 AM ET / 08:45 UTC (Revision 4).

@etzelm

etzelm commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 31, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 31, 2026
@etzelm

etzelm commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 31, 2026
@etzelm

etzelm commented Oct 31, 2026

Copy link
Copy Markdown
Contributor 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 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 31, 2026
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @etzelm for the diagnosis and regression proof. Landed the credited replacement in #190291 (8925f62), keeping the boot-admission fix and an isolated restored-home regression. Closing this as superseded by the merged fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor commands Command implementations 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. scripts Repository scripts size: S 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