Skip to content

fix(mcp): recover expired SSE sessions and speed up parsing - #155497

Merged
steipete merged 1 commit into
mainfrom
codex/mcp-repair-performance
Sep 22, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/mcp-repair-performance

Conversation

@steipete

@steipete steipete commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Related: #68187

What Problem This Solves

Legacy SSE MCP servers can stay stuck after their message endpoint returns HTTP 404. The stale connection survives failed tool calls and tool-list refreshes, so later requests keep using an expired session. Large SSE responses also spend unnecessary CPU time scanning every byte in JavaScript.

User Impact

Embedded and node-host MCP runtimes retire expired SSE sessions and discover tools on a fresh connection. Failed tool calls retain their original error and are never replayed. Large HTTP/SSE responses are processed faster with the same message-size limits.

Why This Change Was Made

The SDK drops legacy SSE POST status codes into a plain error. The transport now preserves expiration as a typed error for the existing lifecycle owner, including catalog refresh. Ordinary HTTP 500 errors and stateless Streamable HTTP 404 errors remain distinct. The response limiter searches monotonically for line delimiters while preserving CR/LF, comment, and multiline-event accounting.

Evidence

  • Final exact-head CI run 35750341313 passed on f5ad38af9c0382d8e02d044c6e33e3102c7df711: 117 successful jobs, 16 skipped, zero failures, including the required CI gate and every previously failing lane. Native landing merged this head as 824ab3fead2e67d01e30d8624a0e8cae5c69d1a4.
  • Both stale-session paths have failing-before/passing-after regressions through the runtime and real MCP SDK with a synthetic fetch transport. Tests verify fresh discovery, original errors, no replay, ordinary 500 behavior, and cleanup.
  • Final focused proof: 43 tests pass across HTTP transport, embedded SSE recovery, and node-host recovery. Coverage includes split CRLF, CR-only/LF streams, comments, oversized multiline events, stateful/stateless distinctions, and DELETE 404/405/500 behavior.
  • A broader 20-file MCP sweep passed 351 tests covering runtime reuse, reloads, admission, retirement, HTTP/stdio clients, node dispatch, CLI configuration, and probe exit behavior.
  • Three interleaved baseline/candidate benchmark pairs used the real SDK callTool path, 64 KiB chunks, and 15 measured requests per size after warmup. Median-of-medians latency fell from 52.0 to 13.7 ms for 8 MiB responses (74% reduction) and 1.99 to 0.66 ms for 256 KiB responses. These are synthetic local transport measurements, not overall agent-turn latency. Peak RSS varied: baseline 396–460 MiB, candidate about 416 MiB; no memory improvement is claimed.
  • Deslop completed and independent Codex review through P2 found no actionable findings. Final changed-file gates passed, including core and test typechecks, scoped lint, dead-export scans, and runtime import-cycle guards; both changed documentation pages passed formatting checks.
  • Measured individual pnpm test <file> --maxWorkers=1 wall times: HTTP transport 13.68 seconds (22 tests), embedded SSE recovery 12.26 seconds (4 tests), and node-host recovery 14.06 seconds (17 tests). Their test bodies took about 650 ms, 41 ms, and 1.8 seconds respectively. Cold graph preparation dominates command time. New cases reuse existing fixtures or an in-memory transport; no per-test Gateway/process boots or real sleeps were added. Hosted CI selected the broad core/SDK fallback. In CI run 35731555320, rounded case durations totaled 660 ms for the 22 HTTP cases, 29 ms for the four embedded SSE cases, and 1.384 seconds for the 17 node recovery cases. Their successful covering jobs took 624 seconds (HTTP and embedded) and 694 seconds (node), including other files and setup; standalone CI file wall times were not available.
Previous CI failures and remaining proof limits

