diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7bce1fc9..af8f3d37 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,9 @@ jobs: test: timeout-minutes: 20 strategy: + # Each leg reports its own result: a flake on one platform does not + # cancel the others. + fail-fast: false matrix: include: # macOS uses the Swift toolchain bundled with Xcode: a standalone toolchain diff --git a/CHANGELOG.md b/CHANGELOG.md index ff4cb5e9..c2f71aa1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -257,6 +257,17 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha second `connect()` while one is in progress throws instead of replacing the first one's connection, and that includes a `connect()` stopped by `disconnect()` until it has returned, which can take the rest of its backoff. A `connect()` after that dials a fresh connection. +- On Linux, an OAuth authorization code flow without an `OAuthAuthorizationDelegate` no longer + crashes the process with `SWIFT TASK CONTINUATION MISUSE` after the authorization request. + `OAuthAuthorizationCodeFlow` cancelled its session's request once the request had returned, and + on swift-corelibs-foundation a request cancelled as it finishes completes a second time. +- On Linux, cancelling an `HTTPClientTransport` request no longer crashes the process with + `Trying to access a behaviour for a task that in not in the registry`. The session that streams + responses had the configuration's `URLCache`, and swift-corelibs-foundation could fail a task + cancelled during its cache lookup after the session had let it go; that session now has no + cache, nor do the sessions the OAuth requests run in. `ServerCard.fetch(from:session:)` on + Linux therefore no longer answers from the session's cache; `fetch(from:ifNoneMatch:session:)` + revalidates a card the caller kept. - From `main` after 0.12.1: `Data.parseDataURL(_:)` reads `;base64` from the header only and decodes any percent-escaped byte (#309, #310); `client_secret_basic` percent-encodes the client credentials (RFC 6749 ยง2.3.1, #300); PKCE verifier characters are uniformly distributed (#303); diff --git a/Examples/Tests/ProtocolSnippetTests.swift b/Examples/Tests/ProtocolSnippetTests.swift index 420ccd4a..0bc0a8f6 100644 --- a/Examples/Tests/ProtocolSnippetTests.swift +++ b/Examples/Tests/ProtocolSnippetTests.swift @@ -4,7 +4,7 @@ import Testing @testable import MCP @testable import ProtocolSnippets -@Suite("Protocol snippets", .timeLimit(.minutes(1))) +@Suite("Protocol snippets", .timeLimit(.minutes(2))) struct ProtocolSnippetTests { @Test func handshakeNegotiatesLatestHandshakeRevision() async throws { let version = try await connectWithHandshake(server: await makeLifecycleServer()) diff --git a/Sources/MCP/Base/Authorization/OAuthAuthorizationCodeFlow.swift b/Sources/MCP/Base/Authorization/OAuthAuthorizationCodeFlow.swift index 395e1ecc..97ccc2eb 100644 --- a/Sources/MCP/Base/Authorization/OAuthAuthorizationCodeFlow.swift +++ b/Sources/MCP/Base/Authorization/OAuthAuthorizationCodeFlow.swift @@ -159,13 +159,22 @@ public struct OAuthAuthorizationCodeFlow: Sendable { request.setValue( "text/html, \(ContentType.json)", forHTTPHeaderField: HTTPHeaderName.accept) + #if canImport(FoundationNetworking) + let configuration = session.configuration.withoutURLCache() + #else + let configuration = session.configuration + #endif let noRedirectDelegate = OAuthNoRedirectSessionDelegate() let noRedirectSession = URLSession( - configuration: session.configuration, + configuration: configuration, delegate: noRedirectDelegate, delegateQueue: nil ) - defer { noRedirectSession.invalidateAndCancel() } + // Not `invalidateAndCancel()`: the request has ended when this runs, + // and on swift-corelibs-foundation cancelling a task that has just + // finished completes it again, so `data(for:)` resumes its + // continuation twice and traps. + defer { noRedirectSession.finishTasksAndInvalidate() } let (_, response) = try await noRedirectSession.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { diff --git a/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift b/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift index e33ac6fc..2781b91a 100644 --- a/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift +++ b/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift @@ -71,15 +71,15 @@ extension URLSession { /// `data(for:)` with the redirect checks of ``OAuthRedirectGuard``. /// /// swift-corelibs-foundation has no per-task delegates: there the request - /// runs in a session with this session's configuration and the guard as - /// its delegate. + /// runs in a session with this session's configuration, without its URL + /// cache, and the guard as its delegate. func oauthData( for request: URLRequest, redirects policy: OAuthRedirectGuard.Policy, validator: OAuthURLValidator ) async throws -> (Data, URLResponse) { #if canImport(FoundationNetworking) let guarded = URLSession( - configuration: configuration, + configuration: configuration.withoutURLCache(), delegate: OAuthRedirectGuard(policy: policy, validator: validator), delegateQueue: nil) defer { guarded.finishTasksAndInvalidate() } diff --git a/Sources/MCP/Base/Transports/ResponseBody.swift b/Sources/MCP/Base/Transports/ResponseBody.swift index f464296b..81522c42 100644 --- a/Sources/MCP/Base/Transports/ResponseBody.swift +++ b/Sources/MCP/Base/Transports/ResponseBody.swift @@ -216,6 +216,21 @@ struct ResponseBody: AsyncSequence, Sendable { return request } } + + extension URLSessionConfiguration { + /// A copy of the configuration with no URL cache. + /// + /// With a cache, swift-corelibs-foundation looks each request up in it + /// before the request starts, and a task cancelled during that lookup + /// can be failed after it has left the session's registry, which traps + /// ("a task that in not in the registry"). The sessions the SDK makes + /// on Linux use this copy. + func withoutURLCache() -> URLSessionConfiguration { + let configuration = copy() as! URLSessionConfiguration + configuration.urlCache = nil + return configuration + } + } #endif extension URLSession { @@ -312,7 +327,10 @@ struct StreamingSession: Sendable { #if canImport(FoundationNetworking) let delegate = StreamingSessionDelegate(redirects: redirects) self.delegate = delegate - self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + // The session carries MCP requests, which are not cached, and + // server card fetches, which revalidate with their own ETag. + self.session = URLSession( + configuration: configuration.withoutURLCache(), delegate: delegate, delegateQueue: nil) #else self.redirects = redirects #endif diff --git a/Tests/MCPTests/CancellationTests.swift b/Tests/MCPTests/CancellationTests.swift index 854f1980..d91f5398 100644 --- a/Tests/MCPTests/CancellationTests.swift +++ b/Tests/MCPTests/CancellationTests.swift @@ -267,7 +267,7 @@ struct CancellationTests { @Test( "A cancellation that arrives before the handler is registered cancels it", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testCancellationBeforeHandlerRegistration() async throws { let transport = GatedContextTransport(gating: .string("call-1")) let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init())) @@ -305,7 +305,7 @@ struct CancellationTests { @Test( "A cancellation for a batched request that has not started yet is kept", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testCancellationOfQueuedBatchRequest() async throws { let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init())) let gate = BatchGate() @@ -362,7 +362,7 @@ struct CancellationTests { @Test( "A request whose id is in flight is refused with -32600, and the first is answered", - .timeLimit(.minutes(1)), arguments: [false, true]) + .timeLimit(.minutes(2)), arguments: [false, true]) func testDuplicateInFlightIDIsRefused(stateless: Bool) async throws { let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init())) let gate = BatchGate() @@ -397,7 +397,7 @@ struct CancellationTests { @Test( "A refusal of an id in flight that cannot be sent is logged, and the next message is handled", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testFailedRefusalIsLogged() async throws { let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init())) let gate = BatchGate() @@ -430,7 +430,7 @@ struct CancellationTests { @Test( "A request may reuse an id once its response is sent, while the server still sends it", - .timeLimit(.minutes(1)), + .timeLimit(.minutes(2)), arguments: [ // Answered by its handler. #"{"jsonrpc":"2.0","id":"x","method":"ping"}"#, @@ -465,7 +465,7 @@ struct CancellationTests { @Test( "Cancelling a request after a duplicate of its id was refused cancels its handler", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testCancellationAfterRefusedDuplicate() async throws { let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init())) let started = BatchGate() @@ -501,7 +501,7 @@ struct CancellationTests { @Test( "A batched request whose id is in flight or repeated in the batch is refused with -32600", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testDuplicateIDsInBatchAreRefused() async throws { let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init())) let gate = BatchGate() @@ -534,7 +534,7 @@ struct CancellationTests { @Test( "A handler that returns after its request was cancelled sends no response", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testSwallowedCancellationSendsNoResponse() async throws { let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init())) let started = Flag() @@ -565,7 +565,7 @@ struct CancellationTests { @Test( "A batched handler that returns after its request was cancelled adds no reply", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testSwallowedCancellationInBatchAddsNoReply() async throws { let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init())) let gate = BatchGate() @@ -596,7 +596,7 @@ struct CancellationTests { @Test( "A request that reuses the id of a cancelled request still running can be cancelled", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testReusedIDOfCancelledRequestCanBeCancelled() async throws { let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init())) let gate = BatchGate() diff --git a/Tests/MCPTests/ClientConnectionFailureTests.swift b/Tests/MCPTests/ClientConnectionFailureTests.swift index e83bc96f..673b26ba 100644 --- a/Tests/MCPTests/ClientConnectionFailureTests.swift +++ b/Tests/MCPTests/ClientConnectionFailureTests.swift @@ -503,7 +503,7 @@ struct OutgoingMessageTests { } } - @Suite("Discovery timeout over HTTP", .timeLimit(.minutes(1))) + @Suite("Discovery timeout over HTTP", .timeLimit(.minutes(2))) struct DiscoveryTimeoutHTTPTests { @Test("A timed-out server/discover closes its POST") func closesTimedOutDiscover() async throws { @@ -527,117 +527,211 @@ struct OutgoingMessageTests { await client.disconnect() } + /// The discovery timeouts of the tests below, shortest first. Each test + /// needs the sign-in of `server/discover` to start before the timeout + /// runs out, and a loaded runner can delay the request by seconds: an + /// attempt where the sign-in started later does not test the timer, so + /// it is run again with the next timeout. + static let discoveryTimeouts: [Duration] = [.seconds(1), .seconds(4), .seconds(12)] + // A user who takes longer than `discoveryTimeout` to sign in must not // be asked to sign in again, nor be moved to the handshake. @Test("Signing in does not count against the discovery timeout") func signInOutlastsDiscoveryTimeout() async throws { - let host = "\(UUID().uuidString).answering.test" - let authorizer = SlowSignInAuthorizer(signIn: .seconds(2)) - let client = Client( - name: "probe", version: "1.0", - configuration: .init(protocolMode: .automatic, discoveryTimeout: .seconds(1))) - - let result = try await client.connect( - transport: ChallengedDiscoverProtocol.transport(host: host, authorizer: authorizer)) - #expect(result.protocolVersion == Version.v2026_07_28) - #expect(authorizer.challenges == 1) - #expect(ChallengedDiscoverProtocol.state.methods(of: host) == [ServerDiscover.name]) - await client.disconnect() + for timeout in Self.discoveryTimeouts { + let attempt = SignInAttempt(timeout: timeout) + let connecting = Task { try await attempt.connect() } + guard try await attempt.timerWaitsForSignIn() else { + await attempt.abandon(connecting) + continue + } + attempt.authorizer.release() + guard case .returned(let result) = await attempt.outcome(of: connecting) else { + Issue.record("connect did not return a result") + await attempt.client.disconnect() + return + } + #expect(result.protocolVersion == Version.v2026_07_28) + #expect(attempt.authorizer.challenges == 1) + #expect(ChallengedDiscoverProtocol.state.methods(of: attempt.host) == [ServerDiscover.name]) + await attempt.client.disconnect() + return + } + Issue.record("The sign-in of server/discover started after every discovery timeout") } @Test("The discovery timeout starts again after signing in") func timeoutAfterSignIn() async throws { - let host = "\(UUID().uuidString).silent.test" - let authorizer = SlowSignInAuthorizer(signIn: .seconds(2)) - let client = Client( - name: "probe", version: "1.0", - configuration: .init(protocolMode: .automatic, discoveryTimeout: .seconds(1))) - - // The server never answers the authorized server/discover. - let result = try await client.connect( - transport: ChallengedDiscoverProtocol.transport(host: host, authorizer: authorizer)) - #expect(result.protocolVersion == Version.v2025_11_25) - #expect(authorizer.challenges == 1) - await client.disconnect() + for timeout in Self.discoveryTimeouts { + // The server never answers the authorized server/discover. + let attempt = SignInAttempt(timeout: timeout, host: "silent.test") + let connecting = Task { try await attempt.connect() } + guard try await attempt.timerWaitsForSignIn() else { + await attempt.abandon(connecting) + continue + } + attempt.authorizer.release() + guard case .returned(let result) = await attempt.outcome(of: connecting) else { + Issue.record("connect did not return a result") + await attempt.client.disconnect() + return + } + #expect(result.protocolVersion == Version.v2025_11_25) + #expect(attempt.authorizer.challenges == 1) + await attempt.client.disconnect() + return + } + Issue.record("The sign-in of server/discover started after every discovery timeout") } @Test("A sign-in that fails after the deadline fails connect without falling back to initialize") func failedSignInAfterDeadlineThrows() async throws { - let host = "\(UUID().uuidString).answering.test" - let authorizer = SlowSignInAuthorizer(signIn: .seconds(2), succeeds: false) - let client = Client( - name: "probe", version: "1.0", - configuration: .init(protocolMode: .automatic, discoveryTimeout: .seconds(1))) - - await #expect(throws: (any Swift.Error).self) { - try await client.connect( - transport: ChallengedDiscoverProtocol.transport(host: host, authorizer: authorizer)) + for timeout in Self.discoveryTimeouts { + let attempt = SignInAttempt(timeout: timeout, succeeds: false) + let connecting = Task { try await attempt.connect() } + guard try await attempt.timerWaitsForSignIn() else { + await attempt.abandon(connecting) + continue + } + attempt.authorizer.release() + let outcome = await attempt.outcome(of: connecting) + #expect(outcome.error != nil, "\(outcome)") + #expect(attempt.authorizer.challenges == 1) + #expect(ChallengedDiscoverProtocol.state.methods(of: attempt.host).isEmpty) + await attempt.client.disconnect() + return } - #expect(authorizer.challenges == 1) - #expect(ChallengedDiscoverProtocol.state.methods(of: host).isEmpty) - await client.disconnect() + Issue.record("The sign-in of server/discover started after every discovery timeout") } // The sign-in ignores cancellation, so only the discovery timer's // cancellation handler can end its wait. @Test("Cancelling connect during sign-in stops waiting promptly") func cancellingConnectDuringSignIn() async throws { - let host = "\(UUID().uuidString).answering.test" - let authorizer = SlowSignInAuthorizer(untilReleased: true) - let transport = ChallengedDiscoverProtocol.transport(host: host, authorizer: authorizer) - let client = Client( + for timeout in Self.discoveryTimeouts { + let attempt = SignInAttempt(timeout: timeout) + let connecting = Task { try await attempt.connect() } + guard try await attempt.timerWaitsForSignIn() else { + await attempt.abandon(connecting) + continue + } + connecting.cancel() + + let finished = await withTaskGroup(of: Bool.self) { group in + group.addTask { + _ = try? await connecting.value + return true + } + group.addTask { + try? await Task.sleep(for: .seconds(5)) + return false + } + let first = await group.next() ?? false + group.cancelAll() + return first + } + #expect(finished) + let deadline = ContinuousClock.now + .seconds(5) + while await attempt.transport.authorizationWaiterCount > 0, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + #expect(await attempt.transport.authorizationWaiterCount == 0) + #expect(attempt.authorizer.signInsEnded == 0) + attempt.authorizer.release() + await attempt.client.disconnect() + return + } + Issue.record("The sign-in of server/discover started after every discovery timeout") + } + } + + /// One attempt of a discovery timeout test: a client in automatic mode, + /// with `timeout` as its discovery timeout, connecting to `host` through + /// a sign-in that lasts until ``SlowSignInAuthorizer/release()``. + private struct SignInAttempt: Sendable { + let host: String + let authorizer: SlowSignInAuthorizer + let transport: HTTPClientTransport + let client: Client + let timeout: Duration + /// Before `connect`, so before the discovery timer starts. + let start = ContinuousClock.now + + init(timeout: Duration, host suffix: String = "answering.test", succeeds: Bool = true) { + host = "\(UUID().uuidString).\(suffix)" + authorizer = SlowSignInAuthorizer(succeeds: succeeds) + transport = ChallengedDiscoverProtocol.transport(host: host, authorizer: authorizer) + client = Client( name: "probe", version: "1.0", - configuration: .init(protocolMode: .automatic, discoveryTimeout: .seconds(1))) + configuration: .init(protocolMode: .automatic, discoveryTimeout: timeout)) + self.timeout = timeout + } + + func connect() async throws -> Client.ConnectionInfo { + try await client.connect(transport: transport) + } - let connecting = Task { try await client.connect(transport: transport) } - // The discovery timer passes its deadline and waits for the sign-in. - var deadline = ContinuousClock.now + .seconds(10) - while await transport.authorizationWaiterCount == 0, ContinuousClock.now < deadline { + /// Waits until the discovery timer has passed its deadline and waits + /// for the sign-in of `server/discover`. `false` when the sign-in + /// started after that deadline: the probe then timed out first and + /// `connect` moved on to `initialize`, so the attempt does not test + /// the timer. A sign-in that starts before the deadline is that of + /// `server/discover`, because `initialize` is sent only after it. + func timerWaitsForSignIn() async throws -> Bool { + let deadline = start + timeout + while authorizer.firstSignInStart == nil, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + guard let started = authorizer.firstSignInStart, started < deadline else { return false } + let limit = deadline + .seconds(10) + while await transport.authorizationWaiterCount == 0, ContinuousClock.now < limit { try await Task.sleep(for: .milliseconds(10)) } #expect(await transport.authorizationWaiterCount == 1) - connecting.cancel() + return true + } - let finished = await withTaskGroup(of: Bool.self) { group in - group.addTask { - _ = try? await connecting.value - return true - } - group.addTask { - try? await Task.sleep(for: .seconds(5)) - return false - } - let first = await group.next() ?? false - group.cancelAll() - return first + /// The outcome of `connecting`. One still running after 30 seconds is + /// recorded as an issue, with the attempt's state, and cancelled, so a + /// stuck `connect` does not stall the suite. + func outcome( + of connecting: Task, sourceLocation: SourceLocation = #_sourceLocation + ) async -> Outcome { + let result = await MCPTests.outcome(within: .seconds(30)) { try await connecting.value } + if result.didTimeOut { + Issue.record( + """ + connect did not return: discovery timeout \(timeout), \(authorizer.challenges) sign-ins, \ + \(authorizer.signInsEnded) ended, \(await transport.authorizationWaiterCount) waiting, \ + authorized \(ChallengedDiscoverProtocol.state.methods(of: host)) + """, sourceLocation: sourceLocation) + connecting.cancel() + authorizer.release() } - #expect(finished) - deadline = ContinuousClock.now + .seconds(5) - while await transport.authorizationWaiterCount > 0, ContinuousClock.now < deadline { - try await Task.sleep(for: .milliseconds(10)) - } - #expect(await transport.authorizationWaiterCount == 0) - #expect(authorizer.signInsEnded == 0) + return result + } + + /// Ends an attempt that did not test the timer. + func abandon(_ connecting: Task) async { authorizer.release() + _ = await outcome(of: connecting) await client.disconnect() } } - /// Signs in on a 401 after `signIn`, like a user at a browser, then - /// authorizes every request when `succeeds` is `true`. With - /// `untilReleased`, the sign-in ignores cancellation and lasts until - /// ``release()``. + /// Signs in on a 401 like a user at a browser, then authorizes every + /// request when `succeeds` is `true`. The sign-in ignores cancellation + /// and lasts until ``release()``. private final class SlowSignInAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { private struct SignInDenied: LocalizedError { var errorDescription: String? { "User cancelled sign-in" } } private let lock = NSLock() - private let signIn: Duration private let succeeds: Bool - private let untilReleased: Bool private var signedIn = false private var challengeCount = 0 + private var firstChallenge: ContinuousClock.Instant? private var endedCount = 0 private var released = false /// Every sign-in waiting for ``release()``. Cancelling `connect` can @@ -645,18 +739,18 @@ struct OutgoingMessageTests { /// than one can wait. private var pendingReleases: [CheckedContinuation] = [] - init(signIn: Duration = .zero, succeeds: Bool = true, untilReleased: Bool = false) { - self.signIn = signIn + init(succeeds: Bool = true) { self.succeeds = succeeds - self.untilReleased = untilReleased } var challenges: Int { lock.withLock { challengeCount } } + /// When the first sign-in started, if one has. + var firstSignInStart: ContinuousClock.Instant? { lock.withLock { firstChallenge } } /// Sign-ins that returned or threw. var signInsEnded: Int { lock.withLock { endedCount } } var maxAuthorizationAttempts: Int { 2 } - /// Ends every sign-in of `untilReleased`. + /// Ends every sign-in, and lets later ones end at once. func release() { let pending = lock.withLock { released = true @@ -676,18 +770,17 @@ struct OutgoingMessageTests { statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, session: URLSession ) async throws -> Bool { - lock.withLock { challengeCount += 1 } + lock.withLock { + challengeCount += 1 + if firstChallenge == nil { firstChallenge = ContinuousClock.now } + } defer { lock.withLock { endedCount += 1 } } - if untilReleased { - await withCheckedContinuation { continuation in - let now = lock.withLock { - if !released { pendingReleases.append(continuation) } - return released - } - if now { continuation.resume() } + await withCheckedContinuation { continuation in + let now = lock.withLock { + if !released { pendingReleases.append(continuation) } + return released } - } else { - try await Task.sleep(for: signIn) + if now { continuation.resume() } } guard succeeds else { throw SignInDenied() } lock.withLock { signedIn = true } diff --git a/Tests/MCPTests/ClientReceiveLoopTerminationTests.swift b/Tests/MCPTests/ClientReceiveLoopTerminationTests.swift index c046a148..b9902480 100644 --- a/Tests/MCPTests/ClientReceiveLoopTerminationTests.swift +++ b/Tests/MCPTests/ClientReceiveLoopTerminationTests.swift @@ -9,7 +9,7 @@ import Testing @preconcurrency import SystemPackage #endif -@Suite("Client receive loop termination", .timeLimit(.minutes(1))) +@Suite("Client receive loop termination", .timeLimit(.minutes(2))) struct ClientReceiveLoopTerminationTests { /// How long a test waits for something it expects to finish. The limit is /// generous because the whole test run shares the cooperative thread pool, diff --git a/Tests/MCPTests/ClientTests.swift b/Tests/MCPTests/ClientTests.swift index 43ff826f..356377cc 100644 --- a/Tests/MCPTests/ClientTests.swift +++ b/Tests/MCPTests/ClientTests.swift @@ -3,7 +3,7 @@ import Testing @testable import MCP -@Suite("Client Tests", .timeLimit(.minutes(1))) +@Suite("Client Tests", .timeLimit(.minutes(2))) struct ClientTests { @Test("Client connect and disconnect") func testClientConnectAndDisconnect() async throws { @@ -42,7 +42,7 @@ struct ClientTests { @Test( "Ping request", - .timeLimit(.minutes(1)) + .timeLimit(.minutes(2)) ) func testClientPing() async throws { let transport = MockTransport() @@ -717,7 +717,7 @@ struct ClientTests { } } -@Suite("Client undecodable responses", .timeLimit(.minutes(1))) +@Suite("Client undecodable responses", .timeLimit(.minutes(2))) struct ClientUndecodableResponseTests { private struct ServerResult: MCP.Method { static let name = "test/malformed-result" diff --git a/Tests/MCPTests/DeprecationNoticeTests.swift b/Tests/MCPTests/DeprecationNoticeTests.swift index 12bf82c6..a23f140b 100644 --- a/Tests/MCPTests/DeprecationNoticeTests.swift +++ b/Tests/MCPTests/DeprecationNoticeTests.swift @@ -8,7 +8,7 @@ import Testing // negotiated. The SDK logs a notice once for each process; each test runs // with its own set of notices. -@Suite("Deprecation notices (SEP-2577)", .timeLimit(.minutes(1))) +@Suite("Deprecation notices (SEP-2577)", .timeLimit(.minutes(2))) struct DeprecationNoticeTests { private func notices(_ log: CapturingLogHandler) -> [String] { log.messages.filter { $0.contains("deprecated by the specification (SEP-2577)") } diff --git a/Tests/MCPTests/HTTPClientReliabilityTests.swift b/Tests/MCPTests/HTTPClientReliabilityTests.swift index 9ac8157e..4fc39d6c 100644 --- a/Tests/MCPTests/HTTPClientReliabilityTests.swift +++ b/Tests/MCPTests/HTTPClientReliabilityTests.swift @@ -318,7 +318,7 @@ struct HTTPClientConnectionLimitTests { return nil } - @Test("Disconnect ends a response stream waiting a server-chosen delay to resume", .timeLimit(.minutes(1))) + @Test("Disconnect ends a response stream waiting a server-chosen delay to resume", .timeLimit(.minutes(2))) func disconnectEndsResumptionWait() async throws { let (transport, key, logs) = makeLoggingTransport() let requests = RecordedRequests() @@ -335,7 +335,7 @@ struct HTTPClientConnectionLimitTests { #expect(await requests.gets.isEmpty) } - @Test("notifications/cancelled stops reading and resuming the cancelled request's stream", .timeLimit(.minutes(1))) + @Test("notifications/cancelled stops reading and resuming the cancelled request's stream", .timeLimit(.minutes(2))) func cancelledNotificationStopsPost() async throws { let (transport, key, logs) = makeLoggingTransport() let requests = RecordedRequests() @@ -390,7 +390,7 @@ struct HTTPClientConnectionLimitTests { #expect(count <= 15) } - @Test("A GET resume refused with 400 is followed by a fresh GET", .timeLimit(.minutes(1))) + @Test("A GET resume refused with 400 is followed by a fresh GET", .timeLimit(.minutes(2))) func clearsLastEventIDAfter400() async throws { let (transport, key) = makeTransport(streaming: true) let requests = RecordedRequests() @@ -410,7 +410,7 @@ struct HTTPClientConnectionLimitTests { @Test( "A GET stream that fails on a line over the limit reconnects without its Last-Event-ID", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func getStreamDropsEventIDAfterOversizedLine() async throws { let (transport, key) = makeTransport(streaming: true) let requests = RecordedRequests() @@ -429,7 +429,7 @@ struct HTTPClientConnectionLimitTests { #expect(ids.prefix(2) == [nil, nil]) } - @Test("A 401 on the GET stream goes to the authorizer and the GET is retried", .timeLimit(.minutes(1))) + @Test("A 401 on the GET stream goes to the authorizer and the GET is retried", .timeLimit(.minutes(2))) func getStreamHandlesChallenge() async throws { let authorizer = ChallengeCountingAuthorizer() let (transport, key) = makeTransport(streaming: true, authorizer: authorizer) @@ -475,7 +475,7 @@ struct HTTPClientConnectionLimitTests { await transport.disconnect() } - @Test("A 401 on a POST gives the authorizer the Authorization the POST carried", .timeLimit(.minutes(1))) + @Test("A 401 on a POST gives the authorizer the Authorization the POST carried", .timeLimit(.minutes(2))) func postChallengePassesSentAuthorization() async throws { let authorizer = ChallengeCountingAuthorizer() let (transport, key) = makeTransport(authorizer: authorizer) @@ -492,7 +492,7 @@ struct HTTPClientConnectionLimitTests { await transport.disconnect() } - @Test("A 405 to a POST does not stop the GET stream of the session that follows", .timeLimit(.minutes(1))) + @Test("A 405 to a POST does not stop the GET stream of the session that follows", .timeLimit(.minutes(2))) func postMethodNotAllowedKeepsGetStream() async throws { let (transport, key) = makeTransport(streaming: true, sseInitializationTimeout: 30) let requests = RecordedRequests() @@ -526,7 +526,7 @@ struct HTTPClientConnectionLimitTests { @Test( "A 404 on the GET stream stops the stream, and the next request reports the expiry", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func getNotFoundExpiresSession() async throws { let (messages, sink) = AsyncStream.makeStream() let logger = Logger(label: "mcp.test.reliability") { _ in StreamingLogHandler(sink: sink) } @@ -575,7 +575,7 @@ struct HTTPClientConnectionLimitTests { @Test( "Concurrent POSTs on an expired session all report the expiry, and the GET stream stops", - .timeLimit(.minutes(1)), arguments: [false, true]) + .timeLimit(.minutes(2)), arguments: [false, true]) func concurrentPostsOnExpiredSession(withErrorBody: Bool) async throws { let (messages, sink) = AsyncStream.makeStream() let logger = Logger(label: "mcp.test.reliability") { _ in StreamingLogHandler(sink: sink) } @@ -636,7 +636,7 @@ struct HTTPClientConnectionLimitTests { } @Test( - "A 404 to a GET without the session ID does not end the session", .timeLimit(.minutes(1))) + "A 404 to a GET without the session ID does not end the session", .timeLimit(.minutes(2))) func getNotFoundWithoutSessionHeader() async throws { // A proxy-like modifier strips the session ID from GETs. let (transport, key) = makeTransport( @@ -662,7 +662,7 @@ struct HTTPClientConnectionLimitTests { @Test( "A CancellationError from the authorizer is thrown as is", - .timeLimit(.minutes(1)), + .timeLimit(.minutes(2)), arguments: [ ("validate", "POST"), ("headers", "POST"), ("challenge", "POST"), ("challenge", "stateless POST"), ("challenge", "resumption GET"), diff --git a/Tests/MCPTests/HTTPClientResumptionTests.swift b/Tests/MCPTests/HTTPClientResumptionTests.swift index 5150e365..59f4cf39 100644 --- a/Tests/MCPTests/HTTPClientResumptionTests.swift +++ b/Tests/MCPTests/HTTPClientResumptionTests.swift @@ -144,7 +144,7 @@ import Testing await transport.disconnect() } - @Test("The request fails after the most resumptions", .timeLimit(.minutes(1))) + @Test("The request fails after the most resumptions", .timeLimit(.minutes(2))) func failsAfterMaxResumptions() async throws { let (transport, key) = makeTransport() let requests = Requests() @@ -165,7 +165,7 @@ import Testing await transport.disconnect() } - @Test("Resumptions that deliver messages do not use up the most resumptions", .timeLimit(.minutes(1))) + @Test("Resumptions that deliver messages do not use up the most resumptions", .timeLimit(.minutes(2))) func resumesPastMaxWhileMessagesArrive() async throws { let (transport, key) = makeTransport() let requests = Requests() @@ -186,7 +186,7 @@ import Testing await transport.disconnect() } - @Test("Resumptions that replay the same message use up the most resumptions", .timeLimit(.minutes(1))) + @Test("Resumptions that replay the same message use up the most resumptions", .timeLimit(.minutes(2))) func replayedMessageIsNoProgress() async throws { let (transport, key) = makeTransport() let requests = Requests() @@ -264,7 +264,7 @@ import Testing await transport.disconnect() } - @Test("A line over the limit fails the request without resuming", .timeLimit(.minutes(1))) + @Test("A line over the limit fails the request without resuming", .timeLimit(.minutes(2))) func oversizedLineIsNotResumed() async throws { let (transport, key) = makeTransport() let requests = Requests() @@ -345,7 +345,7 @@ import Testing #expect(delivered == [answer]) } - @Test("A request cancelled during its last resumption does not fail", .timeLimit(.minutes(1))) + @Test("A request cancelled during its last resumption does not fail", .timeLimit(.minutes(2))) func cancelledDuringLastResumption() async throws { let key = UUID().uuidString let configuration = URLSessionConfiguration.ephemeral diff --git a/Tests/MCPTests/HTTPClientTransportTests.swift b/Tests/MCPTests/HTTPClientTransportTests.swift index e1272825..ed16883b 100644 --- a/Tests/MCPTests/HTTPClientTransportTests.swift +++ b/Tests/MCPTests/HTTPClientTransportTests.swift @@ -120,15 +120,8 @@ import Testing return request } - /// Set by `stopLoading()`. swift-corelibs-foundation traps when a - /// protocol calls its client for a task it already cancelled, so each - /// callback checks it first. The lock is not held during a callback: - /// corelibs can call `stopLoading()` from its work queue while a - /// callback waits for that queue. - private let stateLock = NSLock() - private var stopped = false - - private var isStopped: Bool { stateLock.withLock { stopped } } + /// Ends the client calls at `stopLoading()`: see ``URLProtocolStop``. + private let stop = URLProtocolStop() override func startLoading() { let loader = SendableURLProtocol(self) @@ -138,20 +131,16 @@ import Testing private func load() async { do { let (response, data) = try await executeHandler(for: request) - guard !isStopped else { return } - client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) - guard !isStopped else { return } - client?.urlProtocol(self, didLoad: data) - guard !isStopped else { return } - client?.urlProtocolDidFinishLoading(self) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didLoad: data) } + stop.ifLoading(self) { [self] in client?.urlProtocolDidFinishLoading(self) } } catch { - guard !isStopped else { return } - client?.urlProtocol(self, didFailWithError: error) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didFailWithError: error) } } } override func stopLoading() { - stateLock.withLock { stopped = true } + stop.stop() } static func verifyCallCounts( @@ -1153,7 +1142,7 @@ import Testing @Test( "Client with HTTP Transport complete flow", .httpClientTransportSetup, - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testClientFlow() async throws { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [MockURLProtocol.self] @@ -2528,12 +2517,9 @@ import Testing /// Reports two responses for one request, each with half of a JSON-RPC /// response that is valid only when the halves are joined. private final class TwoResponsesURLProtocol: URLProtocol { - /// Set by `stopLoading()`, as in `IsolatedMockURLProtocol`: the - /// client cancels the task at the second response, and corelibs traps - /// on a call for a cancelled task. - private let stateLock = NSLock() - private var stopped = false - private var isStopped: Bool { stateLock.withLock { stopped } } + /// The client cancels the task at the second response, so the calls + /// after it end at `stopLoading()`: see ``URLProtocolStop``. + private let stop = URLProtocolStop() override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } @@ -2541,15 +2527,13 @@ import Testing let response = HTTPURLResponse( url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["Content-Type": "application/json"])! - client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) - client?.urlProtocol(self, didLoad: Data(#"{"jsonrpc":"2.0","#.utf8)) - client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) - guard !isStopped else { return } - client?.urlProtocol(self, didLoad: Data(#""id":"r1","result":{}}"#.utf8)) - guard !isStopped else { return } - client?.urlProtocolDidFinishLoading(self) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didLoad: Data(#"{"jsonrpc":"2.0","#.utf8)) } + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didLoad: Data(#""id":"r1","result":{}}"#.utf8)) } + stop.ifLoading(self) { [self] in client?.urlProtocolDidFinishLoading(self) } } - override func stopLoading() { stateLock.withLock { stopped = true } } + override func stopLoading() { stop.stop() } } /// Answers a request with the first half of a JSON-RPC response and keeps @@ -2623,11 +2607,10 @@ import Testing override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } - /// swift-corelibs-foundation traps on a callback after `stopLoading()`. + /// Ends the client calls at `stopLoading()`: see ``URLProtocolStop``. + private let stop = URLProtocolStop() private let stateLock = NSLock() - private var stopped = false private var log: Log? - private var isStopped: Bool { stateLock.withLock { stopped } } override func startLoading() { let key = request.value(forHTTPHeaderField: Self.keyHeader) ?? "" @@ -2639,40 +2622,42 @@ import Testing var headers = ["Content-Type": "application/json"] if let contentLength = script.contentLength { headers["Content-Length"] = String(contentLength) } let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: headers)! - client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } let loader = SendableURLProtocol(self) - DispatchQueue.global().async { loader.value.stream(script) } + // A thread of its own: the stream blocks while it waits, which on a + // Dispatch thread would hold one of Swift's pool on Linux. + Thread.detachNewThread { loader.value.stream(script) } } private func stream(_ script: Script) { var sent = 0 var paused = false while true { - guard !isStopped else { return } + guard !stop.isStopped else { return } if let pauseAfter = script.pauseAfter, sent > pauseAfter, !paused { paused = true let deadline = Date().addingTimeInterval(30) - while !isStopped && Date() < deadline { Thread.sleep(forTimeInterval: 0.005) } - guard !isStopped else { return } + while !stop.isStopped && Date() < deadline { Thread.sleep(forTimeInterval: 0.005) } + guard !stop.isStopped else { return } } guard sent < script.length else { break } let count = min(Self.chunk, script.length - sent) - // Counted first, so the count is in place once the client has the bytes. - stateLock.withLock { log }?.delivered(count) sent += count - client?.urlProtocol(self, didLoad: Data(repeating: 0x20, count: count)) + stop.ifLoading(self) { [self] in + // Counted first, so the count is in place once the client has the bytes. + stateLock.withLock { log }?.delivered(count) + client?.urlProtocol(self, didLoad: Data(repeating: 0x20, count: count)) + } + } + stop.ifLoading(self) { [self] in + stateLock.withLock { log }?.stop() + client?.urlProtocolDidFinishLoading(self) } - guard !isStopped else { return } - stateLock.withLock { log }?.stop() - client?.urlProtocolDidFinishLoading(self) } override func stopLoading() { - let log = stateLock.withLock { () -> Log? in - stopped = true - return self.log - } - log?.stop() + stop.stop() + stateLock.withLock { log }?.stop() } } @@ -2698,6 +2683,22 @@ import Testing (HTTPURLResponse(url: endpoint, statusCode: status, httpVersion: "HTTP/1.1", headerFields: [:])!, Data()) } + #if canImport(FoundationNetworking) + // With a URL cache, swift-corelibs-foundation can fail a task + // cancelled during its cache lookup after it has left the session's + // registry, which traps. + @Test("The streaming session has no URL cache, and the configuration it was given keeps its own") + func streamingSessionHasNoURLCache() { + let configuration = URLSessionConfiguration.ephemeral + let cache = configuration.urlCache + #expect(cache != nil) + let streaming = StreamingSession(configuration: configuration) + defer { streaming.invalidate() } + #expect(streaming.session.configuration.urlCache == nil) + #expect(configuration.urlCache === cache) + } + #endif + @Test( "A request whose authorizer is awaited across disconnect() fails instead of trapping", arguments: [SuspendingAuthorizer.Stage.prepare, .challenge]) @@ -2756,7 +2757,7 @@ import Testing _ = try await session.responseBody(for: URLRequest(url: endpoint), streaming: streaming) } let result = await outcome(within: .seconds(2)) { try await task.value } - #expect(result.error != nil) + #expect(result.error != nil, "\(result)") } @Test("A response body read from a task cancelled while it arrives throws instead of ending early") @@ -2800,7 +2801,7 @@ import Testing #expect(delivered.isEmpty) } - @Test("A JSON response body over 16 MiB fails the request and is not read further", .timeLimit(.minutes(1))) + @Test("A JSON response body over 16 MiB fails the request and is not read further", .timeLimit(.minutes(2))) func oversizedJSONBody() async throws { let limit = ServerSentEventParser.maxEventLength let chunk = LongJSONBodyURLProtocol.chunk @@ -2822,7 +2823,7 @@ import Testing #expect(messages == 0) } - @Test("A JSON response with a Content-Length over 16 MiB fails before its body is read", .timeLimit(.minutes(1))) + @Test("A JSON response with a Content-Length over 16 MiB fails before its body is read", .timeLimit(.minutes(2))) func oversizedJSONContentLength() async throws { let chunk = LongJSONBodyURLProtocol.chunk // The body waits before its first chunk until the client stops it. @@ -2840,7 +2841,7 @@ import Testing await transport.disconnect() } - @Test("A JSON response body one byte over 16 MiB fails the request", .timeLimit(.minutes(1))) + @Test("A JSON response body one byte over 16 MiB fails the request", .timeLimit(.minutes(2))) func jsonBodyOneByteOverLimit() async throws { let limit = ServerSentEventParser.maxEventLength // The body stays open after its last byte until the client stops it. @@ -2860,7 +2861,7 @@ import Testing #expect(messages == 0) } - @Test("A JSON response body of 16 MiB is delivered whole", .timeLimit(.minutes(1))) + @Test("A JSON response body of 16 MiB is delivered whole", .timeLimit(.minutes(2))) func jsonBodyAtLimit() async throws { let limit = ServerSentEventParser.maxEventLength let (configuration, _) = LongJSONBodyURLProtocol.configuration(.init(length: limit, contentLength: limit)) @@ -2884,8 +2885,8 @@ import Testing let transport = HTTPClientTransport( endpoint: endpoint, configuration: configuration, streaming: false) try await transport.connect() - let result = await outcome(within: .seconds(5)) { [request] in try await transport.send(request) } - #expect(result.error != nil) + let result = await outcome(within: .seconds(30)) { [request] in try await transport.send(request) } + #expect(result.error != nil, "\(result)") await transport.disconnect() } @@ -3013,15 +3014,11 @@ import Testing override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } - /// Set by `stopLoading()`: swift-corelibs-foundation traps when a - /// protocol calls its client for a task it already cancelled. The lock - /// is not held during a callback. + /// Ends the client calls at `stopLoading()`: see ``URLProtocolStop``. + private let stop = URLProtocolStop() private let stateLock = NSLock() - private var stopped = false private var server: ReleaseTestServer? - private var isStopped: Bool { stateLock.withLock { stopped } } - override func startLoading() { let key = request.value(forHTTPHeaderField: Self.keyHeader) ?? "" guard let server = Self.registry.lock.withLock({ Self.registry.servers[key] }) else { @@ -3033,27 +3030,22 @@ import Testing } override func stopLoading() { - let server = stateLock.withLock { () -> ReleaseTestServer? in - stopped = true - return self.server - } - server?.stopped(self) + stop.stop() + stateLock.withLock { server }?.stopped(self) } func reply(status: Int, contentType: String, body: Data?, finish: Bool = true) { let response = HTTPURLResponse( url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: ["Content-Type": contentType])! - guard !isStopped else { return } - client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } if let body { write(body) } - guard finish, !isStopped else { return } - client?.urlProtocolDidFinishLoading(self) + guard finish else { return } + stop.ifLoading(self) { [self] in client?.urlProtocolDidFinishLoading(self) } } func write(_ data: Data) { - guard !isStopped else { return } - client?.urlProtocol(self, didLoad: data) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didLoad: data) } } } diff --git a/Tests/MCPTests/HTTPServerTransportTests.swift b/Tests/MCPTests/HTTPServerTransportTests.swift index 314edfc6..1f593925 100644 --- a/Tests/MCPTests/HTTPServerTransportTests.swift +++ b/Tests/MCPTests/HTTPServerTransportTests.swift @@ -1464,7 +1464,7 @@ struct StatefulHTTPServerTransportTests { await transport.disconnect() } - @Test("Resuming a request's stream finishes the stream it replaces", .timeLimit(.minutes(1))) + @Test("Resuming a request's stream finishes the stream it replaces", .timeLimit(.minutes(2))) func testResumeFinishesReplacedStream() async throws { let transport = makeStatefulTransport() let sessionID = try await initializeSession(transport: transport) diff --git a/Tests/MCPTests/Helpers/OffThreadPool.swift b/Tests/MCPTests/Helpers/OffThreadPool.swift index fcc9e07d..0f55a6d6 100644 --- a/Tests/MCPTests/Helpers/OffThreadPool.swift +++ b/Tests/MCPTests/Helpers/OffThreadPool.swift @@ -1,6 +1,6 @@ import Foundation -/// Runs `work` on a Dispatch thread instead of Swift's cooperative pool. +/// Runs `work` on a thread of its own instead of Swift's cooperative pool. /// /// Use it for test code that blocks a thread or computes for a long time, such /// as a blocking `read()` on a pipe or megabytes fed to a parser byte by byte. @@ -8,8 +8,13 @@ import Foundation /// simulator), and every other test running in parallel waits for it. Running /// the tests with `LIBDISPATCH_COOPERATIVE_POOL_STRICT=1`, which gives the pool /// a single thread, shows any test that still blocks it: that test never ends. +/// +/// A Dispatch queue is no way around the pool on Linux: there the pool runs on +/// libdispatch's global queues, so a `read()` blocked on `DispatchQueue.global()` +/// holds one of the pool's threads all the same, and on two CPUs a few of them +/// stopped every test in the process until the reads returned. func offThreadPool(_ work: @escaping @Sendable () throws -> T) async throws -> T { try await withCheckedThrowingContinuation { continuation in - DispatchQueue.global().async { continuation.resume(with: Result { try work() }) } + Thread { continuation.resume(with: Result { try work() }) }.start() } } diff --git a/Tests/MCPTests/Helpers/URLCacheProbe.swift b/Tests/MCPTests/Helpers/URLCacheProbe.swift new file mode 100644 index 00000000..b9f777c0 --- /dev/null +++ b/Tests/MCPTests/Helpers/URLCacheProbe.swift @@ -0,0 +1,77 @@ +import Foundation + +#if canImport(FoundationNetworking) + import FoundationNetworking + + /// Records, for each request it answers, whether the session the request + /// ran in had a URL cache. + /// + /// A request whose URL has `redirect_uri` and `state` query items gets a + /// 302 to `redirect_uri` with `code=probe` and that `state`, as an + /// authorization endpoint answers; any other gets a 200 with `{}`. Give + /// each request a path of its own and read the result with + /// ``hadURLCache(path:)``. + /// + /// swift-corelibs-foundation keeps the session of a task in an internal + /// property, which the probe reads with `Mirror`. + final class URLCacheProbe: URLProtocol { + /// `@unchecked Sendable`: `lock` guards `hadCache`. + private final class Records: @unchecked Sendable { + let lock = NSLock() + var hadCache: [String: Bool] = [:] + } + private static let records = Records() + private let stop = URLProtocolStop() + + /// Whether the session of the request to `path` had a URL cache, or + /// `nil` if no request to `path` reached the probe. + static func hadURLCache(path: String) -> Bool? { + records.lock.withLock { records.hadCache[path] } + } + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + guard let url = request.url else { return } + let hadCache = Self.session(of: self).configuration.urlCache != nil + Self.records.lock.withLock { Self.records.hadCache[url.path] = hadCache } + let query = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + let response: HTTPURLResponse + if let redirectURI = query.first(where: { $0.name == "redirect_uri" })?.value, + let state = query.first(where: { $0.name == "state" })?.value + { + response = HTTPURLResponse( + url: url, statusCode: 302, httpVersion: "HTTP/1.1", + headerFields: ["Location": "\(redirectURI)?code=probe&state=\(state)"])! + } else { + response = HTTPURLResponse( + url: url, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"])! + } + stop.ifLoading(self) { [self] in + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + } + if response.statusCode == 200 { + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didLoad: Data("{}".utf8)) } + } + stop.ifLoading(self) { [self] in client?.urlProtocolDidFinishLoading(self) } + } + + override func stopLoading() { stop.stop() } + + /// The session the task of `urlProtocol` runs in, swift-corelibs-foundation's + /// internal `URLSessionTask.session`. + private static func session(of urlProtocol: URLProtocol) -> URLSession { + guard let task = urlProtocol.task else { fatalError("The protocol has no task") } + var mirror: Mirror? = Mirror(reflecting: task) + while let current = mirror { + if let session = current.children.first(where: { $0.label == "session" })?.value as? URLSession { + return session + } + mirror = current.superclassMirror + } + fatalError("URLSessionTask has no session; swift-corelibs-foundation changed") + } + } +#endif diff --git a/Tests/MCPTests/Helpers/URLProtocolStop.swift b/Tests/MCPTests/Helpers/URLProtocolStop.swift new file mode 100644 index 00000000..860864c8 --- /dev/null +++ b/Tests/MCPTests/Helpers/URLProtocolStop.swift @@ -0,0 +1,91 @@ +import Foundation + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +/// Keeps a mock `URLProtocol` from calling its client once `stopLoading()` +/// has been called, and, on swift-corelibs-foundation, makes each call where +/// corelibs makes its own protocols' calls. +/// +/// swift-corelibs-foundation traps ("Trying to access a behaviour for a task +/// that in not in the registry") when a protocol calls its client for a task +/// that has left its session, and a cancelled task leaves it soon after +/// `stopLoading()` returns. A flag checked before each call is not enough: the +/// task can be cancelled between the check and the call. ``ifLoading(_:)`` +/// holds a lock across both, and ``stop()``, called from `stopLoading()`, waits +/// for it. +/// +/// The lock is recursive because corelibs can call `stopLoading()` on the +/// thread of a client call (`suspend()` from a 401 runs it with +/// `workQueue.sync`). A client call can also wait for the session's work +/// queue while `stopLoading()` runs there, on another thread, so ``stop()`` +/// waits at most a second: by then the call is inside corelibs, past the +/// point where it looks the task up. +/// +/// `@unchecked Sendable`: the locks guard `stopped`. +final class URLProtocolStop: @unchecked Sendable { + private let callLock = NSRecursiveLock() + private let flagLock = NSLock() + private var stopped = false + + /// Whether ``stop()`` has been called. + var isStopped: Bool { flagLock.withLock { stopped } } + + /// Runs `call`, a call to the client of `urlProtocol`, unless ``stop()`` + /// has been called by then. + /// + /// On swift-corelibs-foundation the call runs later, on the work queue of + /// the protocol's task, after the calls before it. Every client method + /// there reads the session's task registry on the calling thread, while + /// the session's work queue adds and removes tasks, so a call from another + /// thread races with the session's other tasks and can crash the process. + /// corelibs makes its own protocols' calls on that queue, and runs + /// `stopLoading()` there too. + func ifLoading(_ urlProtocol: URLProtocol, _ call: @escaping () -> Void) { + #if canImport(FoundationNetworking) + // Only a shortcut: the check on the work queue decides. + guard !isStopped else { return } + // `nonisolated(unsafe)`: `call` runs once, on the task's serial work + // queue, as corelibs runs the calls of its own protocols. + nonisolated(unsafe) let call = call + Self.workQueue(of: urlProtocol).async { [self] in ifLoading(call) } + #else + ifLoading(call) + #endif + } + + /// Runs `call`, a call to the protocol's client, unless ``stop()`` has + /// been called. + func ifLoading(_ call: () -> Void) { + callLock.lock() + defer { callLock.unlock() } + guard !isStopped else { return } + call() + } + + /// Ends the client calls of ``ifLoading(_:)``, once a call in progress + /// has returned. + func stop() { + let locked = callLock.lock(before: Date().addingTimeInterval(1)) + flagLock.withLock { stopped = true } + if locked { callLock.unlock() } + } + + #if canImport(FoundationNetworking) + /// The serial queue swift-corelibs-foundation runs the task of + /// `urlProtocol` on, its internal `URLSessionTask.workQueue`, which + /// targets the session's work queue. + static func workQueue(of urlProtocol: URLProtocol) -> DispatchQueue { + guard let task = urlProtocol.task else { fatalError("The protocol has no task") } + var mirror: Mirror? = Mirror(reflecting: task) + while let current = mirror { + if let queue = current.children.first(where: { $0.label == "workQueue" })?.value as? DispatchQueue { + return queue + } + mirror = current.superclassMirror + } + fatalError("URLSessionTask has no workQueue; swift-corelibs-foundation changed") + } + #endif +} diff --git a/Tests/MCPTests/MultiRoundTripTests.swift b/Tests/MCPTests/MultiRoundTripTests.swift index 3d3c37d1..346566c7 100644 --- a/Tests/MCPTests/MultiRoundTripTests.swift +++ b/Tests/MCPTests/MultiRoundTripTests.swift @@ -840,7 +840,7 @@ struct MultiRoundTripTests { @Test( "A bridged call cancelled before it asks for input sends no input request", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testBridgeCancelledBeforeAsking() async throws { let (server, progress) = await makeLateAskingServer() let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() @@ -867,7 +867,7 @@ struct MultiRoundTripTests { @Test( "A bridged input request withdrawn while it is being sent is followed by notifications/cancelled", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func testBridgeWithdrawWhileSending() async throws { let (server, progress) = await makeLateAskingServer() let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() diff --git a/Tests/MCPTests/OAuthAuthorizationCodeFlowTests.swift b/Tests/MCPTests/OAuthAuthorizationCodeFlowTests.swift index 85c610e4..86d7bf41 100644 --- a/Tests/MCPTests/OAuthAuthorizationCodeFlowTests.swift +++ b/Tests/MCPTests/OAuthAuthorizationCodeFlowTests.swift @@ -175,4 +175,33 @@ struct OAuthAuthorizationCodeFlowTests { ) #expect(code == "auth-code-123") } + + #if canImport(FoundationNetworking) + // With a URL cache, swift-corelibs-foundation can fail a task + // cancelled during its cache lookup after it has left the session's + // registry, which traps. + @Test("Without a delegate, the authorization request runs in a session with no URL cache") + func performSessionHasNoURLCache() async throws { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [URLCacheProbe.self] + #expect(configuration.urlCache != nil) + let session = URLSession(configuration: configuration) + defer { session.finishTasksAndInvalidate() } + let path = "/authorize/\(UUID().uuidString)" + var components = URLComponents(string: "https://auth.example.com\(path)")! + components.queryItems = [ + URLQueryItem(name: "redirect_uri", value: redirectURI.absoluteString), + URLQueryItem(name: "state", value: "my-state"), + ] + let code = try await flow.perform( + authorizationURL: components.url!, + redirectURI: redirectURI, + state: "my-state", + delegate: nil, + session: session + ) + #expect(code == "probe") + #expect(URLCacheProbe.hadURLCache(path: path) == false) + } + #endif } diff --git a/Tests/MCPTests/OAuthAuthorizerStateTests.swift b/Tests/MCPTests/OAuthAuthorizerStateTests.swift index 03d21cbb..a851cce7 100644 --- a/Tests/MCPTests/OAuthAuthorizerStateTests.swift +++ b/Tests/MCPTests/OAuthAuthorizerStateTests.swift @@ -314,7 +314,7 @@ struct OAuthAuthorizerStateTests { #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) } - @Test("Challenges waiting for an authorization that fails fail with its error", .timeLimit(.minutes(1))) + @Test("Challenges waiting for an authorization that fails fail with its error", .timeLimit(.minutes(2))) func waitersShareFailedAuthorization() async throws { let flow = GatedAuthCodeFlow() flow.error = UserCancelledAuthorization() @@ -343,7 +343,7 @@ struct OAuthAuthorizerStateTests { @Test( "Concurrent 403 step-ups for a token whose step-up the user cancelled ask once and fail", - .timeLimit(.minutes(1))) + .timeLimit(.minutes(2))) func waitersShareCancelledStepUp() async throws { let storage = InMemoryTokenStorage() storage.save( @@ -375,7 +375,7 @@ struct OAuthAuthorizerStateTests { #expect(storage.load()?.value == "narrow") } - @Test("Concurrent 403 step-ups for the same scopes run one token request", .timeLimit(.minutes(1))) + @Test("Concurrent 403 step-ups for the same scopes run one token request", .timeLimit(.minutes(2))) func concurrentStepUps() async throws { let tokens = RecordingTokenClient() let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens) @@ -409,7 +409,7 @@ struct OAuthAuthorizerStateTests { #expect(tokens.calls.count == 1) } - @Test("A challenge waiting for another one stops waiting when cancelled", .timeLimit(.minutes(1))) + @Test("A challenge waiting for another one stops waiting when cancelled", .timeLimit(.minutes(2))) func waitingChallengeIsCancellable() async throws { let flow = GatedAuthCodeFlow() let validator = CountingURLValidator() @@ -683,7 +683,7 @@ struct OAuthAuthorizerStateTests { #expect(storage.load()?.value != renewed.value) } - @Test("A cancelled proactive refresh is tried again by the next request", .timeLimit(.minutes(1))) + @Test("A cancelled proactive refresh is tried again by the next request", .timeLimit(.minutes(2))) func cancelledRefreshTriedAgain() async throws { let storage = InMemoryTokenStorage() let tokens = RecordingTokenClient() diff --git a/Tests/MCPTests/OAuthComponentTestHelpers.swift b/Tests/MCPTests/OAuthComponentTestHelpers.swift index faeb0d87..7d49fb11 100644 --- a/Tests/MCPTests/OAuthComponentTestHelpers.swift +++ b/Tests/MCPTests/OAuthComponentTestHelpers.swift @@ -58,15 +58,8 @@ override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } - /// Set by `stopLoading()`. swift-corelibs-foundation traps when a - /// protocol calls its client for a task it already cancelled, so each - /// callback checks it first. The lock is not held during a callback: - /// corelibs can call `stopLoading()` from its work queue while a - /// callback waits for that queue. - private let stateLock = NSLock() - private var stopped = false - - private var isStopped: Bool { stateLock.withLock { stopped } } + /// Ends the client calls at `stopLoading()`: see ``URLProtocolStop``. + private let stop = URLProtocolStop() override func startLoading() { let loader = SendableURLProtocol(self) @@ -76,20 +69,16 @@ private func load() async { do { let (response, data) = try await executeHandler(for: request) - guard !isStopped else { return } - client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) - guard !isStopped else { return } - client?.urlProtocol(self, didLoad: data) - guard !isStopped else { return } - client?.urlProtocolDidFinishLoading(self) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didLoad: data) } + stop.ifLoading(self) { [self] in client?.urlProtocolDidFinishLoading(self) } } catch { - guard !isStopped else { return } - client?.urlProtocol(self, didFailWithError: error) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didFailWithError: error) } } } override func stopLoading() { - stateLock.withLock { stopped = true } + stop.stop() } } diff --git a/Tests/MCPTests/OAuthURLValidatorTests.swift b/Tests/MCPTests/OAuthURLValidatorTests.swift index 8044ae9f..12ef0414 100644 --- a/Tests/MCPTests/OAuthURLValidatorTests.swift +++ b/Tests/MCPTests/OAuthURLValidatorTests.swift @@ -375,4 +375,25 @@ struct OAuthURLValidatorTests { from: URL(string: "https://auth.example.com/token")!, to: URL(string: "https://auth.example.com/token2")!)) } + + #if canImport(FoundationNetworking) + // With a URL cache, swift-corelibs-foundation can fail a task + // cancelled during its cache lookup after it has left the session's + // registry, which traps. + @Test("A guarded OAuth request runs in a session with no URL cache") + func testGuardedSessionHasNoURLCache() async throws { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [URLCacheProbe.self] + #expect(configuration.urlCache != nil) + let session = URLSession(configuration: configuration) + defer { session.finishTasksAndInvalidate() } + let path = "/token/\(UUID().uuidString)" + let (data, response) = try await session.oauthData( + for: URLRequest(url: URL(string: "https://auth.example.com\(path)")!), + redirects: .none, validator: OAuthURLValidator()) + #expect((response as? HTTPURLResponse)?.statusCode == 200) + #expect(data == Data("{}".utf8)) + #expect(URLCacheProbe.hadURLCache(path: path) == false) + } + #endif } diff --git a/Tests/MCPTests/OffThreadPoolTests.swift b/Tests/MCPTests/OffThreadPoolTests.swift new file mode 100644 index 00000000..735e5f4a --- /dev/null +++ b/Tests/MCPTests/OffThreadPoolTests.swift @@ -0,0 +1,59 @@ +import Foundation +import Testing + +@Suite("offThreadPool") +struct OffThreadPoolTests { + /// Work items that block until all of them have started, or a deadline. + private final class Rendezvous: @unchecked Sendable { + private let condition = NSCondition() + private var started = 0 + private var released = false + let count: Int + + init(count: Int) { self.count = count } + + /// Blocks the calling thread until every item has started and + /// ``release()`` was called, or `deadline`; whether every item started. + func arrive(deadline: Date) -> Bool { + condition.lock() + defer { condition.unlock() } + started += 1 + condition.broadcast() + while !released, condition.wait(until: deadline) {} + return started == count + } + + var startedCount: Int { + condition.lock() + defer { condition.unlock() } + return started + } + + func release() { + condition.lock() + released = true + condition.broadcast() + condition.unlock() + } + } + + @Test("Many blocked work items run at once while async code keeps running") + func blockedWorkRunsAtOnce() async throws { + let rendezvous = Rendezvous(count: 24) + let deadline = Date().addingTimeInterval(10) + try await withThrowingTaskGroup(of: Bool.self) { group in + for _ in 0.. Value { try JSONDecoder().decode(Value.self, from: try #require(data)) } -@Suite("Request ids on a message stream", .timeLimit(.minutes(1))) +@Suite("Request ids on a message stream", .timeLimit(.minutes(2))) struct StreamRequestIDTests { private actor Inbox { private(set) var values: [Value] = [] @@ -281,7 +281,7 @@ struct StreamRequestIDTests { } } -@Suite("Request ids over the stateless HTTP transport", .timeLimit(.minutes(1))) +@Suite("Request ids over the stateless HTTP transport", .timeLimit(.minutes(2))) struct StatelessHTTPRequestIDTests { private func post(_ body: String, headers extra: [String: String] = [:]) async throws -> HTTPResponse { try #require(try await post(body, headers: extra, within: .seconds(30)), "No answer within 30 seconds") diff --git a/Tests/MCPTests/RequestLifecycleTests.swift b/Tests/MCPTests/RequestLifecycleTests.swift index 2209e20d..a21c2332 100644 --- a/Tests/MCPTests/RequestLifecycleTests.swift +++ b/Tests/MCPTests/RequestLifecycleTests.swift @@ -83,7 +83,7 @@ private func text(_ result: CallTool.Result) -> String? { return nil } -@Suite("Request lifecycle", .timeLimit(.minutes(1))) +@Suite("Request lifecycle", .timeLimit(.minutes(2))) struct RequestLifecycleTests { @Test("cancelRequest right after send always cancels, and never overtakes the request") @available(*, deprecated, message: "Uses the deprecated sampling and logging APIs (SEP-2577)") @@ -364,7 +364,7 @@ struct RequestLifecycleTests { } } -@Suite("Server-to-client request limits", .timeLimit(.minutes(1))) +@Suite("Server-to-client request limits", .timeLimit(.minutes(2))) struct ServerToClientLimitTests { /// A raw server end with an initialized handshake client. private func connected( @@ -536,7 +536,7 @@ struct ServerToClientLimitTests { } } -@Suite("Batches", .timeLimit(.minutes(1))) +@Suite("Batches", .timeLimit(.minutes(2))) struct BatchTests { @Test("Batched requests on a stateless connection carry _meta and run the round-trip loop") @available(*, deprecated, message: "Uses the deprecated sampling and logging APIs (SEP-2577)") @@ -671,7 +671,7 @@ private let invalidStreamMessages: [(String, Int, Value)] = [ ("true false", -32700, .null), ] -@Suite("Server replies", .timeLimit(.minutes(1))) +@Suite("Server replies", .timeLimit(.minutes(2))) struct ServerReplyTests { private actor Inbox { var values: [Value] = [] diff --git a/Tests/MCPTests/RoundtripTests.swift b/Tests/MCPTests/RoundtripTests.swift index e10bfde8..9d4dca50 100644 --- a/Tests/MCPTests/RoundtripTests.swift +++ b/Tests/MCPTests/RoundtripTests.swift @@ -13,7 +13,7 @@ import Testing @Suite("Roundtrip Tests") struct RoundtripTests { @Test( - .timeLimit(.minutes(1)) + .timeLimit(.minutes(2)) ) func testRoundtrip() async throws { let (clientToServerRead, clientToServerWrite) = try FileDescriptor.pipe() @@ -100,110 +100,37 @@ struct RoundtripTests { try await server.start(transport: serverTransport) - let initTask = Task { - let result = try await client.connect(transport: clientTransport) - - #expect(result.serverInfo?.name == "TestServer") - #expect(result.serverInfo?.version == "1.0.0") - #expect(result.capabilities.prompts != nil) - #expect(result.capabilities.tools != nil) - #expect(result.protocolVersion == Version.latestHandshake) - } - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - try await Task.sleep(for: .seconds(10)) - initTask.cancel() - throw CancellationError() - } - group.addTask { - try await initTask.value - } - try await group.next() - group.cancelAll() - } - - // Test ping - let pingTask = Task { - try await client.ping() - // Ping doesn't return anything, so just getting here without throwing is success - #expect(Bool(true)) - } - - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - try await Task.sleep(for: .seconds(10)) - pingTask.cancel() - throw CancellationError() - } - group.addTask { - try await pingTask.value - } - try await group.next() - group.cancelAll() - } - - let listToolsTask = Task { - let tools = try await client.listTools().tools - #expect(tools.count == 1) - #expect(tools[0].name == "add") - } - - let callToolTask = Task { - let result = try await client.callTool(name: "add", arguments: ["a": 1, "b": 2]) - #expect(result.isError == nil) - #expect(result.content == [.text(text: "3")]) - } - - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - try await Task.sleep(for: .seconds(10)) - listToolsTask.cancel() - callToolTask.cancel() - throw CancellationError() - } - group.addTask { - try await listToolsTask.value - } - group.addTask { - try await callToolTask.value - } - try await group.next() - group.cancelAll() - } - - // Test listing resources - let listResourcesTask = Task { - let result = try await client.listResources() - #expect(result.resources.count == 2) - #expect(result.resources[0].uri == "test://example.txt") - #expect(result.resources[0].name == "Example Text") - #expect(result.resources[1].uri == "test://data.json") - #expect(result.resources[1].name == "Test Data") - } - - // Test reading a resource - let readResourceTask = Task { - let result = try await client.readResource(uri: "test://example.txt").contents - #expect(result.count == 1) - #expect(result[0] == .text("Hello, World!", uri: "test://example.txt")) - } - - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - try await Task.sleep(for: .seconds(10)) - listResourcesTask.cancel() - readResourceTask.cancel() - throw CancellationError() - } - group.addTask { - try await listResourcesTask.value - } - group.addTask { - try await readResourceTask.value - } - try await group.next() - group.cancelAll() - } + // The test's time limit is the only one: a step that hangs is cancelled + // with the test instead of racing a sleep of its own. + let result = try await client.connect(transport: clientTransport) + #expect(result.serverInfo?.name == "TestServer") + #expect(result.serverInfo?.version == "1.0.0") + #expect(result.capabilities.prompts != nil) + #expect(result.capabilities.tools != nil) + #expect(result.protocolVersion == Version.latestHandshake) + + // Ping doesn't return anything, so not throwing is success. + try await client.ping() + + async let listedTools = client.listTools() + async let calledTool = client.callTool(name: "add", arguments: ["a": 1, "b": 2]) + let tools = try await listedTools.tools + #expect(tools.count == 1) + #expect(tools.first?.name == "add") + let call = try await calledTool + #expect(call.isError == nil) + #expect(call.content == [.text(text: "3")]) + + async let listedResources = client.listResources() + async let readResource = client.readResource(uri: "test://example.txt") + let resources = try await listedResources.resources + #expect(resources.count == 2) + #expect(resources.first?.uri == "test://example.txt") + #expect(resources.first?.name == "Example Text") + #expect(resources.last?.uri == "test://data.json") + #expect(resources.last?.name == "Test Data") + let contents = try await readResource.contents + #expect(contents == [.text("Hello, World!", uri: "test://example.txt")]) await server.stop() await client.disconnect() diff --git a/Tests/MCPTests/SamplingToolsTests.swift b/Tests/MCPTests/SamplingToolsTests.swift index eb6e1434..160e5587 100644 --- a/Tests/MCPTests/SamplingToolsTests.swift +++ b/Tests/MCPTests/SamplingToolsTests.swift @@ -402,7 +402,7 @@ struct SamplingToolWireTests { // MARK: - Capabilities and refusals -@Suite("Sampling with tools: capabilities", .timeLimit(.minutes(1))) +@Suite("Sampling with tools: capabilities", .timeLimit(.minutes(2))) struct SamplingToolCapabilityTests { @Test("The tool loop runs end to end", arguments: [Client.ProtocolMode.handshake, .automatic]) @available(*, deprecated, message: "Uses the deprecated sampling API (SEP-2577)") @@ -576,7 +576,7 @@ private struct ScriptedServer { } } -@Suite("Sampling with tools: client", .timeLimit(.minutes(1))) +@Suite("Sampling with tools: client", .timeLimit(.minutes(2))) struct SamplingToolClientTests { @Test("The client refuses tools it did not declare, before the handler runs") @available(*, deprecated, message: "Uses the deprecated sampling API (SEP-2577)") diff --git a/Tests/MCPTests/ServerCardTests.swift b/Tests/MCPTests/ServerCardTests.swift index 14dfc120..334a7bae 100644 --- a/Tests/MCPTests/ServerCardTests.swift +++ b/Tests/MCPTests/ServerCardTests.swift @@ -549,11 +549,11 @@ struct ServerCardValidatorTests { override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } - /// swift-corelibs-foundation traps on a callback after `stopLoading()`. + /// Ends the client calls made after `startLoading()` returns, at + /// `stopLoading()`: see ``URLProtocolStop``. + private let stop = URLProtocolStop() private let stateLock = NSLock() - private var stopped = false private var log: Log? - private var isStopped: Bool { stateLock.withLock { stopped } } override func startLoading() { let key = request.value(forHTTPHeaderField: Self.keyHeader) ?? "" @@ -586,17 +586,17 @@ struct ServerCardValidatorTests { case .stream(let chunk, let count, let contentLength, let pauseAfter): respond(url, status: 200, headers: contentLength.map { ["Content-Length": String($0)] } ?? [:]) let loader = SendableURLProtocol(self) - DispatchQueue.global().async { + // A thread of its own: the stream blocks while it waits, which on + // a Dispatch thread would hold one of Swift's pool on Linux. + Thread.detachNewThread { loader.value.stream(chunk: chunk, count: count, pauseAfter: pauseAfter) } } } private func finish(with response: HTTPURLResponse) { - guard !isStopped else { return } - client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) - guard !isStopped else { return } - client?.urlProtocolDidFinishLoading(self) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } + stop.ifLoading(self) { [self] in client?.urlProtocolDidFinishLoading(self) } } /// Sends `count` chunks. Once more than `pauseAfter` bytes went out, it @@ -605,21 +605,24 @@ struct ServerCardValidatorTests { var sent = 0 var paused = false for _ in 0.. pauseAfter, !paused { paused = true let deadline = Date().addingTimeInterval(30) - while !isStopped && Date() < deadline { Thread.sleep(forTimeInterval: 0.005) } - guard !isStopped else { return } + while !stop.isStopped && Date() < deadline { Thread.sleep(forTimeInterval: 0.005) } + guard !stop.isStopped else { return } + } + stop.ifLoading(self) { [self] in + client?.urlProtocol(self, didLoad: Data(repeating: 0x20, count: chunk)) + stateLock.withLock { log }?.delivered(chunk) } - client?.urlProtocol(self, didLoad: Data(repeating: 0x20, count: chunk)) - stateLock.withLock { log }?.delivered(chunk) sent += chunk Thread.sleep(forTimeInterval: 0.002) } - guard !isStopped else { return } - stateLock.withLock { log }?.stop() - client?.urlProtocolDidFinishLoading(self) + stop.ifLoading(self) { [self] in + stateLock.withLock { log }?.stop() + client?.urlProtocolDidFinishLoading(self) + } } private func respond(_ url: URL, status: Int, headers: [String: String]) { @@ -628,11 +631,8 @@ struct ServerCardValidatorTests { } override func stopLoading() { - let log = stateLock.withLock { () -> Log? in - stopped = true - return self.log - } - log?.stop() + stop.stop() + stateLock.withLock { log }?.stop() } } diff --git a/Tests/MCPTests/StatelessGatingTests.swift b/Tests/MCPTests/StatelessGatingTests.swift index dcd91082..bcf49130 100644 --- a/Tests/MCPTests/StatelessGatingTests.swift +++ b/Tests/MCPTests/StatelessGatingTests.swift @@ -329,10 +329,10 @@ private func json(_ response: HTTPResponse) throws -> Value { private let initialize = #"{"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"c","version":"1"}}}"# -/// The next message the transport hands to the server; fails after two seconds. +/// The next message the transport hands to the server; fails after 30 seconds. private func nextIncoming(_ iterator: inout AsyncThrowingStream.Iterator) async throws -> Value { let timeout = Task { - try await Task.sleep(for: .seconds(2)) + try await Task.sleep(for: .seconds(30)) Issue.record("No message reached the server") } defer { timeout.cancel() } diff --git a/Tests/MCPTests/SubscriptionTests.swift b/Tests/MCPTests/SubscriptionTests.swift index d139cc43..6842a72d 100644 --- a/Tests/MCPTests/SubscriptionTests.swift +++ b/Tests/MCPTests/SubscriptionTests.swift @@ -89,7 +89,7 @@ private func resourceSubscriptions(of listen: [String: Value]) -> Value? { listen["params"]?.objectValue?["notifications"]?.objectValue?["resourceSubscriptions"] } -@Suite("Subscription Tests", .timeLimit(.minutes(1))) +@Suite("Subscription Tests", .timeLimit(.minutes(2))) struct SubscriptionTests { @Test("listen is acknowledged with the subset the server supports") func testAcknowledgement() async throws { diff --git a/Tests/MCPTests/TaskTests.swift b/Tests/MCPTests/TaskTests.swift index e48daa76..9ac0eb19 100644 --- a/Tests/MCPTests/TaskTests.swift +++ b/Tests/MCPTests/TaskTests.swift @@ -1881,7 +1881,7 @@ struct LateTaskAnswerTests { @Test( "A tools/call cancelled while its task answer is on the way: the task is cancelled", - .timeLimit(.minutes(1)), arguments: LatePeer.revisions) + .timeLimit(.minutes(2)), arguments: LatePeer.revisions) func cancelRacesAnswer(revision: String) async throws { let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() try await serverTransport.connect() diff --git a/Tests/MCPTests/ToolNameTests.swift b/Tests/MCPTests/ToolNameTests.swift index a0eeae49..aa6d8a30 100644 --- a/Tests/MCPTests/ToolNameTests.swift +++ b/Tests/MCPTests/ToolNameTests.swift @@ -92,7 +92,7 @@ struct ToolNameTests { } } -@Suite("Tool names on the wire (SEP-986)", .timeLimit(.minutes(1))) +@Suite("Tool names on the wire (SEP-986)", .timeLimit(.minutes(2))) struct ToolNameWarningTests { private let listed = ["getUser", "get user", "get user", "dup", "dup", "x/y"] diff --git a/Tests/MCPTests/URLProtocolStopTests.swift b/Tests/MCPTests/URLProtocolStopTests.swift new file mode 100644 index 00000000..460ed83f --- /dev/null +++ b/Tests/MCPTests/URLProtocolStopTests.swift @@ -0,0 +1,104 @@ +import Foundation +import Testing + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +@Suite("URLProtocolStop") +struct URLProtocolStopTests { + /// Every event, in order. + private final class Events: @unchecked Sendable { + private let lock = NSLock() + private var names: [String] = [] + func append(_ name: String) { lock.withLock { names.append(name) } } + var all: [String] { lock.withLock { names } } + } + + @Test("stop() returns only after a client call in progress, and no call runs after it") + func stopWaitsForCallInProgress() async { + let stop = URLProtocolStop() + let events = Events() + let (calling, callingContinuation) = AsyncStream.makeStream() + let stopping = DispatchSemaphore(value: 0) + Thread.detachNewThread { + stop.ifLoading { + callingContinuation.yield() + stopping.wait() + // The call holds on once the other thread is about to call + // stop(), so stop() reaches the lock while the call has it. + Thread.sleep(forTimeInterval: 0.2) + events.append(stop.isStopped ? "call after stop" : "call") + } + } + for await _ in calling { break } + await withCheckedContinuation { continuation in + Thread.detachNewThread { + stopping.signal() + stop.stop() + events.append("stopped") + stop.ifLoading { events.append("late call") } + continuation.resume() + } + } + #expect(events.all == ["call", "stopped"]) + #expect(stop.isStopped) + } + + @Test("stop() from inside a client call does not wait for it") + func stopInsideCall() { + let stop = URLProtocolStop() + let start = ContinuousClock.now + stop.ifLoading { stop.stop() } + #expect(ContinuousClock.now - start < .milliseconds(500)) + #expect(stop.isStopped) + } + + #if canImport(FoundationNetworking) + /// Answers every request from a thread of its own, through + /// ``URLProtocolStop/ifLoading(_:_:)``. + final class ThreadedAnswerProtocol: URLProtocol { + private let stop = URLProtocolStop() + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + let loader = SendableURLProtocol(self) + Thread.detachNewThread { loader.value.answer() } + } + + private func answer() { + let response = HTTPURLResponse( + url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [:])! + stop.ifLoading(self) { [self] in + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + } + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didLoad: Data("ok".utf8)) } + stop.ifLoading(self) { [self] in client?.urlProtocolDidFinishLoading(self) } + } + + override func stopLoading() { stop.stop() } + } + + // corelibs reads the session's task registry in each client call and + // changes it on the session's work queue: a call from another thread, + // while the session adds and removes other tasks, crashed the process. + @Test("Client calls made from other threads, for many tasks of one session, do not crash") + func manyTasksOfOneSession() async throws { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [ThreadedAnswerProtocol.self] + let session = URLSession(configuration: configuration) + defer { session.finishTasksAndInvalidate() } + let url = URL(string: "http://127.0.0.1:9/answer")! + for _ in 0..<20 { + try await withThrowingTaskGroup(of: Data.self) { group in + for _ in 0..<50 { + group.addTask { try await session.data(from: url).0 } + } + for try await data in group { #expect(data == Data("ok".utf8)) } + } + } + } + #endif +} diff --git a/design/linux.md b/design/linux.md index 5bcba543..d199939f 100644 --- a/design/linux.md +++ b/design/linux.md @@ -26,12 +26,14 @@ arrives (`ResponseBody`) and parses `text/event-stream` with its own `ServerSent - Apple platforms: `URLSession.bytes(for:)`. - swift-corelibs-foundation has no `bytes(for:)` and no per-task delegates. The transport keeps - a second session with the same configuration and a `StreamingSessionDelegate`, which hands - each data task's response to the caller waiting for it and its chunks to that task's body. - A second response for one task fails it rather than join the two bodies. The body is an - `AsyncThrowingStream`, whose iterator returns `nil` when the reading task is cancelled; the - body throws `CancellationError` then, where `AsyncBytes` throws an error of its own, so a cut - JSON body is not delivered as a message. + a second session (`StreamingSession`) with the same configuration, less its `urlCache`, and a + `StreamingSessionDelegate`, which hands each data task's response to the caller waiting for it + and its chunks to that task's body. A second response for one task fails it rather than join + the two bodies. The body is an `AsyncThrowingStream`, whose iterator returns `nil` when the + reading task is cancelled; the body throws `CancellationError` then, where `AsyncBytes` throws + an error of its own, so a cut JSON body is not delivered as a message. `ServerCard.fetch` + streams through the same session, so on Linux it does not read + `session.configuration.urlCache`. A session traps (corelibs) or raises (Apple platforms) when a task is created after it was invalidated. `disconnect()` invalidates both sessions through `StreamingSession.Lifetime`: a task @@ -64,16 +66,31 @@ Checked on ubi9 and noble: (`URLRequest.addingAdditionalHeaders(of:)`, for the transport's requests and the OAuth requests), so a `URLProtocol` sees the same headers as on Apple platforms. - A `URLProtocol` that calls its client after the task was cancelled traps - (`TaskRegistry.swift: Trying to access a behaviour for a task that in not in the registry`). - The test mocks (`MockURLProtocol`, `IsolatedMockURLProtocol`) check `stopLoading()` before - each callback and do not hold a lock during one: corelibs can call `stopLoading()` from its - work queue while a callback waits for that queue. + (`TaskRegistry.swift: Trying to access a behaviour for a task that in not in the registry`), + and so can one that calls it from a thread other than the task's work queue: every client + method reads the session's task registry, which the work queue changes without a lock. The + test mocks make each call through `URLProtocolStop.ifLoading(_:_:)`, which runs it on the + task's work queue (found with `Mirror`, as it is internal), where corelibs makes its own + protocols' calls and runs `stopLoading()`, unless `stop()` has been called. A recursive lock + is held across the check and the call, and `stop()`, called from `stopLoading()`, waits for it + at most a second. +- With a `URLCache`, corelibs looks each request up in it before the request starts, and a task + cancelled during that lookup can be failed after it has left the session's registry, with the + same trap. The sessions the SDK makes on Linux (`StreamingSession`, and the OAuth sessions of + `URLSession.oauthData(for:redirects:validator:)` and `OAuthAuthorizationCodeFlow.perform`) + copy the caller's configuration without its `urlCache`. +- Cancelling a task that has just finished completes it a second time: `data(for:)` then resumes + its continuation twice and traps. A session whose request has returned is invalidated with + `finishTasksAndInvalidate()`, not `invalidateAndCancel()`. ## Differences by design - `NetworkTransport` uses Network.framework and exists on Apple platforms only. - `StdioTransport` takes `FileDescriptor` from `System` on Apple platforms and from `SystemPackage` elsewhere. +- On Linux, `ServerCard.fetch(from:session:)` and the OAuth requests are never answered from the + session's `URLCache` (see above). `fetch(from:ifNoneMatch:session:)` revalidates a card the + caller kept, on both platforms. ## Reproduce diff --git a/scripts/ci/deps-linux.sh b/scripts/ci/deps-linux.sh index 27fb8801..b9fbe8a4 100755 --- a/scripts/ci/deps-linux.sh +++ b/scripts/ci/deps-linux.sh @@ -9,9 +9,10 @@ # Tools already on PATH at a usable version are left alone. Supports dnf # (swift:*-rhel-ubi9 and other RHEL-based images) and apt # (swift:*-noble and other Debian/Ubuntu images). On dnf everything comes -# from the image's package mirrors; on apt Node, Go and uv come from their -# upstream download sites (the Node and Go tarballs checked against their -# published SHA-256). Runs as root, or through sudo. +# from the image's package mirrors, except Node when they have no Node 22; on +# apt Node, Go and uv come from their upstream download sites (the Node and Go +# tarballs checked against their published SHA-256). Runs as root, or through +# sudo. set -euo pipefail TOOLS=("$@") @@ -38,12 +39,26 @@ else fi APT_UPDATED=0 +# The Ubuntu mirrors drop connections at times. `apt-get update` then only +# warns and keeps no package lists, and the install finds no package: both are +# tried again, after 15, 30, 45 and 60 seconds. apt_install() { - if [[ $APT_UPDATED -eq 0 ]]; then - $SUDO apt-get update -q - APT_UPDATED=1 - fi - DEBIAN_FRONTEND=noninteractive $SUDO apt-get install -yq --no-install-recommends "$@" + local attempt + for attempt in 1 2 3 4 5; do + if [[ $APT_UPDATED -eq 0 ]]; then + $SUDO apt-get update -q || true + APT_UPDATED=1 + fi + if DEBIAN_FRONTEND=noninteractive $SUDO apt-get install -yq --no-install-recommends "$@"; then + return + fi + [[ $attempt -eq 5 ]] && break + info "apt-get install $* failed; retrying in $((attempt * 15))s" + sleep $((attempt * 15)) + APT_UPDATED=0 + done + echo "deps-linux.sh: apt-get install $* failed after 5 attempts" >&2 + exit 1 } # The major version of `node`, or 0. @@ -73,18 +88,34 @@ install_node() { if [[ "$(node_major)" -ge 22 ]]; then return; fi info "installing Node 22" if [[ $PM == dnf ]]; then - # DEPS_NODE_DNF_PACKAGE names a Node 22 package from the image's own - # repositories, tried first. - if [[ -z "${DEPS_NODE_DNF_PACKAGE:-}" ]] || ! $SUDO dnf install -yq "$DEPS_NODE_DNF_PACKAGE"; then - $SUDO dnf module enable -yq nodejs:22 - $SUDO dnf install -yq nodejs npm + if ! dnf_install_node; then + # The UBI 9 mirrors have listed the nodejs:22 module for x86_64 + # without its packages, while arm64 had them. + info "dnf has no Node 22; installing it from nodejs.org" + command -v xz >/dev/null || $SUDO dnf install -yq xz + install_node_tarball fi else apt_install ca-certificates curl xz-utils - local base=https://nodejs.org/dist/latest-v22.x line - line="$(curl -fsSL "$base/SHASUMS256.txt" | awk -v a="linux-$NODE_ARCH.tar.xz" '$2 ~ a"$" { print $1, $2; exit }')" - install_tarball "$base/${line#* }" "${line%% *}" -xJ --strip-components=1 + install_node_tarball + fi + [[ "$(node_major)" -ge 22 ]] || { echo "deps-linux.sh: Node 22 or later is required" >&2; exit 1; } +} + +# Node 22 from the image's repositories. DEPS_NODE_DNF_PACKAGE names a Node 22 +# package of its own repositories, tried first. +dnf_install_node() { + if [[ -n "${DEPS_NODE_DNF_PACKAGE:-}" ]] && $SUDO dnf install -yq "$DEPS_NODE_DNF_PACKAGE"; then + return fi + $SUDO dnf module enable -yq nodejs:22 && $SUDO dnf install -yq nodejs npm +} + +# The newest Node 22 from nodejs.org, checked against its published SHA-256. +install_node_tarball() { + local base=https://nodejs.org/dist/latest-v22.x line + line="$(curl -fsSL "$base/SHASUMS256.txt" | awk -v a="linux-$NODE_ARCH.tar.xz" '$2 ~ a"$" { print $1, $2; exit }')" + install_tarball "$base/${line#* }" "${line%% *}" -xJ --strip-components=1 } install_go() {