Skip to content

fix(gateway): add GatewayClient connection pool to prevent WS reconnect flood - #85462

Closed
samson1357924 wants to merge 8 commits into
openclaw:mainfrom
samson1357924:fix/85333-gateway-client-pool
Closed

samson1357924 wants to merge 8 commits into
openclaw:mainfrom
samson1357924:fix/85333-gateway-client-pool

Conversation

@samson1357924

Copy link
Copy Markdown
Contributor

Background

Issue #85333: Doctor performance regression. Background agents call callGateway({method: "sessions.list"}) every ~500ms. Each call creates a fresh GatewayClient, which starts WS exponential backoff from 1s. When 5.20 introduced token auth for WS connections, every connection is rejected — new client → backoff from 1s → flood → event loop starvation.

Changes

src/gateway/call.ts

Added a connection pool for GatewayClient instances:

  • clientPool Map keyed by (method, token, password) — calls with the same method and auth share a connection
  • acquirePooledClient() — returns an existing live client from the pool, or creates a new one
  • releasePooledClient() — instead of stopping immediately, keeps the client alive for a 10s TTL. Subsequent calls within 10s reuse the same connection, letting the WS backoff properly converge to 30s

Modified executeGatewayRequestWithScopes() to use the pool instead of create+stop per call.

src/gateway/client.ts

Added isShutdown public getter so the pool can check liveness without reaching into the private closed field.

Testing

  • Unit tests pass: npx vitest run src/gateway/call.test.ts
  • Manual: run doctor --fix with and without patch, compare gateway log for WS flood

…ected into config

Two-part fix:

A (onboarding-plugin-install.ts): add bundled root guard in
addPluginLoadPath(). Before writing a plugin path to
plugins.load.paths, check whether it resolves to OpenClaw's
bundled plugin directory via resolvePackagedBundledLoadPathAlias.
Bundled plugins are auto-discovered and do not need a config entry.

B (repair-sequencing.ts): move maybeRepairBundledPluginLoadPaths
to the end of the repair sequence so it runs after all plugin
install/enable/auto-enable mutations are complete. Without this,
plugin repair steps could re-add the bundled path after the
mid-sequence cleanup, leaving a dirty config to be persisted.

References: openclaw#85334
…ct flood

Repeated callGateway calls each created a fresh GatewayClient then
stopped it immediately. Each new client started WS exponential backoff
from 1s, so background agents polling sessions.list (~2/sec) never
let backoff converge to 30s, creating a sustained auth flood.

Fix: pool GatewayClients by (method + token + password) key.
acquirePooledClient() reuses a live client from the pool.
releasePooledClient() keeps the client alive for 10s TTL then cleans
up, letting WS backoff converge properly.

Also adds GatewayClient.isShutdown public getter for pool liveness
check without reaching into the private closed field.

References: openclaw#85333
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime commands Command implementations size: M triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 22, 2026
@clawsweeper

clawsweeper Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

Latest ClawSweeper review: 2026-05-22 17:53 UTC / May 22, 2026, 1:53 PM ET.

Workflow note: Future ClawSweeper reviews update this same comment in place.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

Summary
The branch adds a global GatewayClient pool in src/gateway/call.ts/src/gateway/client.ts and also carries JSON read-retry plus bundled-plugin doctor/onboarding repair changes.

Reproducibility: yes. for the PR defects from source inspection: current main forwards abort/accepted callbacks and stops each client, while the PR returns pooled clients with one-shot callbacks and no teardown. No live upgraded doctor reproduction or after-fix proof was provided for the original regression.

PR rating
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🧂 unranked krab
Summary: Missing real behavior proof plus blocking lifecycle, security-context, and availability defects make this PR not quality-ready.

