Skip to content

fix: let PostgreSQL Gateways start with plugin-backed secrets - #201063

Merged
VACInc merged 3 commits into
openclaw:mainfrom
Staruy:fix/postgres-secrets-startup
Nov 19, 2026
Merged

VACInc merged 3 commits into
openclaw:mainfrom
Staruy:fix/postgres-secrets-startup

Conversation

@Staruy

@Staruy Staruy commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

High Level TLDR

A cold Gateway using PostgreSQL for shared state can fail while preparing valid plugin-backed secrets. Secrets preparation now reads plugin metadata through the worker. Web-provider discovery passes the installed-plugin records and migration readiness it read to the scoped loader. External channel contracts reuse the prepared manifest registry.

Related to #201058.

Scope

Three small adjustments keep every secrets-preparation path on the worker-read facts:

  • Plugin metadata is now also loaded when the only plugin-backed surface is a web tool (tools.web search or fetch config, via hasRuntimeWebToolConfigSurface), so web-tool-only configs get the prepared manifest registry instead of a later synchronous read.
  • Plugin metadata is also loaded when only the assignmentConfig needs it, so a projected assignment config does not fall back to a synchronous read.
  • The channel secret collector skips the channels.defaults key. It is shared channel defaults, not a channel id; without the skip, a config whose only channel key is defaults would look up a channel contract for it and fall into the synchronous config-wide manifest resolver.

What Problem This Solves

A Gateway that keeps shared state in PostgreSQL could fail to start from cold when its config uses plugin-backed secrets, for example a web search provider plugin with a SecretRef API key. Secrets preparation runs on the Gateway main thread, and plugin metadata, installed-plugin records and migration readiness were read synchronously there. PostgreSQL connections are only allowed from the database worker, so startup stopped with PostgreSQL connections must run in a worker before any credential was resolved. SQLite Gateways were not affected.

Root Cause

The synchronous manifest resolver on the Gateway thread opened PostgreSQL while loading plugin metadata. The regression fixture reproduced the actual admission error, PostgreSQL connections must run in a worker, with both a fresh ledger and a committed migration receipt.

Switching only the metadata read leaves a second path through web-provider discovery and the synchronous loader. The loader checks migration readiness. Its asynchronous reader publishes a reusable readiness result only when the process has a committed migration receipt. A fresh ledger can therefore return an empty result from the worker and still cause a synchronous PostgreSQL read afterward. The loader now consumes that empty result explicitly. No cache policy or admission guard changes.

Evidence

Real behavior proof

The fixture opens a disposable PostgreSQL shared-state store, installs the Gateway process role, and verifies that the real guard refuses synchronous PostgreSQL connections on the test thread. It calls prepareSecretsRuntimeSnapshot and uses a local plugin that registers a web search provider. Success means the named provider was selected and the synthetic SecretRef was materialized.

# Set POSTGRES_TEST_PRELOAD to the file URL for
# scripts/test-database-conformance-preload.mjs with connection=<encoded test DSN>.
NODE_OPTIONS="--import=$POSTGRES_TEST_PRELOAD" pnpm test src/secrets/runtime-web-provider.postgres.test.ts --maxWorkers=1
  • Before, PostgreSQL stopped at the admission guard in both cases. SQLite passed.
  • After, PostgreSQL with no receipt, PostgreSQL with a receipt, and SQLite all passed (Tests 3 passed (3)). Local PostgreSQL was 16.16 with a dedicated database and non-superuser role. The test file ran in 8.89 seconds including test setup and transform on the final run.
  • The new test is a .postgres.test.ts suite, so the hosted PostgreSQL conformance job runs it on this head.

