Skip to content

fix: avoid disconnects and delays during hosted tool calls - #146369

Merged
steipete merged 6 commits into
mainfrom
codex/direct-gateway-dispatch
Sep 12, 2026
Merged

steipete merged 6 commits into
mainfrom
codex/direct-gateway-dispatch

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes #100941. Related: #146226.

What Problem This Solves

Fixes an issue where agents running inside the Gateway could stall or receive connection errors while making parallel automation, node, approval, question, message, and session calls. Many of these operations opened a fresh WebSocket back to the same process for each request. Cleanup and memory/session lookups contained the same avoidable round trips.

Why This Change Was Made

Hosted tools use the existing in-process Gateway router with the same validated runtime identity, method scopes, approval correlation, cancellation, deadlines, and current-run/current-Gateway checks. Runtime identity preparation is shared with the transport path without signing and decoding a token for an internal call. Explicit remote destinations and standalone/localEmbedded clients retain transport.

Detached cron and subagent cleanup uses the existing instance-owned recovery principal, with a narrow method allowlist and commit guards. Cleanup can finish after the originating turn ends, but cannot borrow a replacement Gateway. Message delivery still passes through the Gateway's delivery, receipt, and idempotency owners; a timed-out send reattaches once with its original key. Memory visibility, command SecretRef resolution, and hosted Doctor data reads use bound routing as well. Doctor retains actual connection-health probes.

User Impact

Hosted operations avoid repeated connection setup and authentication, especially during parallel tool calls and multi-step node commands. The Gateway-to-node connection remains necessary; the redundant agent-to-own-Gateway hop is removed. Existing caller authority, delivery outcomes, session protections, and remote targeting remain enforced.

Evidence

  • Routing regressions fail on the old code and pass on the candidate, including the actual message-tool entry point and Gateway router. Covered cases include explicit remote targets, cancellation, expired run/operator authority, retired Gateway bindings, and cleanup revocation before commit.
  • Focused node/automation/question/approval, runtime identity, session lifecycle, visibility, command secrets, outbound delivery, and send reconciliation suites pass. Hosted send/poll and message actions exercise the bound request path without opening a Gateway connection.
  • A synthetic warm routing benchmark ran 100 node discovery/preparation/invocation sequences: 300 calls took 1.561 seconds with 300 sockets before, and 0.0122 seconds with zero sockets after. Process RSS was 593.4 MB before and 583.3 MB after. This isolates routing overhead and is not an end-to-end model or provider latency claim.
  • Independent integrated review and the Doctor follow-up review are scoped-clean through P2. The complete normal build, including all Doctor changes, passed in 7m01s. Core/extension production and test types passed; the final Doctor commands test type graph also passed after correcting its async fixture contract. All selected changed-gate stages completed across recorded runs after fixing test lint and shrinking assertion allowances. No live Gateway was restarted or reconfigured.
  • The final combined routing run passed 50 tests; the final helper/routing rerun passed 80. Doctor adds five red-before/green-after entry-point regressions, with 226 focused owner tests passing. These counts cover separate runs and are not an unduplicated full-suite total. Full exact-head CI remains a merge gate.
  • CI exposed a canceled-collector cleanup path that cleared its inherited Gateway binding, opened transport, and kept running into later fixtures. Cleanup now distinguishes inherited scope from explicitly transferred or unbound ownership. In the original spawn-then-retirement order on Linux Node 24.19, the old code produced four failures and 118 device-directory writes under later fixtures; the repair passed all 42 tests with zero such writes, without changing retirement fixtures, counts, or timeouts. The final cleanup owner suites (75 cases) and registry suite (166 cases), types/lint, and independent P2 reviews passed. Linux reproduction.
  • The next CI run exposed an unrelated startup fixture choosing a port from Linux's outgoing-connection range and losing it before Gateway bind. That fixture now uses the existing deterministic safe-port allocator; its assertions and timeout are unchanged. The fixture, selected checks, and independent P2 review pass. The branch was refreshed onto the canonical TLS-sidecar repair (fix(gateway): register TLS renewal with sidecar owner #146412), with all six task commits verified patch-identical. Hosted routing and lifecycle/startup proof on the refreshed base passed 30 cases. Required CI for the refreshed head remains the landing gate.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes commands Command implementations agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 12, 2026