Rank-up moves:

  • Post redacted before/after openclaw doctor --fix output or gateway logs from the same upgraded setup, removing private endpoints, tokens, IPs, phone numbers, and other private details.
  • Replace the global pool with a scoped design that preserves full gateway context, per-request callbacks, abort behavior, and teardown semantics.
  • Split unrelated JSON and doctor/plugin-load-path changes out of this gateway PR.
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Real behavior proof
Needs real behavior proof before merge: The PR body has unchecked testing boxes and no after-fix terminal output, logs, recording, screenshot, or linked artifact; the contributor should add redacted before/after doctor --fix or gateway-log proof and update the PR body to trigger re-review, or ask a maintainer to comment @clawsweeper re-review.

Risk before merge

  • A later same-key call can reuse a GatewayClient whose onHelloOk closure belongs to an already-settled earlier call, causing the new request to time out or open extra sockets instead of sending its method.
  • The pool key omits URL, TLS fingerprint, scopes, device identity, approval runtime token, client mode/name, instance id, and protocol bounds, so reuse can cross security and compatibility contexts.
  • releasePooledClient leaves one-shot CLI WebSockets and timers alive after callGateway resolves, which can keep processes open and accumulate reconnecting clients.
  • The PR removes current abort and accepted-callback forwarding used by agent command cancellation, so interrupted gateway runs may not be aborted correctly.
  • The branch mixes gateway pooling with JSON and doctor/plugin repairs, and the JSON retry portion is already present on current main, increasing merge/rebase risk without proving the stated fix.

Maintainer options:

  1. Redesign scoped gateway reuse (recommended)
    Preserve the current callGateway contract by keying any reusable object on the full target/auth/scope/protocol context and giving each call its own request callbacks and abort handling.
  2. Require upgraded-environment proof
    Ask for redacted before/after openclaw doctor --fix output or gateway logs from the same 2026.5.19 to 2026.5.20 upgrade path before accepting the root-cause and fix claim.
  3. Split or pause the mixed branch
    If the branch continues to include JSON and doctor/plugin repairs, pause this PR or replace it with a narrow gateway-only fix so unrelated behavior does not ride along.

Next step before merge
Needs contributor real behavior proof and a maintainer-owned gateway lifecycle/auth design decision before repair or merge.

Security
Needs attention: The diff introduces an auth-sensitive connection pool whose key omits security-relevant gateway context.

Review findings

  • [P1] Do not reuse a settled one-shot GatewayClient — src/gateway/call.ts:58-59
  • [P1] Include the full gateway context in the pool key — src/gateway/call.ts:53-54
  • [P1] Preserve abort and accepted callbacks — src/gateway/call.ts:711-714
Review details

Best possible solution:

Replace the global pool with a narrow gateway lifecycle fix that preserves per-request callbacks, teardown, and the full connection/security context, then add focused lifecycle tests plus redacted before/after doctor --fix gateway proof.

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

Yes for the PR defects from source inspection: current main forwards abort/accepted callbacks and stops each client, while the PR returns pooled clients with one-shot callbacks and no teardown. No live upgraded doctor reproduction or after-fix proof was provided for the original regression.

Is this the best way to solve the issue?

No; this is not the best way to solve the issue because a global GatewayClient pool does not preserve the existing connection, auth, and request lifecycle contract. A scoped reusable transport or caller-level throttling fix with tests and live proof would be safer.

Label justifications:

  • P1: The PR targets an urgent doctor/gateway regression but currently risks breaking core gateway calls, cancellation, and process availability.
  • merge-risk: 🚨 compatibility: The pool changes callGateway from per-call clients to global reuse and drops current abort/accepted request options.
  • merge-risk: 🚨 security-boundary: The pool key omits security-relevant gateway context such as target URL, TLS pin, scopes, device identity, and approval token.
  • merge-risk: 🚨 availability: The no-op release path can leave WebSocket clients and reconnect/tick timers alive after one-shot CLI calls finish.
  • rating: 🧂 unranked krab: Current PR rating is 🧂 unranked krab because proof is 🧂 unranked krab, patch quality is 🧂 unranked krab, and Missing real behavior proof plus blocking lifecycle, security-context, and availability defects make this PR not quality-ready.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body has unchecked testing boxes and no after-fix terminal output, logs, recording, screenshot, or linked artifact; the contributor should add redacted before/after doctor --fix or gateway-log proof and update the PR body to trigger re-review, or ask a maintainer to comment @clawsweeper re-review.

Full review comments:

  • [P1] Do not reuse a settled one-shot GatewayClient — src/gateway/call.ts:58-59
    GatewayClient stores onHelloOk in constructor options, so returning an existing live client reuses the callback closure from the first call. A later same-key callGateway promise gets no fresh request callback; start() will open another socket on the same instance and the new wrapper can only time out instead of sending its method.
    Confidence: 0.94
  • [P1] Include the full gateway context in the pool key — src/gateway/call.ts:53-54
    The key only includes method/token/password, but the client is constructed with URL, TLS fingerprint, scopes, device identity, approval runtime token, client mode/name, instance id, and protocol bounds. Reusing across any of those differences can route a call through the wrong target or authorization context.
    Confidence: 0.93
  • [P1] Preserve abort and accepted callbacks — src/gateway/call.ts:711-714
    Current main forwards signal and onAccepted into GatewayClient.request, and agent-via-gateway relies on that to track accepted runs and abort them on process signals. The PR drops those options, so interrupted accepted gateway runs can keep running.
    Confidence: 0.91
  • [P1] Do not leave per-call CLI clients open indefinitely — src/gateway/call.ts:74-79
    releasePooledClient no longer stops the client after the wrapper promise settles. Current main waits for teardown before resolving; with this no-op release, one-shot CLI calls can leave WebSockets, tick timers, and reconnect loops alive after the command should be done.
    Confidence: 0.9
  • [P2] Actually enforce the pool size cap — src/gateway/call.ts:62-71
    When the map is at capacity and all entries are still live, this loop deletes nothing and clientPool.set() adds another key anyway. Diverse method/auth combinations can therefore grow past the advertised cap.
    Confidence: 0.88

Overall correctness: patch is incorrect
Overall confidence: 0.93

Security concerns:

  • [high] Pool key omits security context — src/gateway/call.ts:54
    Pooling only by method/token/password can reuse a client across different URL, TLS fingerprint, scopes, device identity, approval runtime token, mode, and protocol bounds, weakening the intended gateway authorization and target isolation.
    Confidence: 0.93

What I checked:

  • PR pool implementation: The PR adds a module-global pool keyed only by method/token/password, returns any live existing client, and makes release a no-op. (src/gateway/call.ts:53, 588af8b1536c)
  • Current per-call lifecycle: Current main creates a fresh client, passes abort/accepted request options, and stops the active client before settling the wrapper promise. (src/gateway/call.ts:727, c9b17c51427e)
  • PR drops request callbacks: The PR's request path only passes expectFinal and timeoutMs, omitting current signal and onAccepted forwarding used by agent CLI abort/status flows. (src/gateway/call.ts:711, 588af8b1536c)
  • GatewayClient start semantics: GatewayClient.start() creates a new WebSocket for the instance, while successful connect dispatches the constructor-time onHelloOk callback, so reusing an instance does not give each later call its own request callback. (src/gateway/client.ts:304, 588af8b1536c)
  • Current abort/accepted consumers: Current main's agent gateway CLI uses GatewayRequestFunction and onSignalAbort/accepted-run handling to abort accepted gateway runs on process signals. (src/commands/agent-via-gateway.ts:319, c9b17c51427e)
  • Related issue context: The linked report describes a 2026.5.20 openclaw doctor --fix regression, but the PR body has unchecked unit/manual testing boxes and no redacted before/after doctor or gateway-log proof.

