Prevent double continuation resumption in client (#113)

* Prevent double continuation resumption in client

Consolidate request removal and continuation resumption logic to ensure each request's continuation is resumed exactly once, preventing "SWIFT TASK CONTINUATION MISUSE" errors during network failures.

* Fix race condition test
This commit is contained in:
Mattt 2025-05-26 04:36:01 -07:00 • committed by GitHub
commit fec680a243
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 161 additions and 34 deletions

View file

@ -191,10 +191,8 @@ public actor Client {
// Try decoding as a batch response first // Try decoding as a batch response first
if let batchResponse = try? decoder.decode([AnyResponse].self, from: data) { if let batchResponse = try? decoder.decode([AnyResponse].self, from: data) {
await handleBatchResponse(batchResponse) await handleBatchResponse(batchResponse)
} else if let response = try? decoder.decode(AnyResponse.self, from: data), } else if let response = try? decoder.decode(AnyResponse.self, from: data) {
let request = pendingRequests[response.id] await handleResponse(response)
{
await handleResponse(response, for: request)
} else if let message = try? decoder.decode(AnyMessage.self, from: data) { } else if let message = try? decoder.decode(AnyMessage.self, from: data) {
await handleMessage(message) await handleMessage(message)
} else { } else {
@ -217,23 +215,49 @@ public actor Client {
break break
} }
} while true } while true
await self.logger?.info("Client message handling loop task is terminating.")
} }
} }
/// Disconnect the client and cancel all pending requests /// Disconnect the client and cancel all pending requests
public func disconnect() async { public func disconnect() async {
// Cancel all pending requests await logger?.info("Initiating client disconnect...")
for (id, request) in pendingRequests {
// Part 1: Inside actor - Grab state and clear internal references
let taskToCancel = self.task
let connectionToDisconnect = self.connection
let pendingRequestsToCancel = self.pendingRequests
self.task = nil
self.connection = nil
self.pendingRequests = [:] // Use empty dictionary literal
// Part 2: Outside actor - Resume continuations, disconnect transport, await task
// Resume continuations first
for (_, request) in pendingRequestsToCancel {
request.resume(throwing: MCPError.internalError("Client disconnected")) request.resume(throwing: MCPError.internalError("Client disconnected"))
pendingRequests.removeValue(forKey: id) }
await logger?.info("Pending requests cancelled.")
// Cancel the task
taskToCancel?.cancel()
await logger?.info("Message loop task cancellation requested.")
// Disconnect the transport *before* awaiting the task
// This should ensure the transport stream is finished, unblocking the loop.
if let conn = connectionToDisconnect {
await conn.disconnect()
await logger?.info("Transport disconnected.")
} else {
await logger?.info("No active transport connection to disconnect.")
} }
task?.cancel() // Await the task completion *after* transport disconnect
task = nil _ = await taskToCancel?.value
if let connection = connection { await logger?.info("Client message loop task finished.")
await connection.disconnect()
} await logger?.info("Client disconnect complete.")
connection = nil
} }
// MARK: - Registration // MARK: - Registration
@ -267,12 +291,12 @@ public actor Client {
throw MCPError.internalError("Client connection not initialized") throw MCPError.internalError("Client connection not initialized")
} }
// Use the actor's encoder
let requestData = try encoder.encode(request) let requestData = try encoder.encode(request)
// Store the pending request first // Store the pending request first
return try await withCheckedThrowingContinuation { continuation in return try await withCheckedThrowingContinuation { continuation in
Task { Task {
// Add the pending request before attempting to send
self.addPendingRequest( self.addPendingRequest(
id: request.id, id: request.id,
continuation: continuation, continuation: continuation,
@ -284,9 +308,15 @@ public actor Client {
// Use the existing connection send // Use the existing connection send
try await connection.send(requestData) try await connection.send(requestData)
} catch { } catch {
// If send fails immediately, resume continuation and remove pending request // If send fails, try to remove the pending request.
continuation.resume(throwing: error) // Resume with the send error only if we successfully removed the request,
self.removePendingRequest(id: request.id) // Ensure cleanup on send error // indicating the response handler hasn't processed it yet.
if self.removePendingRequest(id: request.id) != nil {
continuation.resume(throwing: error)
}
// Otherwise, the request was already removed by the response handler
// or by disconnect, so the continuation was already resumed.
// Do nothing here.
} }
} }
} }
@ -300,8 +330,8 @@ public actor Client {
pendingRequests[id] = AnyPendingRequest(PendingRequest(continuation: continuation)) pendingRequests[id] = AnyPendingRequest(PendingRequest(continuation: continuation))
} }
private func removePendingRequest(id: ID) { private func removePendingRequest(id: ID) -> AnyPendingRequest? {
pendingRequests.removeValue(forKey: id) return pendingRequests.removeValue(forKey: id)
} }
// MARK: - Batching // MARK: - Batching
@ -555,21 +585,29 @@ public actor Client {
// MARK: - // MARK: -
private func handleResponse(_ response: Response<AnyMethod>, for request: AnyPendingRequest) private func handleResponse(_ response: Response<AnyMethod>) async {
async
{
await logger?.debug( await logger?.debug(
"Processing response", "Processing response",
metadata: ["id": "\(response.id)"]) metadata: ["id": "\(response.id)"])
switch response.result { // Attempt to remove the pending request using the response ID.
case .success(let value): // Resume with the response only if it hadn't yet been removed.
request.resume(returning: value) if let removedRequest = self.removePendingRequest(id: response.id) {
case .failure(let error): // If we successfully removed it, resume its continuation.
request.resume(throwing: error) switch response.result {
case .success(let value):
removedRequest.resume(returning: value)
case .failure(let error):
removedRequest.resume(throwing: error)
}
} else {
// Request was already removed (e.g., by send error handler or disconnect).
// Log this, but it's not an error in race condition scenarios.
await logger?.warning(
"Attempted to handle response for already removed request",
metadata: ["id": "\(response.id)"]
)
} }
removePendingRequest(id: response.id)
} }
private func handleMessage(_ message: Message<AnyNotification>) async { private func handleMessage(_ message: Message<AnyNotification>) async {
@ -619,14 +657,21 @@ public actor Client {
private func handleBatchResponse(_ responses: [AnyResponse]) async { private func handleBatchResponse(_ responses: [AnyResponse]) async {
await logger?.debug("Processing batch response", metadata: ["count": "\(responses.count)"]) await logger?.debug("Processing batch response", metadata: ["count": "\(responses.count)"])
for response in responses { for response in responses {
// Look up the pending request for this specific ID within the batch // Attempt to remove the pending request.
if let request = pendingRequests[response.id] { // If successful, pendingRequest contains the request.
// Reuse the existing single response handler logic if let pendingRequest = self.removePendingRequest(id: response.id) {
await handleResponse(response, for: request) // If we successfully removed it, handle the response using the pending request.
switch response.result {
case .success(let value):
pendingRequest.resume(returning: value)
case .failure(let error):
pendingRequest.resume(throwing: error)
}
} else { } else {
// Log if a response ID doesn't match any pending request // If removal failed, it means the request ID was not found (or already handled).
// Log a warning.
await logger?.warning( await logger?.warning(
"Received response in batch for unknown request ID", "Received response in batch for unknown or already handled request ID",
metadata: ["id": "\(response.id)"] metadata: ["id": "\(response.id)"]
) )
} }

View file

@ -479,4 +479,86 @@ struct ClientTests {
await client.disconnect() await client.disconnect()
} }
@Test("Race condition between send error and response")
func testSendErrorResponseRace() async throws {
let transport = MockTransport()
let client = Client(name: "TestClient", version: "1.0")
try await client.connect(transport: transport)
try await Task.sleep(for: .milliseconds(10))
// Set up the transport to fail sends from the start
await transport.setFailSend(true)
// Create a ping request to get the ID
let request = Ping.request()
// Create a response for the request and queue it immediately
let response = Response<Ping>(id: request.id, result: .init())
let anyResponse = try AnyResponse(response)
try await transport.queue(response: anyResponse)
// Now attempt to send the request - this should fail due to send error
// but the response handler might also try to process the queued response
do {
_ = try await client.ping()
#expect(Bool(false), "Expected send to fail")
} catch let error as MCPError {
if case .transportError = error {
#expect(Bool(true))
} else {
#expect(Bool(false), "Expected transport error, got \(error)")
}
} catch {
#expect(Bool(false), "Expected MCPError, got \(error)")
}
// Verify no continuation misuse occurred
// (If it did, the test would have crashed)
await client.disconnect()
}
@Test("Race condition between response and send error")
func testResponseSendErrorRace() async throws {
let transport = MockTransport()
let client = Client(name: "TestClient", version: "1.0")
try await client.connect(transport: transport)
try await Task.sleep(for: .milliseconds(10))
// Create a ping request to get the ID
let request = Ping.request()
// Create a response for the request and queue it immediately
let response = Response<Ping>(id: request.id, result: .init())
let anyResponse = try AnyResponse(response)
try await transport.queue(response: anyResponse)
// Set up the transport to fail sends
await transport.setFailSend(true)
// Now attempt to send the request
// The response might be processed before the send error occurs
do {
_ = try await client.ping()
// In this case, the response handler won the race and the request succeeded
#expect(Bool(true), "Response handler won the race - request succeeded")
} catch let error as MCPError {
if case .transportError = error {
// In this case, the send error handler won the race
#expect(Bool(true), "Send error handler won the race - request failed")
} else {
#expect(Bool(false), "Expected transport error, got \(error)")
}
} catch {
#expect(Bool(false), "Expected MCPError, got \(error)")
}
// Verify no continuation misuse occurred
// (If it did, the test would have crashed)
await client.disconnect()
}
} }