Skip to content

fix: let PostgreSQL agents start turns with plugin tools - #201876

Closed
VACInc wants to merge 3 commits into
openclaw:mainfrom
VACInc:fix/postgres-plugin-tools
Closed

VACInc wants to merge 3 commits into
openclaw:mainfrom
VACInc:fix/postgres-plugin-tools

Conversation

@VACInc

@VACInc VACInc commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

A healthy PostgreSQL Gateway can reject an agent turn with the full tool profile before contacting the model. Load missing plugin tools through the existing asynchronous loader so their readiness read runs in a worker.

What Problem This Solves

A plugin needed by the turn may not yet be registered in its runtime generation. Cold tool construction then reports PostgreSQL connections must run in a worker, even though Gateway readiness succeeds.

User Impact

Agent turns can load those plugin tools and complete. Synchronous compatibility entry points remain synchronous. This changes no configuration, schema, permissions, retention, or durability.

Why This Change Was Made

Async tool construction now carries its execution mode through the existing tool-resolution generator, including callers without workspace-readiness state. Plugin selection, registry reuse, factories, and tool policy keep their existing owners. The synchronous API selects the existing synchronous loader.

Existing consumer test doubles follow that same generator contract. The database regression reuses the existing forked plugin inspection suite and its fixture. An explicit conformance target keeps both PostgreSQL cases in database CI. One unchanged diagnostic helper moves into the existing tool inspection module to satisfy the source-file size limit.

Root Cause

On the base, resolvePluginToolsFromRegistry calls loadPluginRegistryHandle for missing owners. That synchronous loader skips the readiness worker step and falls back to readPluginStateMigrationReadiness on the Gateway thread. Opening the PostgreSQL connection there is correctly refused. The asynchronous agent adapter also previously selected the synchronous resolver when no workspace-readiness context existed.

The regression runs with the actual Gateway process role on thread zero, prepares metadata as startup does, and loads and invokes a synthetic cold tool. Both PostgreSQL cases fail on the base at readDeferredPluginMigrations / readPluginStateMigrationReadiness; both SQLite controls pass. Each case uses an independent store and plugin cache.

Real behavior proof

RAN on Linux, Node 26.13.1, PostgreSQL 17.12, with a disposable Unix-socket-only server and isolated foreground Gateways. The model endpoint is the repository's loopback OpenAI mock fixture. Configuration uses tools.profile: "full" and disables memory search.

The turn command was:

openclaw agent --agent main --session-id <isolated-session> \
  --message 'Return marker <marker>' --thinking off --json

Temporary session and marker values are placeholders above. On the base, readiness returned ready: true, the command exited 1 with the worker-only connection error, and the mock received zero requests. With the fix, eight turns completed with status: "ok", summary: "completed", and the requested marker in the reply. The SQLite control also completed eight turns.

What was not tested

No paid or external model calls, live channels, production state, TLS deployment, other server majors, or database port/upgrade workflow. The mock-backed turns prove tool construction and model reachability, not the functionality of every registered tool. PostgreSQL successful-turn latency has no baseline comparison because the base fails before model dispatch.

Verification

  • RAN: exact regression on the base: two PostgreSQL failures at the readiness read; two SQLite passes. With the fix: four passes.
  • RAN: full pnpm build, focused consumer tests including prompt-prefix stability, core and changed-test typechecks, targeted lint/format, mock-export ratchet, and git diff --check.
  • RAN: 198 focused consumer tests passed, plus four real-database regression cases. The consolidated registry suite passed 16 cases in 39.52 s including collection (about 4 s test time); its wrapper took 41.06 s. CI conformance shard 3/4 also passed all 16 cases, with 6.439 s summed per-case execution time.
  • RAN: same SQLite full-profile mock workload on the base and final source, three warmup turns then five measured fresh-session turns. CLI-to-reply median: 949 ms before, 877 ms after; ranges 863-982 ms and 801-1048 ms. This small shared-host sample is a control, not a throughput or tail-latency guarantee.
  • Simplification: reuse the existing async loader and generator. No new worker, registry, cache, or state owner. Production delta: 41 added / 29 removed lines; test, fixture, and conformance-routing delta: 128 added / 17 removed lines. The diagnostic helper move is included in those counts.

Evidence

