Repository navigation
[P33] http: release a client transport dropped without disconnect - #338
Merged
Merged
Conversation
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.
This was referenced Nov 25, 2026
varun06
previously approved these changes
Nov 25, 2026
varun06
left a comment
Contributor
There was a problem hiding this comment.
Already reviewed and still looking good.
varun06
approved these changes
Nov 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
rel/1.0.0in order (previous: P32 (#339) · next: P34 (#337))conformance/p33-transport-releaseconformance/p32-apps(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)a25aeb6http: release a client transport dropped without disconnectdea1521http: second-pass review fixesc50ceeahttp: third-pass review fixesSummary
An
HTTPClientTransportthat the application drops without callingdisconnect()is now released, and withstreaming: trueit stops its standalone GET stream. Before, it stayed in memory for the rest of the process and kept reconnecting the GET stream with backoff.Clientis 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()oruseStatelessProtocol(_:)ended the wait; the timeout existed only inside the GET loop. Withstreaming: false, or against a server that never sends a session ID, the task waited forever.streaming: true, the GET loop held the transport for its whole life:while isConnected && !Task.isCancelled, reconnecting with backoff.deinit. Nothing cancelled the tasks, finished the message stream or invalidated the twoURLSessions, which keep their delegates until they are invalidated.Changes
Sources/MCP/Base/Transports/HTTPClientTransport.swiftSessionIDSignal, 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 whenstreamingis false.Last-Event-IDandretry:behave as before.deinitcancels 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 aURLSessiontask at that point, because doing so holds the transport.Documentation
HTTPClientTransport,connect()anddisconnect():disconnect()ends the connection at once; a transport dropped without it is released and its GET stream stops.ClientandClient.disconnect(): a connected client must be disconnected; its receive loop keeps it, and its transport, alive untildisconnect()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
disconnect()is released and its URL sessions are invalidated; withstreaming: trueno GET is sent after the release.isConnected.Tests
HTTPClientTransportReleaseTests(inHTTPClientTransportTests.swift), with a streamingURLProtocolmock. A dropped transport is released:Each test fails at
b88dd46(P32 (#339)). The suite lives inHTTPClientTransportTests.swiftbecause, in a separate file, a secondURLProtocolsubclass compiled in the same frontend batch makes Swift 6.4 rejectMockURLProtocol.startLoading(a compiler issue).Review notes
Clientitself is still kept alive by its receive loop when it is dropped connected. General support for dropping a client withoutdisconnect()needs weak receive and inbound loops and adeinitthat runs the existing synchronous teardown; it is left for a separate change.Verification
swift test1236 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).swift:6.1-rhel-ubi9): fullswift test, 1333 tests.scripts/run-interop.sh --checkmatchesinterop/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.