Earlier runs exposed shared fixture and tooling failures. The base includes the canonical placement-clock repair (#155530), SSH pairing-order repair (f87f23c483b4c5130f42f2451f0b03e36ea0effe), and typed CLI-shim contract (80b9608a25e191a17e1466d750c2f76a38a38507). The MCP patch retains the same stable patch ID across refreshes.

Run 35719486744 observed a started Gateway delivery after its 15-second assertion window. The base includes the readiness change 9a7984ef3daee304a4b684961964ddfbe687b7ff; that shard passed in the following MCP run. Our earlier original 23-file/325-test Linux replay and one diagnostic run also passed, the latter settling 7.038 seconds after release. Those were non-reproductions, not root-cause proof; Testbox RAM was 16.56 GB versus CI's 8.22 GB. No timeout or assertion was changed, and diagnostic edits were reverted.

Run 35731555320 passed the MCP test jobs and the Gateway delivery shard, but two archive-placement cases failed their one-second readiness poll and left unjoined requests that later reported revoked reads. The current base contains the owning repair #155751 and the related terminal-persistence fixture correction in bb2d479926adb23fb30737e2fd3e5af63969dc84 (#152057). An equivalent local placement correction independently changed a pristine-main result of 2 failures / 22 passes / 2 unhandled errors into 24 passes with no unhandled errors, and passed selected checks and independent review; it was superseded without duplicate publication. The canonical archive repair's original 40-file replay retained one unexplained auth-refresh root-count failure, while its selected hosted CI passed. Earlier passing executions do not erase those historical limitations.

Run 35739216555 on fc2e52a54492efd1ccc3b8347ca774a973b073ce passed both previously failing Gateway shards and production types. Its sole test failure included cold memory-reader startup in a one-second fixture assertion. The current base contains the canonical correction from #155745 (5c9d100c72a08cbc0c3d1f09e5590ec27bd8d8e5): it queues a read barrier after both candidate lookups and verifies their public completion before releasing the held rebuild, with provider-entry and cancellation cleanup. On immutable canonical main, all three fixture cases passed; restoring the historical blocking await made both startup variants fail the intended post-barrier assertion, with no timeout or unhandled error. The external proof driver's summary-count check misread Vitest's grouped trace; both named failures were independently qualified from the retained output without rerunning. The alternative warm-reader PR #155778 was closed as superseded. This proves repair independence, not a one-second cold-start guarantee or a product startup speedup.

A separate clock-test coverage weakness was fixed on main by #155748 (092cc29d5e0a9da56c507e567a6a5edaedf3be4d). A timer-aligned control proved that the old scheduler could pass through natural timer expiration 11.816 seconds after release; moving held enqueue after readiness made that same old scheduler fail the original queue assertion, while the current scheduler passed both delayed and normal flows. All four controls, selected checks, and independent review passed. This concerns the integration test's mutation coverage, independently of the MCP boundary regressions, and does not establish the cause of the historical started-but-unsettled failure.

@clawsweeper

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

@steipete
steipete marked this pull request as ready for review September 22, 2026 05:55
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Sep 22, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 22, 2026
@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 22, 2026, 12:01 PM ET / 16:01 UTC (Revision 10).

ClawSweeper review

What this changes

Recover expired SSE tool-server connections without replaying failed calls, accelerate response scanning, and add recovery tests and documentation.

Merge readiness

✅ Ready for maintainer review

Keep open: the SSE POST-404 recovery remains missing from current main and the latest release. The introduced patch has no actionable correctness or security findings.

Priority: P2
Reviewed head: f5ad38af9c0382d8e02d044c6e33e3102c7df711

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful boundary coverage, documented benchmark limits, and no actionable findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-authored exemption applies. Embedded recovery uses the production runtime and real SDK with synthetic fetch; node recovery uses injected clients, and the reported benchmark measures synthetic SDK calls. These are not live-server proof. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored exemption applies. Embedded recovery uses the production runtime and real SDK with synthetic fetch; node recovery uses injected clients, and the reported benchmark measures synthetic SDK calls. These are not live-server proof. No stored-data contract changes.
Evidence reviewed 9 items Introduced patch boundary: Reviewed the pinned merge-base-to-head changes. Recovery extends the existing transport and lifecycle owners; unrelated base-branch work is excluded.
Current-main necessity: Current main recognizes session expiration only for stateful Streamable HTTP. Its relevant production files are unchanged from the pinned introduction base, leaving legacy SSE POST failures outside that recovery classification.
Latest-release check: The supplied latest release, v2026.9.5, also contains only the stateful Streamable HTTP expiration predicate; this SSE repair is not established as shipped.
Findings None None.
Security None None.

How this fits together

OpenClaw’s MCP clients discover and call tools on external servers for embedded agents and paired node hosts. The HTTP transport reports failures to the existing lifecycle owners, which retire connections and refresh available tools.

flowchart TD
  A[Agent or node tool request] --> B[MCP HTTP transport]
  B --> C[External tool server]
  C --> D[Bounded response scanning]
  C --> E{Session expired?}
  D --> F[Tool result]
  E -->|Yes| G[Retire connection and report failure]
  G --> H[Fresh connection and tool discovery]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +41, Tests +227, Docs +5. Total +273 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 4 62 21 +41
Tests 3 366 139 +227
Docs 2 6 1 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 434 161 +273

Review metrics

Metric Value Why it matters
Production versus test growth Production net +41 lines; tests net +227 lines Production growth implements typed expiration reporting and faster bounded scanning within existing owners; most growth covers recovery and parsing regressions.

Technical review

Best possible solution:

Keep session replacement within the existing lifecycle owners, preserving original failures, no automatic replay, and bounded response parsing.

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

Yes, from source: an established legacy SSE connection whose message POST returns 404 produces a plain SDK error that current main does not classify as session expiration. No runtime reproduction was executed during this review.

Is this the best way to solve the issue?

Yes. Preserving the transport error’s type lets both existing lifecycle owners recover without duplicating retry policy or replaying potentially mutating calls.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Repairs a specific MCP connection-recovery failure and improves parsing performance without evidence of a broader urgent outage.
  • 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 maintainer-authored exemption applies. Embedded recovery uses the production runtime and real SDK with synthetic fetch; node recovery uses injected clients, and the reported benchmark measures synthetic SDK calls. These are not live-server proof. No stored-data contract changes.

Evidence

What I checked:

  • Introduced patch boundary: Reviewed the pinned merge-base-to-head changes. Recovery extends the existing transport and lifecycle owners; unrelated base-branch work is excluded. (src/agents/mcp-http-transport.ts:235, f5ad38af9c03)
  • Current-main necessity: Current main recognizes session expiration only for stateful Streamable HTTP. Its relevant production files are unchanged from the pinned introduction base, leaving legacy SSE POST failures outside that recovery classification. (src/agents/mcp-client-lifecycle.ts:21, ddbbc80aac5a)
  • Latest-release check: The supplied latest release, v2026.9.5, also contains only the stateful Streamable HTTP expiration predicate; this SSE repair is not established as shipped. (src/agents/mcp-client-lifecycle.ts:21, ec9c1a13db89)
  • Direct dependency contract: OpenClaw directly imports the MCP SDK SSE transport and pins version 1.30.0. npm metadata identifies this repository and commit. Its send method converts failed POST responses into plain errors, while exceptions thrown by custom fetch retain their identity through rethrow, supporting the typed-error adapter. (src/client/sse.ts, 2d889f2b329e)
  • Recovery and parser coverage: The embedded regression exercises the production runtime and real SDK using synthetic fetch responses for tools/call and tools/list, contrasting 404 recovery with ordinary 500 errors and checking no replay and cleanup. Node-host coverage uses injected clients. Transport cases cover CR, LF, split CRLF and oversized multiline events. The captured body reports 43 focused passes and 351 broader passes; these were not rerun during this read-only review. (src/agents/agent-bundle-mcp-runtime.sse-recovery.test.ts:21, f5ad38af9c03)
  • Related discussion distinguishes the remaining failure: The closed related report describes stale sessions after server restart. Its closure relied on terminal SSE error/close handling; this patch addresses POST 404 errors that do not emit that terminal signal. The discussion therefore supplies useful context without proving this branch redundant.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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 (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-22T06:16:06.268Z sha 1d7e9945a3f8c532e813b7f32b9e70d22414bfeb :: needs maintainer review before merge. :: none
  • reviewed 2026-09-22T07:03:58.986Z sha 1d7e9945a3f8c532e813b7f32b9e70d22414bfeb :: needs maintainer review before merge. :: none
  • reviewed 2026-09-22T09:52:33.979Z sha 1cad42d :: needs maintainer review before merge. :: none
  • reviewed 2026-09-22T10:23:22.815Z sha 1333d0b5bb0fba6e81abf6e4f445fd23ba43985f :: needs maintainer review before merge. :: none
  • reviewed 2026-09-22T11:15:05.143Z sha 1c1a6f5 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-22T13:14:57.972Z sha 55f9d24 :: needs changes before merge. :: none
  • reviewed 2026-09-22T14:25:47.298Z sha fc2e52a54492efd1ccc3b8347ca774a973b073ce :: needs maintainer review before merge. :: none
  • reviewed 2026-09-22T15:14:06.542Z sha fc2e52a54492efd1ccc3b8347ca774a973b073ce :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/mcp-repair-performance branch 5 times, most recently from 55f9d24 to fc2e52a Compare September 22, 2026 14:16
@steipete
steipete force-pushed the codex/mcp-repair-performance branch from fc2e52a to f5ad38a Compare September 22, 2026 15:53
@steipete
steipete merged commit 824ab3f into main Sep 22, 2026
183 checks passed
@steipete
steipete deleted the codex/mcp-repair-performance branch September 22, 2026 16:13
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 22, 2026
* commit 'f3327bde3c6052a4ed6d487bb09fbe1e11c0cd35': (25 commits)
  fix(test): pass the fixture lifetime to launcher fixtures (#155825)
  fix(test): prepare history benchmark before child deadlines (#155780)
  refactor(config): derive tool contracts from schemas (#155484)
  chore(deps): update fs-safe to 0.18.1 (#155771)
  fix(doctor): allow repair with retained deleted-agent sessions (#155752)
  fix(setup): await inference probe cleanup (#155407)
  fix(mcp): recover expired SSE sessions and speed up parsing (#155497)
  fix(release): forward the stable soak waiver through the candidate helper (#155798)
  feat: calibrate Gateway plugin resources through retirement (#155792)
  fix: preserve the invoked launcher when restarting Node (#147621)
  fix(sessions): stop repeated failed worker exit cleanup (#154720)
  fix(ui): preserve active replies and tools after failed steering (#155746)
  fix(ci): retain missing-load-path baseline diagnostics (#154861)
  fix(gateway): keep session lists responsive during activity updates (#155767)
  fix: keep plugin queues bound to their selected session (#155714)
  chore(i18n): refresh native locales (#155571)
  fix(ci): wait for reset hook entry and join fixture cleanup (#155770)
  test: move subagent fixtures to module boundaries (#155727)
  fix(gateway): retain question requester authority through settlement (#155335)
  perf(gateway): move progress-card reads off the main thread (#153857)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 23, 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 docs Improvements or additions to documentation maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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