@steipete
steipete marked this pull request as ready for review September 12, 2026 19:38
@clawsweeper

clawsweeper Bot commented Sep 12, 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.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 12, 2026, 5:36 PM ET / 21:36 UTC (Revision 3).

ClawSweeper review

What this changes

Routes hosted tool calls, message operations, session cleanup, and Doctor reads through their owning Gateway without opening redundant WebSocket connections.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: current main still has the redundant transport path, and this PR provides a coherent fix. No introduced blocking correctness defect was found; the earlier generic migration warning is unsupported by the diff.

Priority: P1
Reviewed head: 65062563076b5e81238b9140d76e14d2e372c90f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent owner-level repair with meaningful regression coverage and no blocking code finding.
Proof confidence 🌊 off-meta tidepool Not applicable: The ordinary contributor-proof gate is exempt for this maintainer-authored PR. The body reports hosted routing and cleanup observations, and source inspection found no unresolved authority violation requiring the exception; Doctor upgrade validation remains a separate repository gate.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary contributor-proof gate is exempt for this maintainer-authored PR. The body reports hosted routing and cleanup observations, and source inspection found no unresolved authority violation requiring the exception; Doctor upgrade validation remains a separate repository gate.
Evidence reviewed 11 items Pinned introduction boundary: Reviewed the merge-base-to-head changes from b405e7f to 6506256. The host-verified test merge preserves base-only Slack changes; those changes are not attributed to this PR.
Still necessary on current main: The inspected main version of callGatewayTool still dispatches through callGateway. The merged config-read fix at #146226 covers a narrower surface and does not supersede the broader hosted-call cutover.
Latest release retains transport: The v2026.9.4 source also delegates these calls to callGateway; the central change is not already shipped in the supplied latest release.
Findings None None.
Security None None.

How this fits together

The Gateway coordinates agent tools, approvals, messages, and session operations. This change routes requests originating inside it through the existing router while preserving transport for standalone callers and explicit destinations.

flowchart TD
  A[Hosted tools and cleanup] --> B{Dispatch destination}
  C[Standalone or explicit destination] --> B
  B -->|Hosted| D[Bound caller and Gateway authority]
  B -->|External| E[WebSocket client]
  D --> F[Gateway authorization and router]
  E --> F
  F --> G[Tool results and owned side effects]
Loading

Before merge

  • Resolve merge risk (P1) - The supplied published-updater validation covers the TLS parent candidate, leaving this branch's changed Doctor import and dispatch paths unverified during upgrade.
  • Complete next step (P2) - Add or link a published-updater × candidate result covering this branch's Doctor changes with existing operator state; no database migration is indicated.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +434, Tests +1277, Docs +6, Other -1. Total +1716 across 79 files.

View PR surface stats
Area Files Added Removed Net
Source 40 671 237 +434
Tests 37 1622 345 +1277
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 2 -1
Total 79 2300 584 +1716

Review metrics

Metric Value Why it matters
Production versus regression coverage Production net +434 lines; tests and test support net +1,277 lines Production growth supports the stated authority-preserving routing cutover; most growth is regression coverage.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-device-pairing.ts, migration/backfill/repair: src/commands/doctor-gateway-health.ts, migration/backfill/repair: src/flows/doctor-core-checks.ts, migration/backfill/repair: src/flows/doctor-health-contributions-final.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #100941
Summary: This PR is the candidate fix for the canonical redundant-connection report; the earlier config-only fix overlaps but does not replace it.

Members:

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

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep one hosted dispatch owner with existing authority and delivery contracts, and establish that Doctor remains usable through the published updater with existing operator state.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep one hosted dispatch owner with existing authority and delivery contracts, and establish that Doctor remains usable through the published updater with existing operator state.

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

Yes for the redundant connection mechanism: current-main hosted calls still reach the transport client. The historical 1006 failure rate was not reproduced during this read-only review.

Is this the best way to solve the issue?

Yes: extending the existing bound router removes the redundant hop while retaining authorization, destination selection, and delivery ownership; no separate connection pool is needed.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: The linked report documents failed parallel tool calls and lost completion delivery in active agent workflows.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The ordinary contributor-proof gate is exempt for this maintainer-authored PR. The body reports hosted routing and cleanup observations, and source inspection found no unresolved authority violation requiring the exception; Doctor upgrade validation remains a separate repository gate.

Evidence

What I checked:

  • Pinned introduction boundary: Reviewed the merge-base-to-head changes from b405e7f to 6506256. The host-verified test merge preserves base-only Slack changes; those changes are not attributed to this PR. (65062563076b)
  • Still necessary on current main: The inspected main version of callGatewayTool still dispatches through callGateway. The merged config-read fix at fix(gateway): avoid loopback connections for embedded config reads #146226 covers a narrower surface and does not supersede the broader hosted-call cutover. (src/agents/tools/gateway.ts, 9b59fe4ef7da)
  • Latest release retains transport: The v2026.9.4 source also delegates these calls to callGateway; the central change is not already shipped in the supplied latest release. (src/agents/tools/gateway.ts, 3a9d69db306c)
  • Bound routing and live authority: The request binder captures caller context and the admitted Gateway, rejects replacement, and preserves standalone/localEmbedded transport. Direct runtime identities reuse the existing payload validation and live delegated-authority machinery. (src/agents/tools/in-process-gateway.ts:275, 65062563076b)
  • Cleanup authority reaches the mutation guard: The lifecycle adapter restricts session dispatch to history, abort, and deletion, passing current-owner assertions into the instance runtime. The existing Gateway router composes these into session authorization, and session deletion carries them through its final commit guard. (src/gateway/server-recovery-runtime-context.ts:63, 65062563076b)
  • Focused regression coverage: Inspected coverage for foreign approval requesters, revoked runs, expired operator scope, replaced Gateways, cancellation, explicit destinations, and cleanup revocation before mutation. These are supplemental tests, not a reviewer-executed production run. (src/agents/tools/gateway.hosted-routing.test.ts, 65062563076b)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Add or link published-updater × candidate evidence covering the changed Doctor paths and existing state.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-09-12T20:04:14.372Z sha 148cc81 :: blocked before merge. :: none
  • reviewed 2026-09-12T20:48:16.682Z sha d8cdf44 :: blocked before merge. :: none

@steipete
steipete force-pushed the codex/direct-gateway-dispatch branch from d8cdf44 to 6506256 Compare September 12, 2026 21:18
@steipete
steipete merged commit 3d926b2 into main Sep 12, 2026
189 checks passed
@steipete
steipete deleted the codex/direct-gateway-dispatch branch September 12, 2026 21:48
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
…146369)

* fix(gateway): avoid self-connections for hosted operations

* fix(doctor): dispatch hosted diagnostic reads directly

* test(doctor): preserve the asynchronous findings contract

* refactor(gateway): finish the internal transport cutover

* fix: preserve inherited Gateway binding during subagent cleanup

* test(gateway): avoid ephemeral ports during capability startup
karmafeast pushed a commit to karmaterminal/openclaw that referenced this pull request Sep 26, 2026
Put back upstream b1c68b9 content that the continuation line had
silently reverted in shared files. Every row has a keep/restore
disposition recorded in the round journal. Feature hunks are preserved.

Production:
- announce deps: use callSubagentLifecycleGateway for the wake and
  cleanup deps (openclaw#146369 inherited Gateway binding).
- reply-delivery: clear blockSourceText on superseded deferred replies
  (openclaw#143722).
- stream-rendering: record a block reply as delivered only when it has
  text (openclaw#135751).
- gateway runtime handles: carry hotReloadStatus through the managed
  reload.
- sweep-kill and sweeper: honor retired cancellations
  (reconcileRetiredSubagentCancellation), and pass the run's Gateway
  context resolver into sweep session deletes.
- registry read: per-child snapshot reads (openclaw#154727), so the Gateway
  event loop is not blocked.
- session delivery queue: read the post-enqueue status inside the SQLite
  worker instead of on the main thread, restoring the openclaw#147887 invariant.

Tests restored to upstream's coverage:
- task-registry kernel test: back to upstream's kernel functions.
- double-announce: real outbound adapter retry outcomes (openclaw#131419).
- side-question: listener-failure hooks case (openclaw#144828).
- session-delivery storage: main-thread-SQL idle assertion (openclaw#157458).
- media-only: the re-resolved auth selection assertion.
- resume persistence: activation uses the real recovery-runtime shape.

The resume "steered requester turn" test was adapted for upstream's
async task lookup (openclaw#157634). Its stub now settles like the real waker,
and the test waits for settle before an exact count, with a
no-pending-wake assertion added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Fq5EX9ESA3CG9cuZxVoKAK
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 10, 2026
…ed test lines [UNAPPROVED]

UNAPPROVED PREP CHECKPOINT. Successor to the immutable reviewed C7
a847f88 (upstream parent 401a1de unchanged; no re-pin).
Not a cut, not Mode-B accepted, no presentation motion. Gate 3 is not claimed.

Input: Frond's exact-C7 static table (openclaw#1271; MinIO
frond/shared-media/prince-handoff/2026-11-10/frond-scribe/1271-static-forkonly/
1271-j14-c7-static-20261110T201419Z.tar.zst, sha256 bdd45ab8...abb0e, verified):
25 fork-only Knip lines (31 symbols) and 44 deadcode:exports entries (41 symbols).

Each symbol is dispositioned from its real consumers at C7 (lane receipt table):
- DEAD, deleted (10): orphaned rollback rebase helpers (persistence wiring went with
  merge bdb5ecb's re-home onto upstream's async write queue), migratedEntry* (upstream
  deleted the feature in openclaw#162100; merge 6c9a459 orphaned the fork copies), an unused
  disarm reader, an unaccepted-delegate remover, the announce runtime's callGateway
  re-export (upstream removed it in openclaw#146369), and two unused test-support helpers.
- IN-FILE ONLY, export dropped (17).
- REDUNDANT RE-EXPORTS removed (5); one test now imports from the owner module.
- TEST SEAMS tagged @internal (8): Knip 6.40.0 ignores @internal only in --production,
  so the full-tree scan still audits each against its test consumers.
- DYNAMICALLY CONSUMED (1): custody-boot calls refuseStaleContinuationWorkAtReplay on a
  namespace bound by Promise.all array destructuring; config/knip-dynamic-consumers.mjs
  now models that consumer from the live source (AST, binding identity), with a test.
No file-level ignoreIssues entry, threshold or baseline is changed.

Test lines: C7 was 401 over. Exact attribution: 19 j13 residual (#1563 +20, #1562 -1),
30 upstream slack shift (U13 31 -> U14 1), 352 agent schema 41/42 coverage in 13 files.
C8 nets -4. Allocations: continuation-j14-baseline-shift.txt 30 and
continuation-j14-coverage.txt 367 (itemized). Ratchet: 6742738 = ceiling, against base
401a and against C7.

Recipient-authority behaviour is unchanged (migrateSessionRecipientAuthority gains a JSDoc
tag only; refuseStaleContinuationWorkAtReplay is unchanged and now modeled).
src/skills/** untouched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

1 participant