Local autoreview of the production repair, P0-P2, reports scoped-clean. The complete option-construction and loader owners were supplied. Local autoreview of the CI inventory repair also reports scoped-clean. The current-head diagnostic only adds refusal details to an existing assertion; it changes no expected response, request, wait, retry, or production behavior.

CI inventory repair

The first CI run found 78 jobs against the scheduled 77-job cap. The regression now reuses the existing forked inspection suite. No extra host-worker inventory entry or increased limit remains. RAN the four scheduled-capacity cases and eleven conformance-routing cases: all passed.

Repeated Bun failure investigation

Both failed CI attempts tested the same merge commit. Their avatar-subscription test received ok: false:

RAN the actual scripts/ci-run-node-test-shard.mts entry with its three-file agentic-gateway-server-isolated-hosted-3 selection, Node 24.22.1 and the checksum-verified repository Bun pin, 1.4.4-canary.1+191755ec1. On base 3587df70a23, the avatar case passed three of three runs. On PR head 271b8a34a6d, it also passed three of three. The full shard had a separate terminal-subagent timeout once on each ref; these are separate outcomes, not avatar failures.

Three runs each on CI's exact main parent and tested merge ref also passed the avatar case. A further clean-home, four-CPU run reproduced the exact avatar refusal on the PR head, while its base control passed. Thus the repeated CI failure remains unclassified. No inherited-failure claim is made.

A verified main-branch snapshot contains the same test and passed it:
https://github.com/openclaw/openclaw/actions/runs/44598233217/job/135823119335

The diagnostic commit retains ok: true and the same subscribed-session payload assertion while reporting the RPC error code and message when that assertion fails. This is diagnostic evidence collection, not a claimed fix for the CI refusal. Focused lint, formatting and the gateway test typecheck pass. Equivalent temporary assertion diagnostics passed three head and three base Bun shard runs with fresh homes and four CPUs.

Current head: 649f80c3e072. Production source remains unchanged.

Current diagnostic CI result

The original avatar case passed in the same three-file Bun group, taking 2.943 s:
https://github.com/openclaw/openclaw/actions/runs/44616678138/job/135888545902

CI also advanced its main base. The pass does not establish that the assertion diagnostic repaired the historical refusal; that cause remains unclassified.

The current run is red on a different test: session-message-events.history-worker.test.ts > delivers selected-session count updates after worker overload times out:
https://github.com/openclaw/openclaw/actions/runs/44616678138/job/135888546116

The CI classifier labels this unknown with no matching job on main. RAN that exact two-file Bun group three times on base and three times on this head: all six local runs passed. These replays do not classify the CI timeout as inherited or fix it. No timeout, retry, expected response, or gate was relaxed. Merge readiness is not claimed. No merge or auto-merge was requested.

@clawsweeper

clawsweeper Bot commented Nov 19, 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 gateway Gateway runtime agents Agent runtime and tooling size: M labels Nov 19, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR loads missing plugin tools asynchronously so PostgreSQL readiness reads run through the existing worker.

Example: A PostgreSQL Gateway starts an agent turn with tools.profile set to full and a cold plugin tool.

  • Before: Readiness succeeds, but the turn fails with “PostgreSQL connections must run in a worker” before contacting the model.
  • After: Tool construction awaits worker preparation, and the turn reaches the model and completes.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with relevant Gateway behavior evidence and real-database regressions; the prior capacity defect is fixed.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied Linux CLI-to-Gateway comparison exercises full-profile cold tool construction against real PostgreSQL, records pre-model failure on base and completed turns after the fix, and includes SQLite controls; the model endpoint is a loopback fixture, so this proves construction and dispatch rather than external model or individual tool functionality.
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 healthy PostgreSQL Gateway can reject an agent turn before the model receives a request.
Reason: This maintainer-authored repair restores an existing supported workflow with a small change and no new configuration or public contract.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current PostgreSQL turn-start failure. The previous CI-capacity finding is resolved, and no introduced correctness or security defects remain; exact-head CI is still pending.

Priority: P1
Reviewed head: 271b8a34a6dc0f01d61ef0576eaec5ca0a0e68ab

Before merge

None.

Findings

None.

Agent review details

How this fits together

Agent tool assembly selects permitted plugin tools, obtains their registrations through the plugin loader, and returns bound tools for the model turn.

