Skip to content

fix(sdk): end gRPC request sides when response trailers arrive - #2356

Merged
peppescg merged 1 commit into
mainfrom
fix/1785-h2-premature-close
Oct 16, 2026
Merged

peppescg merged 1 commit into
mainfrom
fix/1785-h2-premature-close

Conversation

@peppescg

@peppescg peppescg commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem. When grpc-go finishes a bidi RPC whose request side is still open, it sends the final DATA, trailers with END_STREAM, then RST_STREAM(NO_ERROR). If the response bytes are still buffered when that reset arrives, Node emits aborted. Its stream iterator then rejects the complete response with ERR_STREAM_PREMATURE_CLOSE instead of EOF (nodejs/node#66693). Connect surfaces this as Unknown, and the SDK reports TransportError: The request could not reach the mecatl server, even though the run completed. A real non-OK status sent before such a reset is also masked as Unknown.
  • Scope. All three bidi RPCs keep the client request side open until the server finishes: Converse, RecheckMcpAuthorization and CancelMcpAuthorization. Any consumer that is not reading when the server completes hits the bug. The CI flake in test(sdk): investigate flaky gRPC MCP authorization premature close #1785 is the cancelContinuation() instance: the SDK awaits the unary cancel while the terminal event, trailers and reset arrive.
  • Fix. The session manager behind createNodeTransport ends each stream's request side when its response trailers arrive. Node already ends that side when it processes the reset; doing it first stops Node from treating a completed response as aborted. A reset before the trailers, a non-zero reset, or a non-OK status still fail. The same fix applies on Node, Bun, and Deno.

Issue relationship

Closes #1785

Type of change

  • Bug fix

Before | After

Real mecatl-sdk-authorization-fixture (grpc-go). The SDK consumer pauses 300 ms after starting a Run, or after the first recheck() event, before draining it.

Runtime Before (stock transport) After (this PR)
Node 24.21 slow Run 3/3 fail, slow recheck 3/3 fail 24/24 pass
Node 22.12 / 26.11 fails the same deterministic tests (not re-measured on the fixture) 24/24 pass per version
Bun 1.4.1 slow Run: 4/4 fail 24/24 pass
Deno 2.9.3 / 2.9.7 slow Run: 24/24 fail 24/24 pass per version (see limits below)
Before: TransportError: The request could not reach the mecatl server
          <- ConnectError: [unknown] Premature close
          <- Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
After:  run.result() -> RunAuthorizationRequiredError (the expected outcome); recheck() -> result event, then EOF

Test plan

Baseline checks

  • Linting (task lint): one pre-existing gosec G703 finding in environment/microvm/launch_ownership_darwin.go:754. It is a macOS-only file, unchanged since feat: add microVM execution environments #580; CI lints on Linux and never sees it. All other modules report 0 issues.
  • Fast offline test suite (task test): not run separately; task test:race covers the same suite.
  • Pre-review race suite (task test:race): every package passes except four tests that fail only on this macOS machine, and fail the same way outside the sandbox: TestConnectUsesSavedServerCAForLazyTLSRPC (macOS x509 verifier), TestMecatedCLICompositionValidatesMicroVMDefaultAfterReadiness (/dev/fd socket path), TestStartupCompatibilityEmbeddedRejected, TestRunInDirUsesDescriptorAndPassesArgumentsOpaquely (env: bash missing from the test PATH). This PR changes no Go code.
  • Offline demo (go run ./cmd/mecademo): tool call, permission ask with approval, and final result.
  • Markdown changed (task docs): no Markdown changes.
  • User docs (task site:build): no user-docs changes.
  • Guarded engine API (task api:check): engine untouched.

TypeScript SDK

  • Biome, tsc --noEmit, unit suite 385/385.
  • task e2e (Node and Bun 1.4.1 matrix): 36/36. task deno on Deno 2.9.3 and 2.9.7: all checks pass.
  • New test/node-transport-completion.test.ts, 7 tests. A raw HTTP/2 peer pins grpc-go's frame order. A PING barrier makes the tests deterministic without sleeps. With the stock transport, the first three fail:
    • complete response followed by a NO_ERROR reset → EOF;
    • non-OK status followed by a NO_ERROR reset → that status, not Unknown;
    • backpressure: the peer honours HTTP/2 flow control and sends a 2 MB response (128 × 16 KB), then trailers and a reset. With no reads, the peer stalls after about 96 KB. The trailers and reset arrive with five messages unread, and all 128 messages still arrive intact before EOF;
    • completion without a reset → EOF;
    • abort while a read is pending → Canceled, no hang;
    • abort after a reset with unread bytes → Canceled, no hang;
    • reset before the response completes → still an error.
  • Runtime matrix on Node 22.12/24.21/26.11, Bun 1.4.1, and Deno 2.9.3/2.9.7 (the CI versions), all through createNodeTransport:
    • a deterministic peer probe (10 runs per scenario);
    • the backpressure scenario (bounded on every runtime: 96–144 KB of 2 MB while paused; intact delivery with the fix);
    • slow and fast consumers against the real fixture (fast consumers: no change, 24/24 everywhere).

Changes

File Change
sdk/typescript/src/node-transport.ts ResponseCompletingSessionManager ends a stream's request side on its response trailers; createNodeTransport uses it.
sdk/typescript/test/node-transport-completion.test.ts Deterministic raw-HTTP/2 regression tests listed above.

User-facing change

On the Node, Bun, and Deno gRPC transport, a completed Run, recheck(), or cancel() no longer fails with TransportError / premature close when the consumer reads slowly. A server error sent just before such a reset now arrives with its real status.

Special notes for reviewers

Why this fix and not a custom response reader. The investigation in #1785 proposed replacing Node's response iterator below Connect (candidate A). I built that variant too and measured both against the same tests:

This PR (end request side on trailers) Custom reader + end on trailers
Issue scenario on Node, Bun, Deno fixed fixed
2 MB response under backpressure bounded, intact bounded, intact
Whole response arrives before the first read (raw transport only) fails on Node 24.20+/26.3+ (nodejs/node#65677) and Bun 1.4.1 passes
Deno, slow consumer, 192 runs 2 failures 0 failures
Source size 23 lines 88 lines
Surface one listener per stream replaces how every gRPC response, unary included, is read

The custom reader covers two more edge cases, but it takes over body reading for every gRPC call and depends on fine stream-state semantics in Node, Bun, and Deno. Writing it exposed two traps:

  • completing on "trailers seen and buffer empty" can truncate under backpressure;
  • a request write that races completion marks Node's readable side as errored, so it never emits end, which hangs a naive reader.

We prefer the smaller change now and keep the reader as a follow-up if the edge cases matter in practice.

Known limits of this PR

  • Late first read on the raw transport. If a caller awaits transport.stream() and starts reading only after the whole response arrived and the stream closed, Node 24.20+/26.3+ (http2: async iteration reports premature close with buffered responses in v26.3.0+ and v24.20.0 nodejs/node#65677) and Bun report a premature close. With a grpc-go server this already fails today on Node 24/26; on Bun it is new with this change. The SDK's high-level and raw clients start reading as soon as headers arrive, so they never reach this state.
  • Deno residual. With deliberately slow consumers, Deno still fails rarely: 2 of 192 runs in the last sample, versus every run before the fix. Fast consumers are unaffected.
  • Request write racing completion. If the SDK writes a request message after the server completed, Node emits ERR_STREAM_WRITE_AFTER_END on the stream and the read fails. That behaviour is unchanged from today.

API compatibility. No wire, proto, or server change. The client half-closes only after the server's END_STREAM, when the RPC is already finished server-side, so permission-ask and disconnect semantics are unchanged. Public SDK API unchanged.

Upstream: nodejs/node#66693 (this bug; maintainer expects a fix for v26/main, not v24), nodejs/node#65677 (late-read variant), connectrpc/connect-es#1752 (resets before trailers; compatible with this change).

🤖 Generated with Claude Code

@peppescg peppescg self-assigned this Oct 15, 2026
A grpc-go server that finishes a bidi RPC while the client request side is
still open sends trailers and then RST_STREAM(NO_ERROR). Node, Bun, and Deno
then report the complete, still-buffered response as a premature close, so a
finished Run, recheck, or cancel failed with TransportError and a non-OK
status arrived as Unknown (nodejs/node#66693).

The Node transport's session manager now ends each stream's request side as
soon as its trailers arrive, before the reset is processed. Genuine resets
and errors still fail. Adds deterministic raw-HTTP/2 regression tests,
including flow-controlled backpressure and abort cases.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@peppescg
peppescg force-pushed the fix/1785-h2-premature-close branch from 8a94656 to 3a94de7 Compare October 15, 2026 13:45
@peppescg
peppescg merged commit 548d185 into main Oct 16, 2026
35 checks passed
@peppescg
peppescg deleted the fix/1785-h2-premature-close branch October 16, 2026 14:19
@toolhive-release-app toolhive-release-app Bot mentioned this pull request Oct 20, 2026
2 tasks
@jbeda jbeda mentioned this pull request Oct 31, 2026
10 of 14 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test(sdk): investigate flaky gRPC MCP authorization premature close

1 participant