Verification

  • Final local run passed 39 tests across the PostgreSQL regression, web tools, and core secrets snapshots. Channel-contract, plugin-origin, and plugin-loader sibling tests passed before the final web-tools simplification.
  • Targeted formatting, type-aware lint and type checking, and git diff --check passed.
  • PR CI provides the broad and fork-head checks. On the previous head, the hosted PostgreSQL conformance job ran src/secrets/runtime-web-provider.postgres.test.ts and all three cases passed.
  • A follow-up test-only commit marks the three updated install-record and manifest mocks as intentionally isolated (// mock-isolation:) and drops their superseded entries from config/test-mock-exports-baseline.txt. This fixes the baseline-ratchets mock-exports check; no runtime code changed.
  • Remaining CI red is inherited from main: checks-node-changed-compact-large-3 fails only src/gateway/server.config-patch.test.ts "uses fresh revisions after agent create, update, and delete before reload applies" (gateway request timeout for agents.delete). Scheduled main run 44401396829 fails the same test with the same error in the same shard. Its fixture config has no SecretRefs, plugin entries, channels, or web tools, so secrets preparation takes the fast path and never reaches the code this PR changes.

What was not tested

Full Gateway socket startup, live provider calls, and production startup latency were outside this focused run. The PostgreSQL baseline stopped before credential materialization, so there is no successful before/after latency comparison for the repaired path. The fixture disables bundled plugins, so the bundled web-provider path and the web-tool-only metadata trigger are covered by the existing unit suites, not by the PostgreSQL regression.

@clawsweeper

clawsweeper Bot commented Nov 18, 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.

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

✅ Maintainer security changes approved

A maintainer approved this revision with an explicit security approval comment.

A later push requires a fresh approval comment for an external contributor's PR.

@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. 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. 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 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Prepare plugin metadata and migration readiness asynchronously before resolving plugin-backed secrets.

Example: A cold PostgreSQL Gateway resolves the vault SecretRef models/openai.

  • Before: Secrets preparation can abort because synchronous PostgreSQL access runs on the Gateway main thread.
  • After: Existing workers prepare metadata and readiness before secret resolution continues.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation is focused and appears correct, but stable-package runtime evidence does not establish the submitted revision's startup behavior.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A PostgreSQL Gateway can reject valid plugin-backed secrets and abort cold startup.
Reason: Restoring the supported startup path has clear user value, and the change preserves existing configuration and plugin contracts.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this PR open: it addresses a current, source-verifiable PostgreSQL startup failure with a focused repair, and no introduced correctness defect was found.

Priority: P1
Reviewed head: 72373b07f683517771436cd13a7ea4d75d2554a2

Before merge

  • Add real behavior proof - The supplied terminal output exercises cold preparation with real PostgreSQL workers on a patched 2026.11.5 package, followed by reported Gateway/RPC/agent success; the submitted revision has focused mocked-metadata regression coverage but explicitly lacks current-branch Gateway runtime proof, so the contributor should supply that scenario with IPs, keys, phone numbers, and non-public endpoints redacted. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Await maintainer action - A maintainer must review revision 72373b0 and grant the enforced security-sensitive-change approval.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted terminal output or logs showing this PR revision starting a cold PostgreSQL Gateway with existing plugin-backed SecretRefs and configured web tools, without manual prewarming.
Agent review details

How this fits together

Gateway startup passes configuration and SecretRefs into secrets preparation, which consumes plugin metadata and migration facts and returns a resolved runtime snapshot.

flowchart TD
  A[Gateway startup] --> B[Secrets preparation]
  B --> C[Async plugin metadata]
  B --> D[Async migration readiness]
  C --> E[Plugin discovery and secret resolution]
  D --> E
  E --> F[Resolved runtime snapshot]
Loading

Technical review

Best possible solution:

Use the existing async metadata and readiness owners before discovery while preserving SecretRef policy and PostgreSQL thread admission.

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

Current main contains the cold synchronous metadata path and loader readiness fallback, and the database admission owner throws the reported PostgreSQL exception; no target code was executed during this read-only review.

Is this the best way to solve the issue?

This is a small, coherent repair using existing worker APIs, without a new cache, admission exception, schema, or competing owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Config-wide plugin metadata discovery keeps the original intent (1ca60fb: Use the config-wide manifest registry instead of inferring a default agent workspace.)
  • Plugin-backed SecretRef materialization keeps the original intent (6037a74: Resolve plugin-managed secret providers from installed manifests while retaining full plugin policy.)
  • Idle discovery fast paths keeps the original intent (5ae27df: Avoid plugin-origin discovery when no configured plugin entries require it; later changes extended eligibility.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +12, Tests +98. Total +110 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 18 6 +12
Tests 1 98 0 +98
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 116 6 +110

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.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #201058
Summary: This PR is the explicit fix candidate for the reported cold secrets-preparation failure.

Members:

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

Labels

Label changes:

  • add P1: An affected PostgreSQL Gateway cannot start after a supported state port; this is an advanced operator workflow.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P1: An affected PostgreSQL Gateway cannot start after a supported state port; this is an advanced operator workflow.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Supply the current-revision cold PostgreSQL startup evidence described above.

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 18, 2026, 2:35 AM ET / 07:35 UTC.

@VACInc VACInc self-assigned this Nov 18, 2026
@VACInc

VACInc commented Nov 19, 2026

Copy link
Copy Markdown
Member

/allow-security-sensitive-change

@VACInc

VACInc commented Nov 19, 2026

Copy link
Copy Markdown
Member

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 20, 2026
…aw#201063)

Gateway startup secrets preparation on PostgreSQL loads plugin metadata,
install records and migration readiness through the async worker path
instead of synchronous reads on the Gateway thread, which PostgreSQL
refuses.

Co-authored-by: VACInc <[email protected]>
Co-authored-by: Staruy <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
Gateway startup secrets preparation on PostgreSQL loads plugin metadata,
install records and migration readiness through the async worker path
instead of synchronous reads on the Gateway thread, which PostgreSQL
refuses.

Co-authored-by: VACInc <[email protected]>
Co-authored-by: Staruy <[email protected]>
(cherry picked from commit 9fa0b92)

Gap-sweep intake (Dallin, 2026-11-24): ledger-high/P0-P1 fix not yet on 2026.11.10. Clean apply. Later main mentions of #201063: none.

Co-authored-by: RomneyDa <[email protected]>
maplel pushed a commit to maplel/openclaw that referenced this pull request Nov 24, 2026
)

* fix(plugins): portable plugin-state keys for PostgreSQL

Use an exclusive SQL lower bound for Doctor pagination instead of a NUL-suffixed cursor. Reject new NUL keys in test-only plugin-state fixtures while retaining legacy SQLite adoption reads.

Add real PostgreSQL Doctor regression coverage and register it in conformance and database-worker lanes. Refs openclaw#184862 openclaw#188642.

* test: account for rebased plugin-state coverage

* test(clickclack): import legacy revocations before adoption

(cherry picked from commit 395cac7)

Release adaptation: Only exclusive SQL lower bound in kernel and Doctor pagination; preserve legacy SQLite keys and public validation. Regression exercises real Doctor paging and inspected executed SQL bindings; no NUL-key fixture policy, schema or unrelated tests.

Follow-up dispositions: 8253356 fix: preserve child results after source lifecycle changes (openclaw#202708); f3f89c7 fix: show saved child results when completion delivery fails (openclaw#202664); c45faa8 fix: align CI tests with admitted tool calls (openclaw#202655); 5c9389a fix: make channels add report required plugin install failures (openclaw#202091); 52b9188 fix: show hosted model details in `models list` without a Gateway (openclaw#202490); d248a76 fix: show an outcome when kept child chats return no answer (openclaw#202423); 5148804 fix(discord): check a queued message's access again when its turn starts (openclaw#202330); 2470d62 fix: let setup use account models with a fresh catalog (openclaw#202019); 9fa0b92 fix: let PostgreSQL Gateways start with plugin-backed secrets (openclaw#201063); c180824 fix(plugins): Talk and plugin-loading requests fail on PostgreSQL Gateways (openclaw#201976); cb5cfb2 fix: keep a doubtful killed-update recovery on the repair path (openclaw#201361); 17c5fb0 fix(state): PostgreSQL state created before Template bootstrap deferral is refused as schema drift (openclaw#197425); b5c1277 fix: let resumed parents collect children stopped by restart (openclaw#201460); f920a7e chore(postgres): qualify cron completion during graceful shutdown (openclaw#201246); 1680f54 fix(openai): new ChatGPT subscription models missing until an OpenClaw release (openclaw#201130); 0d8820a fix(media): image descriptions use the ChatGPT OAuth route when OpenAI has no API key (openclaw#199299); ee3e16e test(agents): trim and fold low-value regression suites (openclaw#198916); b8029b4 test(agents): qualify PostgreSQL simple-completion acquisition (openclaw#200956); 703c82d fix(sessions): record queued input end causes and recover them across crashes (openclaw#200533); 23fca1a fix: let the next update continue after a killed update when nothing is left to repair (openclaw#200680); d565e17 fix(ci): retire deleted session fork test from inventory (openclaw#200611); 4cf12c6 chore(postgres): qualify prompt refresh and rebalance CI (openclaw#200488); d460273 fix(templates): release earlier Template-managed agents (openclaw#200303); ff75829 fix(update): --no-restart update fails when the Gateway restarts itself during Doctor's stop (openclaw#200181); 0b2ad60 chore(postgres): cover compaction watched-session prompts (openclaw#200117); b90c573 test: consolidate redundant coverage (198795 recut) (openclaw#198943); a042363 test: consolidate redundant coverage (198793, part 2) (openclaw#198936); 9bfad2b test: consolidate suites while retaining recovery owners (openclaw#198933); 4e9812c test: consolidate redundant coverage (198789, part 2) (openclaw#198932); 90814f5 fix(subagents): stops a finished sub-agent's chat being deleted before its parent reads the result; 799bc0b fix(ci): stabilize hourly fixtures and retire unused exports (openclaw#199851); e4a3093 perf(update): replace the candidate canary with a runtime contract check (openclaw#198268); a4cc2ad fix: undo cold-session compaction CPU and latency regressions (openclaw#199561); 55fec79 fix(agents): stop divergent mid-turn overflow recovery (openclaw#199636); 2c4413a fix: reduce Gateway stalls under filesystem pressure (openclaw#197510); 37d977f fix: output reducers are skipped in headless and Code Mode runs (openclaw#199434); c9ee264 fix(compaction): concurrent sessions wait for each other's summaries during compaction (openclaw#196550); 2471ddc feat: let agents review generated images before delivery (openclaw#198227); 21f7dc6 fix(github): publication fails with PostgreSQL session or state stores (openclaw#193749); 63d9e57 fix(ci): new PostgreSQL suites are omitted from conformance (openclaw#198390); 466a4b6 fix(telegram): steered answers quote the wrong input (openclaw#178124); 87b6f52 fix(delivery): resend routed Telegram finals after an ambiguous network failure (openclaw#192779); 68a839b fix: isolate held agent databases until explicit restoration (openclaw#198180); cff99b2 fix(agents): keep provider history append-only across runs (openclaw#197874); 8a328bf feat: add an opt-in usage-ranked tool index (openclaw#197128); 097e648 fix(ci): plan only executable infra tests (openclaw#197911); 76385fd fix(models): discovered models become "Unknown model" after restart or an ended sign-in (openclaw#197784); 89d4177 fix(plugin-state): guarded calls fail until Gateway restart after an unknown write outcome (openclaw#197790); baca36e fix(sessions): commit selected invitations with original messages (openclaw#184512); 699e538 fix(sessions): drain passive notices on sessions_send resumes; d6ded18 chore(ci): drop retired test-lines allocation records (2/3) (openclaw#197656); e0dd020 fix(agents): collect process results at suspended-run capacity; 4897740 feat(auth): preserve delegated OCE user profiles and permissions (openclaw#196856); 7197ce1 feat(templates): install bundled plugins through native management (openclaw#196349); 9c6ee9b feat: let Template automations start paused for onboarding (openclaw#196323); 79a6214 fix(message): retain local final replies in conversation history (openclaw#187795); caa978c feat(templates): open durable chat before verified setup (openclaw#196392); 78e73aa fix(sessions): cold PostgreSQL conversations fail after idle readers close (openclaw#189991); b6ed907 perf(sessions): persist active transcript facts for hydration (openclaw#193682); 1595dd2 feat(plugins): reauthorize accepted session work (openclaw#176886); b43ad0a fix(models): avoid reloading plugins on catalog refresh (openclaw#193903); 0947d02 fix(ci): avoid unrelated PostgreSQL runs and admit owned tests (openclaw#193870); 428ca7d feat(openclaw-id): add Gateway membership authority and publication behind the Labs flag (openclaw#192335); c718583 fix(update): repair refuses forever after a verified update fails a later step (openclaw#193132); 3f64174 fix: deliver background replies after a reload retires the turn registry (openclaw#193130); 982f3b1 fix(imessage): report Automation failures after Gateway updates (openclaw#186117); 31b28e9 fix(agents): wait for a peer OAuth refresh before failing request auth (openclaw#192906); cf50d4a feat(storage): support read-only PostgreSQL standby inspection (openclaw#192645); 82fd4e6 fix(agents): retain stale session target refusal reasons (openclaw#192681); 8ac4e19 fix(worktrees): reserve capacity on PostgreSQL (openclaw#192537); 718b349 fix: reduce session startup stalls under storage contention; 08f4a19 refactor(skills): move Skill Workshop into its bundled plugin (openclaw#192471); 837402a fix(clawrouter): keep upstream credit failures off the shared key (openclaw#192575); f38495f fix(plugins): reject late routing from canceled runs (openclaw#192492); dc5d61a improve(sessions): reduce unnecessary maintenance query rows (openclaw#192023); c4bf0dc fix(sessions): avoid extra maintenance scans for embedded archives (openclaw#184507); e44b3d6 fix(team-reports): recover after database connection loss (openclaw#192020); 991fb33 fix(logbook): recover after database connection loss (openclaw#192011); e6d0d2e fix(test): include omitted PostgreSQL conformance suites (openclaw#191962); da5ff0f fix(codex): reject native hooks from a previous run (openclaw#191788); 09f0b0b feat(plugins): add skill usage runtime for plugins (openclaw#191661); 00b2ff4 fix: parent sessions miss child approvals with a custom session store (openclaw#189827); be44b10 fix: stop completed session writes retaining request data (openclaw#191197); d40aa7c fix(sessions): replay creation requests across Gateway restarts (openclaw#190862); d894035 fix: await Doctor shared-state repair preparation (openclaw#190875); b515cc7 feat: fork threaded conversations with Telegram support (openclaw#190783); def6349 feat(plugins): plugins can run a hidden forked turn of a session with their own tools (openclaw#190950); d983e34 feat(plugins): plugin commands can continue the agent with a replacement prompt, on every channel (openclaw#190908); ea3f0b8 fix(ci): provision Node test prerequisites and retain Baseten routing (openclaw#191050); 29503e1 fix(update): Gateway stays stopped after the updater process dies mid-update (openclaw#188497); fc8c2d0 fix(update): preserve unfinished handoff artifacts (openclaw#190571); 7c26e8c fix(ci): cover PostgreSQL managed update handoffs (openclaw#190336); 4913d41 fix(ci): prevent truncated PostgreSQL target listings (openclaw#189509); 8925f62 fix(gateway): start restored PostgreSQL homes on the first attempt (openclaw#190291); 177fe32 feat(models): preserve inference capabilities in opt-in catalog v3 (openclaw#189678); 7faf32d feat: retain repository disk authority through recovery (openclaw#189106); a658df3 feat(database): capture externally quiesced SQLite migrations; 0f9e7f7 feat(database): capture exact SQLite migration capsules; 4fb684e feat(backup): add PostgreSQL local companion checkpoints; c89a101 fix(doctor): migrate auth profiles on PostgreSQL stores (openclaw#189639); 799de09 fix(ci): split oversized workspace and setup files (openclaw#189356); 21ee847 fix(acp): keep completed run conversations resumable (openclaw#189273); fce0e56 perf(sessions): open cold history without restoring archives (schema 39) (openclaw#188397)

Validation: Baseline1 NUL-binding assertion failure/21passing; candidate22/22passes (188693-green.log). Real SQLite Doctor path and generated SQL proved; no native PostgreSQL server execution claimed.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 0895146d8c1493146f5c6461eee0b10c329bdd1e)
(cherry picked from commit f8ccaa70bc9773d6bbb569bc0e275eee0c544ead)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. security-sensitive-changed size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants