Repository navigation
fix: Refuse a request whose id is in flight, and answer no cancelled request - #390
Merged
Merged
Conversation
…request Server tracked each received request by its JSON-RPC id, in startingRequests until its handler task was registered and in pendingRequestTasks while it ran. A second request with the id of one still in flight, alone or as a batch item, overwrote both entries: a notifications/cancelled for the id then cancelled the second handler and left the first running with no way to cancel it, and the first handler's cleanup removed the second's entry. Both requests ran and were answered with the same id. The id of a request MUST NOT be reused while it is in flight: "MUST NOT have been previously used by the requestor within the same session" (2025-11-25 basic, Requests), and "MUST NOT match the ID of any other request the sender has issued and not yet received a response for" (2026-07-28 basic). The receive loop now admits each request before it records it (admit(_:)): an id that is starting, running or open as a listen stream is answered with -32600 "A request with id <id> is already in progress", and no handler runs. In a batch such an item, or a later item with the id of an earlier one, becomes an invalid item and gets its -32600 in the batch reply. The first request's entries are left as they are, so it is answered and can still be cancelled. The check runs before the request's revision is known and applies to both: both revisions forbid the reuse. StatelessHTTPServerTransport gives each request its own internal id, so clients behind it never collide. A request may reuse the id of one it cancelled while that handler still runs: the cancellation already removed the entry. The cancelled request's cleanup now removes the entry only if it is still its own. A handler that caught the CancellationError and returned had its result, or the error it returned, sent anyway: handleRequest dropped the response only when the handler task threw CancellationError. The receiver of notifications/cancelled SHOULD NOT send a response for the cancelled request (2025-11-25 basic/utilities/cancellation, Behavior Requirements 4). A response of a cancelled handler task is now dropped, and a batched one adds no reply to its batch, as when the handler throws. A cancelled tools/call that created a task still cancels it. Taken from #270, without its other changes, which rel/1.0.0 already has. Co-authored-by: darius.codes <commits@darius.codes> Assisted-by: Claude
The receive loop sent the -32600 for a request whose id is in flight with try?, so a transport failure was dropped without a trace. It is now sent in a do/catch and a failure is logged as "Failed to send error response" with the id and the error, as sendUnattributedError does. The loop still goes on to the next message. The comment in admit(_:) cited the 2025-11-25 rule that a request ID "MUST NOT have been previously used by the requestor within the same session", which the server does not enforce: it refuses only an id that is still in flight. It now cites what is enforced, the 2026-07-28 rule (basic, Requests: "MUST NOT match the ID of any other request the sender has issued and not yet received a response for"), notes that 2025-11-25 is stricter, and the SeeAlso links the 2026-07-28 section. Assisted-by: Claude
admit(_:) refuses an id that startingRequests, pendingRequestTasks or
listenRequests holds. handleRequest removed those entries only after
it returned: after send(response), and for a listen stream in the
receive loop's task after that. The actor is reentrant across send, so
a client that read the response and at once sent a new request with the
same id, which 2026-07-28 allows ("MUST NOT match the ID of any other
request the sender has issued and not yet received a response for",
basic, Requests), could get -32600 "already in progress". This held for
a handler's response, for an error sent without running a handler
(unknown method, wrong revision, ...), and for a listen request refused
before its stream opened.
handleRequest now stops tracking the request right before it sends its
response. Before the handler task is registered, every return calls
untrackStarting(), which removes the startingRequests entry and the
listen entry; after it, release() removes the pendingRequestTasks entry,
only if it is still this handler's, and the listen entry, once, before
the send or on return. The receive loop no longer clears listenRequests
itself: clearing it after handleRequest returned could remove the entry
of a later listen request that reused the id. A batched request is
untracked when its handler finishes, as before.
A listen stream the server closes keeps its id until its teardown is
sent: the notifications/cancelled that follows the result names the id
(2026-07-28 basic/utilities/cancellation), and a client such as this
SDK's fails its own pending request of that id when it gets one. A
notifications/cancelled that arrives while the result is sent still
cancels the handler task and skips the teardown, as before. A request
cancelled while its handler runs, the task-manager cancellation of a
cancelled tools/call and the stop() generation guard do not change.
The new test holds the server's send of the first reply in a transport
whose send waits until released, then sends a request with the same id:
it fails with -32600 without this change, for a ping, an unknown method
and a refused listen request.
Assisted-by: Claude
varun06
previously approved these changes
Nov 28, 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.
Summary
Takes two fixes from #270 by darius.codes, credited with
Co-authored-by. The rest of that PR is already onrel/1.0.0, and the PR conflicts with it. Independent of #375, which also edits the server's receive loop: it merges with this PR without conflict (see Evidence).1. A request whose id is in flight gets -32600. A second request with the id of one still in flight, alone or in a batch, overwrote the first's
startingRequestsandpendingRequestTasksentries.notifications/cancelledthen stopped the wrong handler, the first could no longer be cancelled, and both were answered with the same id. An id must not be reused while its request is in flight: "MUST NOT match the ID of any other request the sender has issued and not yet received a response for" (2026-07-28 basic). 2025-11-25 is stricter ("MUST NOT have been previously used by the requestor within the same session"); the server enforces only the in-flight rule, under both revisions, so noProtocolProfileflag is needed. An id is free again once its response is sent.release()covers a client that reuses the id of a request it cancelled while that handler still runs.send(response)returned. The actor is reentrant acrosssend, so a client that read the response and at once reused the id could get -32600. Tracking now stops right before the response goes out: for handler responses, errors sent without a handler, and listen requests. Exception: a listen stream the server closes keeps its id until its teardownnotifications/cancelled, which names the id.handleRequestuntracks the request explicitly. A shareddeferthat captures the mutable flag is rejected by Swift 6 region isolation.2. A cancelled request gets no response. A handler that caught
CancellationErrorand returned had its result sent. The receiver ofnotifications/cancelledSHOULD NOT send a response (2025-11-25 basic/utilities/cancellation):let response = try await handlerTask.value (cancel a task the cancelled tools/call created; unchanged) guard generation == connectionGeneration else { return nil } + if handlerTask.isCancelled { return nil } // also no batch reply item-32600instead of a second handler run, and a cancelled request that returns gets no response. Only clients that already break the spec see it, so it isn't listed under "Behavior that can break working code".CHANGELOG.md(1.0.0 Fixes),design/design.mddispatch table,docs/src/protocol.src.mdand the wovendocs/protocol.md. The sentence "If it throwsCancellationError, the server sends nothing; any other error is sent as a response" became stale and is corrected.Not covered:
StatefulHTTPServerTransportkeys its per-request streams by the client's id, so two POSTs with one id in a session may still mix up routing there. That is transport-level, a separate change.stop()runs keeps itslistenRequestsentry until its handler ends, so the id is refused on a new connection until then.pendingRequestTasksentry until the handler ends, so reusing that id is refused until then.Evidence
Eight new tests in
CancellationTests. A privateControlledSendTransportcan fail chosen sends, or hold one insidesenduntil the test releases it, which makes the reuse race deterministic. Each source hunk was removed on its own and the tests re-run:["x 0","y 0","y 0"])["a","b"]); reused idtry?)swift test: 1412 tests in 142 suites pass.CancellationTestspasses 20 of 20 runs.swift scripts/weave.swift --check,swift scripts/doc-coverage.swift, and DocC--warnings-as-errorsall pass.scripts/run-conformance.sh --spec-version 2025-11-25and--spec-version 2026-07-28: both pass against the baseline.pull/375/head; no hunk touches the lines that PR changes inServer.swift.rel/1.0.0merged withpull/375/headand then this PR, the build succeeded and 1413 MCPTests plus 115 SnippetTests passed. That merge has one conflict of its own, inRequestLifecycleTests.swift, which this PR doesn't touch.rel/1.0.0(5702c80a).Merge Danger
Door: two-way until 1.0.0 is tagged: revert the commits. After the tag, the wire behavior is part of 1.0.
Blast Radius: servers
Every
Server. A client that reuses an in-flight id now gets -32600 for the second request. A handler that ignores cancellation and returns no longer has its answer delivered.AI assistance: written and opened by Claude at the author's request, for human review before merge.