Skip to content

fix: collect response bodies without appending a byte at a time - #422

Open
AnujYamdagni wants to merge 1 commit into
modelcontextprotocol:rel/1.0.0from
AnujYamdagni:response-body-chunked-collect
Open

AnujYamdagni wants to merge 1 commit into
modelcontextprotocol:rel/1.0.0from
AnujYamdagni:response-body-chunked-collect

Conversation

@AnujYamdagni

Copy link
Copy Markdown

Motivation and Context

ResponseBody.collect(limit:) appended each byte of a body to Data on its own. It reads 2xx JSON bodies (up to 16 MiB), error bodies (up to 1 MiB) and Server Cards. Appending to Data a byte at a time costs about 9 ns a byte, so a 16 MiB JSON reply took about 150 ms on Linux and on macOS just to collect.

  • Linux: the session delegate already delivers the body as Data chunks. collect now appends a chunk at a time, cut at the limit. The iterator gets a nextChunk() that shares fill() with next(), so the cancellation handling stays in one place, and next() only calls fill() once a chunk is used up.
  • Apple platforms: URLSession.AsyncBytes has no chunk API, so bytes go into a [UInt8] first, then into one Data. That briefly holds the body twice.
  • main reads these bodies with session.data(for:), so this cost is new on the release branch.

16 MiB application/json body through HTTPClientTransport, release build, 5 timings per run:

Platform rel/1.0.0 this change
Linux (Swift 6.4.3, x86_64) 147–153 ms 1.8–7.9 ms
macOS 27 (Swift 6.4.2, arm64) 153–166 ms 30–39 ms

Replies of a few KiB save microseconds; the gain is for large results. On Linux, reading a body a byte at a time (the SSE path) is unchanged: 0.41–0.43 s per 16 MiB before and after. On Apple platforms that path isn't touched.

How Has This Been Tested?

  • New ResponseBodyTests serves bodies in scripted chunks through a URLProtocol. It checks limits on both sides of chunk boundaries, a chunk larger than the limit, an empty body, limit: 0, a body that fails before and after the limit is reached, and (on Linux) next() mixed with nextChunk(). Apart from limit: 0 and the Linux-only nextChunk() test, which needs the new method, the tests pass on rel/1.0.0 too: they pin the limit handling, and the speedup is in the table above.
  • URLSession.AsyncBytes can throw a task's error before it hands out bytes that arrived ahead of it, so the two "limit reached before the failure" cases only run on Linux.
  • Linux: swift test passes on 9b9e1c9 (2,054 tests). The new suite passes 10 of 10 runs.
  • macOS (Command Line Tools, so without FoundationModelsTests, which needs Xcode): the new suite passes 10 of 10 runs, and 419 transport tests (HTTP|ServerCard|ResponseBody|Redirect|ServerSentEvent) pass. Full suite in a release build: 2,113 of 2,114 pass; "Client sends CancelledNotification" fails with and without this change.
  • Conformance on Linux: server default leg (276 passed, baseline check passed), and client default, 2025-11-25 and 2026-07-28 legs pass. Run on the previous revision of this change; the Linux code path is the same.
  • Not run: scripts/run-interop.sh (no uv on the Linux machine), iOS, Swift 6.1 (every run used 6.4).

No issue: this is an internal change with no public API.

AI assistance: I used AI tools to help find this, write the change and tests, and review them.

Breaking Changes

None. collect(limit: 0) now returns no bytes on both platforms; it returned one. No caller passes 0.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

ResponseBody.collect(limit:) appends each byte to Data on its own, at
about 9 ns a byte, so collecting a 16 MiB JSON reply takes about 150 ms.
On Linux, append the chunks the session delegate already delivers; on
Apple platforms, collect into [UInt8] first. collect(limit: 0) now
returns no bytes on both platforms, where it returned one.
@AnujYamdagni
AnujYamdagni requested a review from a team as a code owner December 6, 2026 15:59
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 6, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-06T16:03:11.277291Z bab05d2 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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.

Clean optimization and solid tests — no blockers here, just a few optional nits inline.

Comment on lines +54 to +58
mutating func nextChunk() async throws -> Data? {
guard try await fill() else { return nil }
defer { index = chunk.endIndex }
return chunk[index...]
}

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.

Nit: Clearing chunk in defer releases the consumed chunk's backing storage immediately instead of retaining it across the next fill() suspension:

mutating func nextChunk() async throws -> Data? {
    guard try await fill() else { return nil }
    defer {
        chunk = Data()
        index = 0
    }
    return chunk[index...]
}

Comment on lines +20 to +26
private static let lock = NSLock()
/// `nonisolated(unsafe)`: `lock` guards it.
nonisolated(unsafe) private static var scripts: [String: Script] = [:]

static func url(_ script: Script) -> URL {
let key = UUID().uuidString
lock.withLock { scripts[key] = script }

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.

Nit: Synchronization.Mutex<[String: Script]>([:]) avoids NSLock + nonisolated(unsafe) (matching ResponseBody.swift), and removeValue(forKey:) in startLoading() avoids retaining scripts for the lifetime of the test process.

Comment on lines +32 to +34
static func bytes(_ offset: Int, _ count: Int) -> Data {
Data((offset..<(offset + count)).map { UInt8(truncatingIfNeeded: $0 % 251) })
}

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.

Nit: collectLimits() calls bytes(_:_:) with 1 << 20 on 12 sub-cases (both in startLoading() and when building expected), which maps ~22M bytes in debug swift test runs. Precomputing a single static pattern buffer of (1 << 20) + 4 bytes and slicing it makes this much faster on slower CI runners.

Comment on lines +74 to +81
let mib = 1 << 20
let cases: [([Int], [Int])] = [
([5, 5, 5], Array(0...16) + [.max]),
([mib], [1, 10, mib - 1, mib, mib + 1, .max]),
([mib, 3], [mib - 1, mib, mib + 1, mib + 2, mib + 3, mib + 4]),
([], [0, 1, .max]),
([1, 1, 1, 1], [1, 2, 3, 4, 5]),
]

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.

Nit: Consider adding a case with an empty chunk between non-empty ones (e.g. ([5, 0, 5], [0, 5, 6, 10, 11]) and in byteIteration) to directly cover fill()'s while index >= chunk.endIndex loop.

@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.

Thanks for this change @AnujYamdagni , good stuff.
Left couple of nits and approving. would love if @jeanmatthieu can have a quick look before we merge.

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