flowchart LR
  A[Agent turn] --> B[Async tool assembly]
  B --> C[Plugin tool resolver]
  C --> D[Existing async loader]
  D --> E[Database readiness worker]
  E --> D
  D --> F[Bound plugin tools]
  F --> G[Model request]
Loading

Technical review

Best possible solution:

Carry asynchronous construction through the existing resolver and loader while preserving synchronous callers, workspace readiness, and existing registry ownership.

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

Source inspection confirms the cold-load path reaches synchronous database readiness on the Gateway thread, and the contributor reports matching base failures; this read-only review did not execute the reproduction.

Is this the best way to solve the issue?

The patch repairs the owning construction path with the existing asynchronous loader, covers both workspace-context branches, and preserves the synchronous API without adding another state or policy owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared yielding tool construction and synchronous compatibility keeps the original intent (325c56d: Allow inference to overlap workspace preparation while keeping workspace-dependent factories gated and legacy synchronous construction available.)
  • Plugin inspection ownership and settled outcomes keeps the original intent (1a6f0c8: Keep catalog discovery responsive through asynchronous inspection without reloading settled failed owners or losing lifecycle custody.)
  • Diagnostic deduplication keeps the original intent (1762dd5: Prevent repeated tool preparation from retaining duplicate errors while preserving distinct diagnostics and per-attempt logging.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current-main failure and focused repair: The reviewed production files are unchanged between the introduction base and fetched main. Cold tool resolution still calls the synchronous loader there; this PR selects the existing asynchronous loader while retaining activate:false, owner selection, and tool policy. (src/plugins/tools.ts:482, 271b8a34a6dc)
  • Worker boundary: The loader's asynchronous runner executes readPluginStateMigrationReadinessAsync; synchronous execution skips that yielded operation and uses the synchronous readiness reader. (src/plugins/loader-runtime-core.ts:261, 271b8a34a6dc)
  • Previous finding resolved: The latest commit removes the separate PostgreSQL test and its host-worker inventory entry, consolidates its four cases into the existing forked inspection suite, and explicitly includes that suite in PostgreSQL conformance without changing capacity limits. (scripts/lib/postgres-conformance-shards.mts:8, 271b8a34a6dc)
  • Behavior evidence: The complete PR body reports isolated foreground Gateway runs on PostgreSQL 17.12: the base rejected turns before model dispatch, while eight fixed PostgreSQL turns and eight SQLite controls completed through the CLI using the loopback OpenAI fixture. The consolidated regression also reports two PostgreSQL failures on base and sixteen passing cases with the fix. (src/plugins/tools.inspection.test.ts:437, 271b8a34a6dc)
  • Existing design preserved: perf(worktrees): start first replies while checkout finishes #169136 introduced shared yielding construction while preserving synchronous compatibility and workspace readiness; fix(plugins): avoid retaining duplicate tool errors #151897 introduced diagnostic deduplication, whose implementation moves unchanged here. (src/plugins/tool-inspection-state.ts:113, 325c56d230bc)
  • Review scope and validation state: Root and applicable ancestor policies were read; no maintainer-notes directory exists. GitHub confirms the reviewed head is mergeable with CI pending and no failed check runs observed. Some historical blobs were unavailable locally; GitHub's commit patch verified the inventory repair. No target code or second reviewer was run, and the checkout remains clean. (AGENTS.md:1, 271b8a34a6dc)

Likely related people:

  • Vincent Koc: Raw commit 0947d02 adds scripts/lib/postgres-conformance-shards.mts:1 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 0947d02be82f; files: scripts/lib/postgres-conformance-shards.mts)

PR surface

Source +12, Tests +111, Other 0. Total +123 across 11 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 41 29 +12
Tests 6 127 16 +111
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 1 1 0
Total 11 169 46 +123

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.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 automation: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Affected PostgreSQL Gateways reject agent turns before model dispatch despite successful readiness.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • 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-11-19T14:24:50.917Z sha f928d7e :: needs changes before merge. :: [P2] Keep the added regression within scheduled CI capacity

Reviewed November 19, 2026, 9:43 AM ET / 14:43 UTC (Revision 2).

@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Nov 19, 2026
@VACInc

VACInc commented Nov 19, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 19, 2026
@VACInc VACInc closed this Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: M 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.

1 participant