Likely related people:

  • Peter Steinberger: Blame for current callGateway lifecycle lines and recent gateway/client history point to this person as the most active owner of the affected code path. (role: recent area contributor; confidence: high; commits: a54a8813bf22, e510042870cf, b2e7fb01a926; files: src/gateway/call.ts, src/gateway/client.ts)
  • Vincent Koc: Git history shows recent credential and runtime seam work near the gateway authentication surface this pool would reuse. (role: adjacent gateway credential contributor; confidence: medium; commits: 935bd6de7fcb, 87b2a6a16aa2, c109a7623b13; files: src/gateway/call.ts, src/gateway/client.ts)
  • Josh Avant: History includes gateway token fallback, reconnect behavior, and SecretRef credential work that overlaps the security context omitted from the proposed pool key. (role: adjacent auth/reconnect contributor; confidence: medium; commits: a76e81019333, 25252ab5ab15, 806803b7efe2; files: src/gateway/call.ts, src/gateway/client.ts)
  • Tak Hoffman: History shows a focused gateway client request-timeout/lifecycle change relevant to pooling and pending request behavior. (role: gateway lifecycle contributor; confidence: medium; commits: 5fc43ff0ecd8; files: src/gateway/call.ts, src/gateway/client.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against c9b17c51427e.

@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels May 22, 2026
@clawsweeper

clawsweeper Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@social5h3ll

Copy link
Copy Markdown

Reviewed on behalf of Argus.

Core fix is sound — the connection pool correctly solves the WS reconnect flood. The guard and TTL unref pattern are right.

Gaps worth addressing:

  • No unit tests for the pool itself — the core fix has zero dedicated tests. The PR description references vitest but there's no . At minimum: same key reuse, different key → different client, TTL cleanup, in-flight protection.
  • Unbounded Map growth — no size cap on . Consider a to prevent unbounded growth under diverse multi-session usage.
  • TTL race — the 10s timer can fire while a request is still in-flight and close the connection. Consider tracking in-flight request count per client before allowing TTL close.
  • JSON retry component — the retry layer is a separate fix bundled into this PR. Worth splitting out to keep scope clean.

Overall: solid fix, needs tests and a pool size cap to be merge-ready.

- Add CLIENT_POOL_MAX_SIZE=64 to prevent unbounded Map growth
- Remove TTL-based cleanup (TTL race with in-flight requests)
- Pool entries live until disconnected; stale entries evicted on acquire
- Addresses PR openclaw#85462 review feedback from Argus
@samson1357924

Copy link
Copy Markdown
Contributor Author

Addressed review feedback:

  1. Pool size cap: Added CLIENT_POOL_MAX_SIZE=64. When at capacity, evicts one shutdown entry on the next acquirePooledClient call.

  2. TTL race removed: Removed the 10s TTL timer in releasePooledClient. Pool entries now live until the underlying connection disconnects (triggering isShutdown). Stale entries are cleaned up lazily on the next acquirePooledClient call. This eliminates the race where a timer could close a connection mid-request.

  3. Tests: Will add unit tests in a follow-up PR — the existing call.test.ts relies on dependency injection (gatewayCallDeps) which requires some refactoring to expose pool behavior for testing.

@samson1357924

Copy link
Copy Markdown
Contributor Author

This PR is now also available as fix/A5 (A5 = WS reconnect flood) per the new unified naming convention on #85333.

@samson1357924

Copy link
Copy Markdown
Contributor Author

Withdrawing — code review discovered a critical bug:

Problem: acquirePooledClient reuses existing GatewayClient instances, but client.request() is embedded inside the onHelloOk lifecycle callback. onHelloOk fires only once during initial WS handshake, so pooled clients never actually send requests — they hang until timeout.

This causes silent performance degradation (requests timing out) rather than the intended WS flood prevention.

The pool design needs to be fundamentally rethought so that client.request() can be called independently of onHelloOk. See issue #85333 comment thread for full analysis.

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

Labels

commands Command implementations gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants