Skip to content

fix(gateway): keep CLI tools working after caller scope closes - #150339

Merged
steipete merged 1 commit into
mainfrom
upd/restart-stale-async-scope
Sep 16, 2026
Merged

steipete merged 1 commit into
mainfrom
upd/restart-stale-async-scope

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes #146265: Claude CLI tool calls can keep failing with Async work scope is closed after the turn that first started the shared MCP listener finishes. Related: #144788.

The original restart-race/shared-DB-pool diagnosis was withdrawn by the reporter after an instrumented trace identified the MCP HTTP listener retaining a heartbeat turn's closed scope: #146265 (comment).

User Impact

User impact: later Claude CLI turns keep using bundled and plugin tools after an earlier heartbeat, cron, or user turn finishes. Listener shutdown also waits for accepted tool cleanup, including cleanup that outlives the HTTP response.

Why This Change Was Made

The lazy MCP listener now owns its async work scope until Gateway shutdown and does not inherit the first caller's root admission. Cached tools are constructed under that listener lifetime; hooks and each tool execution run in a fresh request scope through the existing cancellation helper. Existing grant checks after discovery and before execution remain in place.

The listener stops accepting HTTP requests before its work scope drains, and failed startup also drains its scope. An active listener therefore cannot remain bound to a closed work scope, so there is no new health branch or speculative failure projection. Old runtime grants retain their existing revocation behavior.

This is distinct from #148089 (deferred session lifecycle hooks) and #148025 (deferred followup-queue drains), and from #144788's post-ack webhook continuation. None of those changes owns the shared MCP HTTP listener.

Thanks to @marieldejesus12 for the instrumented scope trace and @josepeluso for the Claude/Gemini comparison with unchanged Home Assistant configuration.

Evidence

Real loopback HTTP listener, JSON-RPC dispatch, tool cache, and real async scopes; the synthetic tool performs tracked work. No live Claude/model service or operator Gateway is needed for the regression.

Before the production change:

node scripts/run-vitest.mjs src/gateway/mcp-http.async-scope.test.ts

FAIL creator closes, original listener
FAIL creator closes, replacement listener
  Expected: tracked tool completed / isError=false
  Received: Async work scope is closed / isError=true
FAIL accepted cleanup remains owned while a replacement listener serves
  Expected close still pending; received close completed
Tests 3 failed (3)

After:

node scripts/run-vitest.mjs src/gateway/mcp-http.async-scope.test.ts src/gateway/mcp-http.test.ts src/shared/async-work-scope.test.ts

Gateway: 127 passed (127)
Async work scope: 9 passed (9)
Total: 136 passed; 45.91s

The new tests also prove cached tool construction retains the listener scope, separate executions receive distinct scopes, closing the creator's root admission does not poison later calls, and predecessor cleanup cannot close a successor listener. The earlier replacement control was already green; the committed regression extends it by closing the replacement's creator before invoking its tools.

node scripts/check-changed.mjs -- src/gateway/mcp-http.ts src/gateway/mcp-http.async-scope.test.ts passed in full, including core/test typechecks, line-cap guards, export scans, lint, and runtime import-cycle checks. Independent Codex review with --mode branch --base origin/main --max-priority P1 is scoped-clean with no actionable P0/P1 findings.

Production: +32/-12 lines (net +20). Tests: +155 lines. The added production lines assign and drain the serving owner, isolate request cancellation, and clean up failed startup. Lazy import boundaries remain unchanged; no build was run. No live Windows/Claude, full Gateway restart-race, or published-updater run is claimed; the repair changes the candidate runtime's MCP serving lifetime and needs no driver marker or data migration.

Sibling scope-capture inventory and dispositions

The DB/worker owners already capture each operation: worker-task-pool.ts:111 (dispatch restoration at :246, reply restoration at :272), sqlite-worker-client.ts:103, and sqlite-worker-operation-admission.ts:36. The adjacent src/mcp/tools-stdio-server.ts:22,31-32,47-49,75-77 already gives its server/request work explicit lifetimes.

The following background captures retain their existing contracts. A follow-up audit can check import-time context selection, but none was shown to bind later tool admission to a closed scope, so they are not changed here.

Capture Disposition and retained responsibility
src/infra/sqlite-worker-broker.ts:58 Retain native Worker construction context; admission is per operation.
src/infra/worker-task-pool.ts:21 Retain Worker creation/idle retirement; each task restores its own context.
src/infra/sqlite-coordinator.ts:122 Retain idle-coordinator retirement timer; separate follow-up for import timing.
src/infra/sqlite-wal.ts:62 Retain database maintenance timer; separate follow-up for import timing.
src/infra/net/pinned-dispatcher-pool.ts:7 Retain dispatcher idle cleanup; acquisition separately validates DNS/policy.
extensions/memory-core/src/memory/background-context.ts:6 Retain eagerly imported manager watcher/listener context; separate follow-up for import timing.
src/skills/runtime/refresh.ts:63 Retain shared watcher context outside triggering turns.
src/config/sessions/session-transcript-worker-runtime.ts:192 Retain history worker idle retirement; operations have separate ownership.
src/agents/agent-bundle-mcp-manager-lifecycle.ts:22 Retain process idle-sweep timer; session admission has separate owners.
src/agents/tools/media-generate-background-shared.ts:49 Retain independently scheduled media work's AsyncResource.

Per-run captureAsyncWorkTracker closures remain exact-owner lifetime fences.

@clawsweeper

clawsweeper Bot commented Sep 16, 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 the gateway Gateway runtime label Sep 16, 2026
@steipete
steipete marked this pull request as ready for review September 16, 2026 22:15
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Sep 16, 2026
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 16, 2026
@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 16, 2026, 6:48 PM ET / 22:48 UTC (Revision 2).

ClawSweeper review

What this changes

The PR gives the shared CLI tool listener its own lifetime, isolates each tool execution’s cancellation scope, and waits for accepted cleanup during shutdown.

Merge readiness

✅ Ready for maintainer review

Keep open: this remains a useful, focused fix for a source-supported CLI tool failure that persists on the fetched main and latest release. No blocking correctness or security findings were identified.

Priority: P1
Reviewed head: a8f3b9a7b067a029a62a414d41e7ed51addf47cd

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused ownership repair with meaningful production-boundary evidence and no identified blocking defects.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The supplied before/after terminal results exercise the production MCP listener with real HTTP requests after creator-scope closure and verify replacement service plus delayed cleanup settlement; synthetic tools isolate the changed lifecycle boundary.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The supplied before/after terminal results exercise the production MCP listener with real HTTP requests after creator-scope closure and verify replacement service plus delayed cleanup settlement; synthetic tools isolate the changed lifecycle boundary.
Evidence reviewed 8 items Pinned change ownership: Host-verified introduction evidence identifies the exact base-to-head change and a test merge with the pinned main and PR head as its parents. The reviewed changes are confined to the listener and its lifecycle regression tests.
Reporter established the retained caller scope: The instrumented report traces a heartbeat scope closing and later MCP before-tool execution entering that same closed scope: #146265 (comment). Subsequent discussion also reports Claude CLI failure with unchanged Home Assistant configuration while Gemini succeeds; this supports the narrowed bridge diagnosis rather than the original shared-database hypothesis.
Main still lacks the lifetime repair: The fetched main starts the shared listener directly in the caller’s context and closes only the HTTP server; it lacks the listener-owned scope and accepted-cleanup drain introduced here.
Findings None None.
Security None None.

How this fits together

OpenClaw’s local MCP HTTP listener exposes Gateway tools to CLI backends through authenticated requests. It resolves permitted tools, executes them, and returns results while tracking their cleanup.

flowchart TD
  A[CLI backend request] --> B[Bearer and grant checks]
  B --> C[Listener lifetime and tool cache]
  C --> D[Independent execution scope]
  D --> E[Tool result to CLI]
  D --> F[Accepted cleanup]
  G[Gateway shutdown] --> H[Close listener and drain work]
  F --> H
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +20, Tests +155. Total +175 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 32 12 +20
Tests 1 155 0 +155
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 187 12 +175

Review metrics

Metric Value Why it matters
Lifetime ownership footprint Production net +20 lines; tests +155 lines Production growth assigns and drains the serving lifetime using existing scope primitives rather than adding a second lifecycle mechanism.

Technical review

Best possible solution:

Keep lifetime ownership with the shared listener and its individual executions while preserving per-run authorization and the existing closed-scope fences.

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

Yes: start the listener inside a caller scope, close that scope, then invoke a tracked tool over HTTP. Source inspection and the supplied before/after results establish this path; this read-only review did not execute it.

Is this the best way to solve the issue?

Yes: the patch repairs the serving owner and reuses existing cancellation primitives without weakening closed-scope rejection or adding configuration, persistent state, or a parallel API.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: Reported CLI workflows repeatedly lose bundled and plugin tool execution after an earlier caller scope closes.
  • 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. Sufficient (terminal): The supplied before/after terminal results exercise the production MCP listener with real HTTP requests after creator-scope closure and verify replacement service plus delayed cleanup settlement; synthetic tools isolate the changed lifecycle boundary.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied before/after terminal results exercise the production MCP listener with real HTTP requests after creator-scope closure and verify replacement service plus delayed cleanup settlement; synthetic tools isolate the changed lifecycle boundary.

Evidence

What I checked:

  • Pinned change ownership: Host-verified introduction evidence identifies the exact base-to-head change and a test merge with the pinned main and PR head as its parents. The reviewed changes are confined to the listener and its lifecycle regression tests. (src/gateway/mcp-http.ts:528, a8f3b9a7b067)
  • Reporter established the retained caller scope: The instrumented report traces a heartbeat scope closing and later MCP before-tool execution entering that same closed scope: [Bug]: After gateway restart, shared AsyncWorkScope stays closed process-wide — all DB/Fleet agent tools fail "Async work scope is closed" while gateway health reports OK #146265 (comment). Subsequent discussion also reports Claude CLI failure with unchanged Home Assistant configuration while Gemini succeeds; this supports the narrowed bridge diagnosis rather than the original shared-database hypothesis.
  • Main still lacks the lifetime repair: The fetched main starts the shared listener directly in the caller’s context and closes only the HTTP server; it lacks the listener-owned scope and accepted-cleanup drain introduced here. (src/gateway/mcp-http.ts:517, 75ba5e3fae5c)
  • Latest release retains the affected startup pattern: The supplied latest release, v2026.9.4, likewise starts the listener directly without an independent work scope. This review does not establish a shipped fix. (src/gateway/mcp-http.ts, 3a9d69db306c)
  • Production boundary proof: The captured PR body reports three failing pre-fix scenarios and 136 passing checks after the repair. The inspected regression uses real fetch requests, the production HTTP listener, JSON-RPC dispatch, tool cache, and async scopes, with synthetic tool resolution and hooks. It verifies recovery after creator closure, replacement-listener recovery, and cleanup that outlives the response. No live Claude or Windows execution is claimed. (src/gateway/mcp-http.async-scope.test.ts:54, a8f3b9a7b067)
  • Cancellation and authority remain separate: The existing cancellation helper retains cleanup under its parent while returning the tool result independently. The listener still checks grant liveness after discovery, and the handler checks it after awaited preparation/hooks immediately before tool execution; runtime grant revocation and cache eviction remain intact. (src/gateway/mcp-http.handlers.ts:225, a8f3b9a7b067)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

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 (1 earlier review cycle)
  • reviewed 2026-09-16T22:22:43.992Z sha e037444708ac900745003cd96d04db11cb0a0e32 :: needs maintainer review before merge. :: none

Give the shared MCP HTTP listener its own work lifetime and each tool call
an independently tracked request scope. Stop HTTP admission before joining
listener cleanup so late work cannot poison a successor listener.

Fixes #146265. Related: #144788.
Thanks to marieldejesus12 for the instrumented scope trace and josepeluso
for the Claude/Gemini comparison with unchanged plugin configuration.
@steipete
steipete force-pushed the upd/restart-stale-async-scope branch from e037444 to a8f3b9a Compare September 16, 2026 22:40
@steipete
steipete merged commit 3072557 into main Sep 16, 2026
205 checks passed
@steipete
steipete deleted the upd/restart-stale-async-scope branch September 16, 2026 23:05
@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 17, 2026
…law#150339)

Give the shared MCP HTTP listener its own work lifetime and each tool call
an independently tracked request scope. Stop HTTP admission before joining
listener cleanup so late work cannot poison a successor listener.

Fixes openclaw#146265. Related: openclaw#144788.
Thanks to marieldejesus12 for the instrumented scope trace and josepeluso
for the Claude/Gemini comparison with unchanged plugin configuration.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR 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. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

1 participant