Skip to content

[P33] http: release a client transport dropped without disconnect - #338

Merged
jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p33-transport-release
Nov 25, 2026
Merged

jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p33-transport-release

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P33 of P0–P35, merged into rel/1.0.0 in order (previous: P32 (#339) · next: P34 (#337))
Branch conformance/p33-transport-release
Base conformance/p32-apps (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits a25aeb6 http: release a client transport dropped without disconnect
dea1521 http: second-pass review fixes
c50ceea http: third-pass review fixes
Size 11 files, +763 / -156

Summary

An HTTPClientTransport that the application drops without calling disconnect() is now released, and with streaming: true it stops its standalone GET stream. Before, it stayed in memory for the rest of the process and kept reconnecting the GET stream with backoff. Client is unchanged; its documentation now says that a connected client must be disconnected.

Motivation

Three things held a dropped transport (found while closing the review of P18 (#353)):

  • connect() started a task that captured the transport and waited for a session ID. Only a session ID, disconnect() or useStatelessProtocol(_:) ended the wait; the timeout existed only inside the GET loop. With streaming: false, or against a server that never sends a session ID, the task waited forever.
  • With streaming: true, the GET loop held the transport for its whole life: while isConnected && !Task.isCancelled, reconnecting with backoff.
  • There was no deinit. Nothing cancelled the tasks, finished the message stream or invalidated the two URLSessions, which keep their delegates until they are invalidated.

Changes

Sources/MCP/Base/Transports/HTTPClientTransport.swift

  • The session ID wait is a small signal the transport owns (SessionIDSignal, lock-protected), with the timeout timer next to it. A session ID, the timeout, disconnect(), useStatelessProtocol(_:), cancellation or the release of the transport ends it, once. connect() starts no task when streaming is false.
  • The GET loop is a static function over a weak reference. It holds the transport for one step (opening the stream, with its authorizer and DPoP retries, or handling one event), not while it waits for the session ID, sleeps before reconnecting or waits for the next event. Backoff, consecutive failures, 400/404/405 handling, session expiry, Last-Event-ID and retry: behave as before.
  • deinit cancels the GET task and the POSTs in flight, ends the session ID wait, finishes the message stream and invalidates both sessions. No task can be creating a URLSession task at that point, because doing so holds the transport.

Documentation

  • Doc comments on HTTPClientTransport, connect() and disconnect(): disconnect() ends the connection at once; a transport dropped without it is released and its GET stream stops.
  • Doc comments on Client and Client.disconnect(): a connected client must be disconnected; its receive loop keeps it, and its transport, alive until disconnect() or until the transport closes the connection.
  • docs/protocol.md (HTTP client), docs/client.md, the migration guide's HTTP client list and CHANGELOG (Fixes) say the same.

Behavior changes

  • A transport dropped without disconnect() is released and its URL sessions are invalidated; with streaming: true no GET is sent after the release.
  • Some debug log lines of the GET loop no longer include isConnected.

Tests

HTTPClientTransportReleaseTests (in HTTPClientTransportTests.swift), with a streaming URLProtocol mock. A dropped transport is released:

  • without streaming, and its message stream ends;
  • while waiting for a session ID, with no GET sent;
  • while reading an open GET stream: the stream is closed and no further GET is sent;
  • while waiting to reconnect after a failed GET: no further GET is sent.

Each test fails at b88dd46 (P32 (#339)). The suite lives in HTTPClientTransportTests.swift because, in a separate file, a second URLProtocol subclass compiled in the same frontend batch makes Swift 6.4 reject MockURLProtocol.startLoading (a compiler issue).

Review notes

  • Client itself is still kept alive by its receive loop when it is dropped connected. General support for dropping a client without disconnect() needs weak receive and inbound loops and a deinit that runs the existing synchronous teardown; it is left for a separate change.
  • Later changes to the GET loop must keep it static and holding the transport weakly.

Verification

  • macOS: swift test 1236 tests in 135 suites + 113 snippet tests; scripts/ci/run-jobs.sh --strict (build-test, docs incl. DocC warnings-as-errors and doc coverage, api-breakage, every conformance leg and tier, interop --check).
  • Linux (swift:6.1-rhel-ubi9): full swift test, 1333 tests.
  • Conformance client legs 2025-11-25 and 2026-07-28 at their baselines; scripts/run-interop.sh --check matches interop/RESULTS.md.

AI usage disclosure: the changes, the tests, the commit messages and this description were written with Claude Opus 5.5 and reviewed by the authors.

An HTTPClientTransport that the application dropped without calling
disconnect() was never released. connect() started a task that held
the transport while it waited for a session ID, which with
streaming: false, or a server that never sends one, it waited for
forever; with streaming: true the GET loop held it for its whole life
and kept reconnecting with backoff; and nothing cancelled the tasks or
invalidated the two URL sessions, which keep their delegates until
invalidated.

- The session ID wait is a signal the transport owns and the GET loop
  waits on, with the timeout timer next to it. A session ID, the
  timeout, disconnect(), useStatelessProtocol(_:), cancellation of the
  task or the release of the transport ends it, once. connect() starts
  no task when streaming is false.
- The GET loop is a static function over a weak reference: it holds
  the transport for one step (opening the stream with its authorizer
  and DPoP retries, handling one event), not while it waits for the
  session ID, sleeps before reconnecting or waits for the next event.
  Backoff, consecutive failures, 400/404/405 handling, session expiry,
  Last-Event-ID and retry: behave as before.
- deinit cancels the GET task and the POSTs in flight, ends the session
  ID wait, finishes the message stream and invalidates both sessions
  (no task can be creating a URLSession task then: that holds the
  transport).
- Doc comments on the transport, connect() and disconnect(), and on
  Client and Client.disconnect() (a connected client must be
  disconnected: its receive loop keeps it and its transport alive);
  the protocol and client guides, the migration guide and CHANGELOG
  say the same.

Tests: HTTPClientTransportReleaseTests, with a streaming URLProtocol
mock: a dropped transport is released without streaming (and its
message stream ends), while waiting for a session ID (no GET is sent),
while reading an open GET stream (the stream is closed, no further
GET), and while waiting to reconnect after a failed GET (no further
GET). The suite is in HTTPClientTransportTests.swift: in a separate
file, a second URLProtocol subclass compiled in the same frontend batch
makes Swift 6.4 reject MockURLProtocol's startLoading.
- A transport dropped without disconnect() stops its GET stream when it
  is released, not by the next event: the listener holds it only weakly
  while it waits, so deinit runs at once, cancels the listener and
  invalidates the session that owns the GET. Fix the doc comments of the
  type and of connect(), and the guides.
- releasedWithOpenStream no longer writes an event after the drop, so it
  checks that the release itself closes the stream.

- connect() after disconnect() throws internalError instead of building
  new URL sessions: the stream receive() returns is finished by then, so
  a reconnected transport dropped every message. A transport serves one
  connection (protocol guide, Transports); the session ID, stateless mode
  and last event ID would also carry over. The previous release raised at
  the next send on Apple platforms. The migration guide says so.
- disconnect() also cancels POSTs without a request ID (notifications and
  responses to server requests). They ran in the caller's task, and on
  Apple platforms a request keeps the sessions valid until its response
  headers arrive, so such a POST outlived disconnect() until the server
  answered or the idle timeout.
- The HTTPClientTransport docs state the 16 MiB limit on an SSE line and
  on the data of one event, already in the migration guide.
- A connect(transport:) that throws (an HTTP 401 or 5xx, a network
  error, an unsupported version) releases the connection, as disconnect()
  does, and waits for the receive loop before it rethrows. Before, the
  receive loop and the inbound queue kept running and kept the client and
  the transport alive, and the HTTP transport's GET loop kept
  reconnecting, although the caller had no connected client. The leak
  predates this stack (main opened the connection the same way). The
  client guide and connect(transport:) say a failed connect needs no
  disconnect().

- The GET stream holds the transport only while it builds each GET and
  records its reply, no longer while it awaits the authorizer, the
  response headers or a challenge. openEventStream is a static helper
  over the weak reference, which the resumption of POST streams uses
  too, so a transport dropped while its GET waits for headers (up to the
  request timeout) or for an interactive sign-in is released at once.
  deinit cancels the GET; a GET being created keeps the sessions valid
  until its task exists, as at disconnect().

- deinit no longer loops over inFlightPosts: a send() in flight holds the
  transport, and its entry is gone before send() returns, so the loop
  cancelled nothing. The type doc and the protocol guide now say a
  dropped transport stops its GET stream and invalidates its URL
  sessions, and a send() still running keeps it alive until it finishes
  or its task is cancelled.

- The 16 MiB sentence says what each stream does: a POST's request fails
  and its stream is not resumed; the GET stream reconnects after its
  backoff without Last-Event-ID, so it opens a fresh stream.
- The static GET loop keeps the fixes of the PRs below: a line or event
  over 16 MiB drops the stream's resume point, and a 404 is a session
  expiry only when the GET carried Mcp-Session-Id (sentSessionID).
- The reconnect log has willRetryAfter again (the next delay, with
  backoff), and the exit log says why the loop ended: released,
  sessionExpired, cancelled or disconnected.
- CHANGELOG: connect() after disconnect() throws internalError, and a
  failed connect(transport:) disconnects the transport.
- releasedDuringBackoff: the next waits are 50, 100 and 200 ms.
varun06
varun06 previously approved these changes Nov 25, 2026

@varun06 varun06 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already reviewed and still looking good.

Base automatically changed from conformance/p32-apps to rel/1.0.0 November 25, 2026 12:54
@jeanmatthieu
jeanmatthieu dismissed varun06’s stale review November 25, 2026 12:54

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit d6f4250 into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p33-transport-release branch November 25, 2026 12:55
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.

2 participants