Skip to content

fix: CI failures on rel/1.0.0: a stateless test wait, an OAuth double resume on Linux, apt retries - #410

Merged
jeanmatthieu merged 3 commits into
rel/1.0.0from
fix/additional-ci-failures
Dec 1, 2026
Merged

jeanmatthieu merged 3 commits into
rel/1.0.0from
fix/additional-ci-failures

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Motivation and Context

The CI runs of #372 (7e2dabc2, which includes #408) still fail. This fixes nine causes in three commits: fix for the two library crashes (2 and 8), test for the test fixes (1, 4–7 and 9), and ci for the CI change (3). The fourth showed up in this PR's own first CI run. The last four are the Linux flakes the first version of this PR listed as not addressed: the TaskRegistry trap and the HTTPClientTransportTests.swift:2759/:2888 time-outs.

1. A 2-second wait in the stateless exchange tests (test)

Two tests in StatelessTransportExchangeTests failed on RHEL UBI 9 (push run) and Ubuntu 24.04 (PR run):

✘ Test "Cancelling a pending JSON reply cancels the request in the server" recorded an issue at StatelessGatingTests.swift:336:21
✘ Test "notifications/cancelled matches the id by value, not by its text" recorded an issue at StatelessGatingTests.swift:336:21

nextIncoming() records "No message reached the server" after 2 seconds. Both tests recorded it in the same millisecond, while unrelated tests around them took up to 8.7 seconds. Both then finished with no other issue, so the message did arrive, just after the limit. The limit is now 30 seconds, like waitUntil, resultInTime and exchange in the same file.

2. SWIFT TASK CONTINUATION MISUSE in OAuthAuthorizationCodeFlow on Linux (library)

An Ubuntu 24.04 test run (0d80a17d, before #408) crashed with:

Fatal error: SWIFT TASK CONTINUATION MISUSE: data(for:delegate:) tried to resume its continuation more than once,
throwing Error Domain=NSURLErrorDomain Code=-999 ... https://localhost:8080/oauth/authorize?response_type=code...

This is a different problem from the leaked continuation #408 fixed. Without a delegate, perform sends the authorization request on its own session and then cancels that session:

 perform(authorizationURL:redirectURI:state:issuer:delegate: nil, session:)
   noRedirectSession = URLSession(configuration:, delegate: OAuthNoRedirectSessionDelegate())
-  defer { noRedirectSession.invalidateAndCancel() }
+  defer { noRedirectSession.finishTasksAndInvalidate() }
   (_, response) = try await noRedirectSession.data(for: request)

In swift-corelibs-foundation (release/6.1, _ProtocolClient.urlProtocolDidFinishLoading), the success path calls the completion handler, which resumes the data(for:) continuation, and only then sets the task to .completed. The resumed caller can run the defer in that gap. cancel() still sees .running, and its failure path completes the task a second time with -999, which traps. Any Linux app that signs in without an OAuthAuthorizationDelegate can hit this.

When the defer runs, the request has always ended, so there is nothing to cancel. finishTasksAndInvalidate() is what the guarded session in URLSession.oauthData(for:redirects:validator:) already uses. Cancelling the caller still cancels the request, through data(for:)'s own cancellation handler.

3. apt mirror outages, and one Linux flake cancelling three platforms (CI)

  • The Conformance (ubuntu-latest, swift:6.1-noble) job failed in most runs even though every conformance leg passed. Its first leg, conformance-scripts, installs Node with apt while archive.ubuntu.com and security.ubuntu.com were refusing connections. apt-get update only warned, and the install then failed with Unable to locate package curl. apt_install in scripts/ci/deps-linux.sh now retries the update and the install up to four times (after 15, 30, 45 and 60 s) before failing.
  • The test matrix now sets fail-fast: false, as the other matrices do. Before, one failing Linux leg cancelled both macOS legs and the other Linux leg.
  • On dnf, Node 22 now comes from nodejs.org, checked against its SHA-256 as on apt, when the image's repositories can't install it. The UBI 9 x86_64 AppStream mirrors listed the nodejs:22 module without its packages (Unable to find a match: nodejs npm), which failed the Conformance (RHEL UBI 9) and Interop (ubuntu-latest) jobs before they ran anything; the arm64 mirrors had them. In fresh images, the script installs the dnf package on arm64 UBI 9, falls back to nodejs.org on x86_64 UBI 9, and installs from nodejs.org on noble as before.

Not addressed: the Linux Static SDK Build job failed once inside the pinned upstream install-and-build-with-sdk.sh, after 24 minutes of apt update against the same unreachable mirrors.

4. The discovery timeout tests assume the sign-in starts within 1 second (test)

This PR's first CI run failed on RHEL UBI 9 with:

✘ Test "Cancelling connect during sign-in stops waiting promptly" recorded an issue at ClientConnectionFailureTests.swift:598:13: Expectation failed: await transport.authorizationWaiterCount == 1

The four sign-in tests in "Discovery timeout over HTTP" set discoveryTimeout to 1 second. They assume the server/discover POST reaches the authorizer before that. When it doesn't, the discovery timer finds no authorization in progress, abandons the probe, and connect moves on to initialize. The same thing failed "Signing in does not count against the discovery timeout" twice on #372 (it connected at 2025-11-25 instead of 2026-07-28), and the cancel test once on the iOS simulator.

 for timeout in [1 s, 4 s, 12 s]
   connect in a task; the sign-in lasts until release()
-  sign-in of 2 s against a 1 s timeout, and hope it started in time
+  if the first sign-in started after start + timeout: not a test of the timer, try the next timeout
+  wait until the discovery timer waits for the sign-in, then release it
   the same assertions as before
+record an issue if every timeout was missed

A sign-in that starts before start + timeout must belong to server/discover, because initialize is sent only after the timer fires.

5. offThreadPool froze the whole Linux test process for 30 seconds (test)

In about one full run in eight on 2 CPUs, some 540 tests finished within the same second, about 37 s in, and dozens failed on their time limits at once: the discovery timeout sign-in tests, TaskTests.swift:1079, the stateless client tests and others. A thread dump taken during a freeze showed eight threads:

5 × libdispatch worker   read()  ← offThreadPool ← StdioTransportTests.read / ClientReceiveLoopTerminationTests.readLine
1 × libdispatch worker   every Swift concurrency job

On Linux the Swift global executor runs on libdispatch's global queues, so DispatchQueue.global() doesn't get around the cooperative pool: a blocked read() there holds one of the pool's threads all the same.

 func offThreadPool(_ work:) async throws -> T
-  DispatchQueue.global().async { resume(work()) }
+  Thread { resume(work()) }.start()

6. The mock URL protocols called their client off corelibs' work queue (test)

Two crashes came from the mocks, not the SDK:

TaskRegistry.swift:118: Fatal error: Trying to access a behaviour for a task that in not in the registry
  ... MockURLProtocol.load() at HTTPClientTransportTests.swift:146

Program crashed: Bad pointer dereference at 0x0000000000000010
  URLSession.behaviour(for:) ← _ProtocolClient.urlProtocolDidFinishLoading ← IsolatedMockURLProtocol.load()
  • The mocks checked a "stopped" flag and then called the client. A task cancelled between the two was called after it had left its session.
  • Every corelibs URLProtocolClient method reads the session's task registry, two dictionaries without a lock, on the calling thread. Meanwhile the session's work queue adds and removes tasks. corelibs' own protocols call their client from the task's work queue; the mocks called it from a Swift task or a Dispatch thread.
 mock.load()
-  guard !stopped; client.didLoad(data)
+  stop.ifLoading(self) { client.didLoad(data) }
+    Linux: on the task's work queue (where corelibs runs stopLoading() too), unless stopped
+    Apple: in place, under a lock that stop() waits for

The work queue is internal to corelibs, so the test helper finds it with Mirror, and stops the test run if it's gone. The streaming mocks also run on their own thread now, as in 5. The failures at HTTPClientTransportTests.swift:2759 and :2888 print the outcome. The :2888 test checks that a second response fails the request, and it now waits 30 s instead of 5: its limit only stops a hang. :2759 ("fails promptly") keeps its 2 s.

7. The sign-in tests waited for connect without a limit (test)

A connect that never returned held the suite until CI stopped it. Now each waits at most 30 s, then records the attempt's state (sign-ins started and ended, requests waiting for authorization, methods authorized) and cancels. The stalls this showed were the freeze in 5; none remain.

8. TaskRegistry trap from the SDK's own cancel on Linux (library)

With 5 and 6 fixed, this remained, with no mock on the stack:

TaskRegistry.swift:118: Fatal error: Trying to access a behaviour for a task that in not in the registry
  URLSession.behaviour(for:)
  _ProtocolClient.urlProtocol(task:didFailWithError:)
  closure #1 in closure #2 in closure #1 in URLSessionTask.cancel()

StreamingSession, which streams HTTPClientTransport's responses and ServerCard.fetch's on swift-corelibs-foundation, used the configuration as given, and .ephemeral has an in-memory URLCache. With a cache, corelibs first looks each request up in it, and a task cancelled during that lookup can be failed after the session has removed it.

 StreamingSession.init(configuration:redirects:)   // Linux only
-  session = URLSession(configuration:, delegate:, delegateQueue: nil)
+  session = URLSession(configuration: configuration.withoutURLCache(), delegate:, delegateQueue: nil)
 URLSession.oauthData(for:redirects:validator:)    // Linux only
-  guarded = URLSession(configuration: configuration, delegate: OAuthRedirectGuard(...))
+  guarded = URLSession(configuration: configuration.withoutURLCache(), delegate: OAuthRedirectGuard(...))
 OAuthAuthorizationCodeFlow.perform                // the no-redirect session, on Linux
-  URLSession(configuration: session.configuration, delegate: OAuthNoRedirectSessionDelegate())
+  URLSession(configuration: session.configuration.withoutURLCache(), delegate: ...)

MCP requests are never answered from a cache. A server card revalidates with its ETag through fetch(from:ifNoneMatch:session:), so on Linux ServerCard.fetch no longer reads the session's cache. Apple platforms don't use this session. The two short-lived OAuth sessions are built the same way, and data(for:) cancels their task when the caller is cancelled, so they had the same exposure (pointed out in review). OAuth responses are not meant to come from a cache either. There's a CHANGELOG entry, and design/linux.md describes both.

9. testRoundtrip raced each step against a sleep, and every time limit was 1 minute (test)

This PR's CI run on e4e35142 failed on the iOS simulator:

✘ Test testRoundtrip() recorded an issue at RoundtripTests.swift:15:6: Caught error: CancellationError()

The error was the test's own. Each step raced its requests against a Task.sleep(for: .seconds(10)) and threw when the sleep won. The simulator was slow to start in that run, and a trivial test took 26.7 s. On the rerun it took 17.0 s, and testRoundtrip passed after 20.7 s.

-let task = Task { try await client.listTools() ... }
-group: { sleep 10 s; task.cancel(); throw CancellationError() } vs { try await task.value }
+async let tools = client.listTools()
+async let call = client.callTool(name: "add", ...)
+#expect(try await tools ...); #expect(try await call ...)

The steps now await the client directly, and the test's .timeLimit is the only limit. Every .timeLimit in the suite (59 tests) is now 2 minutes instead of 1. These limits only stop a hang, and a simulator stall alone has taken 27 s of the minute.

How Has This Been Tested?

Every CI job, run locally on f69fc9a6

All 17 jobs in scripts/ci/jobs pass on each host: scripts/ci/run-jobs.sh on macOS, and scripts/ci-linux.sh all in each Linux image. The Apple simulator and Catalyst runs use scripts/ci/apple-platform.sh. The whole set was run again after the review changes.

Platform Toolchain Unit tests Conformance Interop
macOS 27, arm64 Xcode, Swift 6.4 1537 pass pass matches
iOS Simulator Xcode, Swift 6.4 1537 pass
tvOS Simulator Xcode, Swift 6.4 1498 pass
visionOS Simulator Xcode, Swift 6.4 1537 pass
Mac Catalyst Xcode, Swift 6.4 1537 pass
RHEL UBI 9, arm64 Swift 6.1 1577 pass pass matches
Ubuntu 24.04, arm64 Swift 6.1 1577 pass pass matches
  • Unit tests. The known issues are the existing withKnownIssue in "A result with a null id gets -32600" in RequestLifecycleTests: 2 on Apple platforms and 3 on Linux. The HelloClient example runs against HelloServer on macOS and on both Linux images. The two Linux-only OAuth cache tests added in review account for 1575 → 1577.
  • Other jobs. The docs job passes everywhere: DocC with --warnings-as-errors, doc coverage, and weave.swift --check. fuzz ran its 5 targets for 60 s each on both Linux images without a crash; it skips on macOS, which has no libFuzzer. api-breakage passes, but there is no 1.x release tag yet to compare against.
  • Linux jobs left to CI. The Linux Static SDK and x86_64 Linux jobs ran only in this PR's CI, where all 14 checks pass on f69fc9a6.
  • Node 22. On RHEL arm64 it came from dnf, and on noble from nodejs.org. macOS used the installed Node 26.

Conformance. The results are identical on all three hosts, with 0 failures and 0 warnings:

Run Client checks Server checks
--spec-version 2025-11-25 248 84
--spec-version 2026-07-28 408 152
Default, extension scenarios included 493 276
Tier --requirements 2025-11-25 303 (18/18 scored scenarios, 100%) 84 (30/30, 100%)
Tier --requirements 2026-07-28 461 (32/32, 100%) 196 (37/37, 100%)

The unscored scenarios (3 and 7 at 2025-11-25, 13 and 7 at 2026-07-28) all pass too. conformance-scripts (the harness's own tests) passes.

Interop. scripts/run-interop.sh --check runs Swift against the Go, Python and TypeScript SDKs:

  • 149 client and server pairs across the six profiles: basic, advanced, connect, session, tasks and apps.
  • Both transports (stdio and HTTP) and both protocol eras (handshake and stateless).
  • 4 example clients.

On each host every pair matches the committed interop/RESULTS.md, with the same pass, fail and skip counts. The failures that file records are all on Go or TypeScript servers; none is on a Swift server.

The fixes

  • Full test runs in a 2-CPU RHEL UBI 9 container (scripts/ci-linux.sh --cpus 2), counting crashes and frozen runs:

    Tree Runs Pass TaskRegistry traps 30 s freezes
    Without 5 or 6's work queue, with or without 8 27 23 0 4
    With 5, without 8 or 6's work queue 60 49 11 0
    With 5 and 8, without 6's work queue 90 89 0 0 (the failure: a mock segfault, fixed by 6)
    All eight 60 60 0 0
  • Regression tests, before and after:

    • OffThreadPoolTests blocks 24 work items until all have started. With the Dispatch queue, only 23 started within 10 s on Linux; now all do.
    • The URLProtocolStopTests stress test sends 1000 requests, 50 at a time, on one session, to a protocol that answers from its own thread. With the calls made in place, it crashed with the segfault above in 8 of 10 runs; now in none of 10.
    • The interleaving in 8 can't be forced from a test. Instead, the tests check that each session has no cache: the streaming session directly, which also checks that the caller's configuration keeps its own cache, and the two OAuth sessions through URLCacheProbe, a URLProtocol that reads the session of its task. All three fail without the change.
  • Crash in 2, before and after. A throwaway stress test, not committed, runs 40,000 delegate-less perform calls against a URLProtocol that answers 302 from a Task, with 12 busy threads on 8 CPUs, on Swift 6.1 / Ubuntu 24.04 (arm64):

    • Before: crashed in 2 of 2 runs, with the CI message above.
    • After: no crash in 6 of 6 runs.
    • With 0 to 8 busy threads, the old code did not crash in 28 runs, so no suite-sized regression test is added. The existing OAuth tests run this path, which is how CI found the crash.
  • The stateless exchange suites pass on macOS. Their failure needs an overloaded runner, so the evidence for fix 1 is the CI logs.

  • apt_install was run with a stub apt-get: it succeeded when the stub succeeded on attempt 3, and failed with exit 1 after 5 attempts when the stub always failed. Building the noble CI image with the new script installs Node, Go, uv and ps as before.

  • Discovery timeout tests (4), before and after, in the same 2-CPU container:

    • Before: "Cancelling connect during sign-in" failed in 2 of 4 runs, each time with one sign-in started and no authorized request.
    • After: none of the four failed in 12 runs. All four reported a pass in 8 of them; in the other 4 the output was cut short by the freeze in 5 or a crash fixed by 6 or 8.
    • With the discovery timer changed to give up instead of waiting for a sign-in, all four fail, so the retry does not hide a regression.
    • On macOS they take 1 to 2 seconds, as before.

Breaking Changes

None. No public API changes.

  • OAuthAuthorizationCodeFlow only changes how it releases its private session.
  • On Linux, the streaming session of HTTPClientTransport and ServerCard.fetch ignores the configuration's URLCache. So a server card fetched on Linux is no longer answered from that cache; ETag revalidation is unchanged.
  • On Linux, the OAuth requests (discovery, registration, token, and the delegate-less authorization request) also run without the configuration's URLCache. The new URLSessionConfiguration.withoutURLCache() is internal.

Types of changes

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

AI Assistance

Drafted with an AI coding agent (Claude) at the author's request, for human review before merge.

jeanmatthieu added a commit that referenced this pull request Nov 30, 2026
…he deadline

The four sign-in tests in "Discovery timeout over HTTP" set
discoveryTimeout to 1 second and assumed that the server/discover POST
reaches the authorizer before the timeout runs out. On a loaded runner
it can take longer: the discovery timer then finds no authorization in
progress, abandons the probe and connect moves on to initialize. Each
test fails its own way:

- "Cancelling connect during sign-in stops waiting promptly": the timer
  never waits, so authorizationWaiterCount stays 0 (#410, RHEL UBI 9;
  earlier on the iOS simulator)
- "Signing in does not count against the discovery timeout": connects
  at 2025-11-25 instead of 2026-07-28 (twice on #372, RHEL and Ubuntu)
- the other two: initialize is challenged as well

In a 2-CPU RHEL UBI 9 container (scripts/ci-linux.sh --cpus 2) the
first one failed in 2 of 4 full test runs, each time with one sign-in
and no authorized request.

The sign-in now lasts until release(), which the tests call once the
discovery timer waits for it, so it outlasts the deadline whatever the
runner's speed. A sign-in that starts before start + timeout belongs to
server/discover, because initialize is sent only after the timer fires;
an attempt where it started later does not test the timer and is run
again with a longer timeout (1, 4, then 12 seconds), and the test
records an issue when even the longest one is missed. The assertions
are unchanged.

In the same container the four tests passed in 12 of 12 full runs.
With the discovery timer changed to give up instead of waiting for a
sign-in, all four fail. On an idle machine they finish in 1 to 2
seconds, as before.

Assisted-by: Claude
@jeanmatthieu
jeanmatthieu force-pushed the fix/additional-ci-failures branch from 12bee6e to 260220a Compare November 30, 2026 19:19
jeanmatthieu added a commit that referenced this pull request Nov 30, 2026
…ulator

Most failures in the CI runs of #372 and #410 came from the tests, not
from the SDK. Each cause:

- offThreadPool ran blocking work, such as a read() on a pipe, on
  DispatchQueue.global(). On Linux the Swift global executor runs on
  libdispatch's global queues, so those reads held the cooperative
  pool's threads: in about one full run in eight on two CPUs the whole
  process froze for about 30 seconds (a thread dump showed five workers
  blocked in read() and one running every async job), and dozens of
  tests failed on their time limits at once, among them the
  HTTPClientTransportTests.swift:2759 and :2888 failures. It now runs
  each work item on a Thread of its own, as do the two streaming mocks
  that block while they wait. OffThreadPoolTests blocks 24 work items
  until all have started: with the Dispatch queue only 23 started within
  10 seconds on Linux.

- The mock URL protocols checked a "stopped" flag and then called their
  client, so a task cancelled in between was called after it had left
  its session ("Trying to access a behaviour for a task that in not in
  the registry", MockURLProtocol.load()). They also called it from a
  Swift task or a Dispatch thread, while every corelibs URLProtocolClient
  method reads the session's task registry, two dictionaries without a
  lock, as the session's work queue changes it ("Bad pointer dereference
  at 0x10" in URLSession.behaviour(for:)). URLProtocolStop now holds a
  lock across the check and the call, and on Linux makes each call on
  the task's work queue, where corelibs makes its own protocols' calls
  and runs stopLoading(); the queue is internal, so the helper finds it
  with Mirror. A stress test that sends 1000 requests, 50 at a time, on
  one session crashed in 8 of 10 runs with the calls made in place, and
  in none of 10 on the work queue.

- The four sign-in tests of "Discovery timeout over HTTP" assumed the
  server/discover POST reaches the authorizer within the 1-second
  discovery timeout. On a loaded runner it can come later, the timer
  abandons the probe, and connect moves on to initialize. The sign-in
  now lasts until release(); an attempt whose sign-in started after the
  deadline does not test the timer and is run again with a longer
  timeout (1, 4, then 12 seconds). With the timer changed to give up
  instead of waiting for a sign-in, all four fail. They also wait at
  most 30 seconds for connect, then record the attempt's state and
  cancel it, instead of holding the suite.

- Limits that only stop a hang are raised: nextIncoming() in
  StatelessGatingTests from 2 to 30 seconds, and the second-response
  test at HTTPClientTransportTests.swift:2888 from 5 to 30. The 2759 and
  2888 failures now print the outcome; 2759 ("fails promptly") keeps its
  2 seconds.

- testRoundtrip() raced each step against a 10-second Task.sleep of its
  own, and failed with that sleep's CancellationError on the iOS
  simulator when a trivial test took 26.7 seconds to finish. The steps
  now await the client's calls directly, the concurrent ones with async
  let, and the test's .timeLimit is the only limit.

- Every .timeLimit in the suite (59 tests) is 2 minutes instead of 1.
  These limits only stop a hang, and a stall of the simulator alone has
  taken 27 seconds of the minute.

With these and the next commit, 60 of 60 full test runs passed in a
2-CPU RHEL UBI 9 container (scripts/ci-linux.sh --cpus 2), against 23 of
27 before, with four 30-second freezes.

Assisted-by: Claude
…let every test leg finish

The Conformance (ubuntu-latest, swift:6.1-noble) job failed in most CI
runs of #372 although every conformance leg in it passed. The first leg,
conformance-scripts, installs Node with apt, and archive.ubuntu.com and
security.ubuntu.com refused connections: `apt-get update` only warned
("Some index files failed to download"), and the install that followed
failed with "Unable to locate package curl". The next leg in the same job
installed the same packages a few minutes later.

apt_install in scripts/ci/deps-linux.sh now tries the update and the
install again up to four times, after 15, 30, 45 and 60 seconds, and
fails the job after the fifth attempt.

On dnf, Node 22 comes from nodejs.org, checked against its published
SHA-256 as on apt, when the image's repositories cannot install it. The
UBI 9 x86_64 AppStream mirrors listed the nodejs:22 module without its
packages ("Unable to find a match: nodejs npm"), which failed the
Conformance (swift:6.1-rhel-ubi9) and Interop (ubuntu-latest) jobs
before they ran anything; the arm64 mirrors had them. Run in fresh
images, the script installs the dnf package on arm64 UBI 9, falls back
to nodejs.org on x86_64 UBI 9, and installs from nodejs.org on noble as
before.

The test matrix in ci.yml also sets fail-fast: false, as the other
matrices do. Without it, one Linux leg that failed cancelled the two
macOS legs and the other Linux leg, so a single flake hid the results of
three platforms.

Assisted-by: Claude
@jeanmatthieu
jeanmatthieu force-pushed the fix/additional-ci-failures branch from 260220a to 869ea37 Compare November 30, 2026 20:36
jeanmatthieu added a commit that referenced this pull request Nov 30, 2026
…ulator

Most failures in the CI runs of #372 and #410 came from the tests, not
from the SDK. Each cause:

- offThreadPool ran blocking work, such as a read() on a pipe, on
  DispatchQueue.global(). On Linux the Swift global executor runs on
  libdispatch's global queues, so those reads held the cooperative
  pool's threads: in about one full run in eight on two CPUs the whole
  process froze for about 30 seconds (a thread dump showed five workers
  blocked in read() and one running every async job), and dozens of
  tests failed on their time limits at once, among them the
  HTTPClientTransportTests.swift:2759 and :2888 failures. It now runs
  each work item on a Thread of its own, as do the two streaming mocks
  that block while they wait. OffThreadPoolTests blocks 24 work items
  until all have started: with the Dispatch queue only 23 started within
  10 seconds on Linux.

- The mock URL protocols checked a "stopped" flag and then called their
  client, so a task cancelled in between was called after it had left
  its session ("Trying to access a behaviour for a task that in not in
  the registry", MockURLProtocol.load()). They also called it from a
  Swift task or a Dispatch thread, while every corelibs URLProtocolClient
  method reads the session's task registry, two dictionaries without a
  lock, as the session's work queue changes it ("Bad pointer dereference
  at 0x10" in URLSession.behaviour(for:)). URLProtocolStop now holds a
  lock across the check and the call, and on Linux makes each call on
  the task's work queue, where corelibs makes its own protocols' calls
  and runs stopLoading(); the queue is internal, so the helper finds it
  with Mirror. A stress test that sends 1000 requests, 50 at a time, on
  one session crashed in 8 of 10 runs with the calls made in place, and
  in none of 10 on the work queue.

- The four sign-in tests of "Discovery timeout over HTTP" assumed the
  server/discover POST reaches the authorizer within the 1-second
  discovery timeout. On a loaded runner it can come later, the timer
  abandons the probe, and connect moves on to initialize. The sign-in
  now lasts until release(); an attempt whose sign-in started after the
  deadline does not test the timer and is run again with a longer
  timeout (1, 4, then 12 seconds). With the timer changed to give up
  instead of waiting for a sign-in, all four fail. They also wait at
  most 30 seconds for connect, then record the attempt's state and
  cancel it, instead of holding the suite.

- Limits that only stop a hang are raised: nextIncoming() in
  StatelessGatingTests from 2 to 30 seconds, and the second-response
  test at HTTPClientTransportTests.swift:2888 from 5 to 30. The 2759 and
  2888 failures now print the outcome; 2759 ("fails promptly") keeps its
  2 seconds.

- testRoundtrip() raced each step against a 10-second Task.sleep of its
  own, and failed with that sleep's CancellationError on the iOS
  simulator when a trivial test took 26.7 seconds to finish. The steps
  now await the client's calls directly, the concurrent ones with async
  let, and the test's .timeLimit is the only limit.

- Every .timeLimit in the suite (59 tests) is 2 minutes instead of 1.
  These limits only stop a hang, and a stall of the simulator alone has
  taken 27 seconds of the minute.

With these and the next commit, 60 of 60 full test runs passed in a
2-CPU RHEL UBI 9 container (scripts/ci-linux.sh --cpus 2), against 23 of
27 before, with four 30-second freezes.

Assisted-by: Claude
@jeanmatthieu
jeanmatthieu marked this pull request as ready for review November 30, 2026 21:46
@jeanmatthieu
jeanmatthieu requested a review from a team as a code owner November 30, 2026 21:46
@varun06

varun06 commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Review of the diff (AI-assisted, reviewed by @varunkumar before posting). I did not build or run the tests.

No blocking issues. There are no public API, wire-format or ProtocolProfile changes, and the new tests use Swift Testing.

Should-fix

  1. OAuthRedirectGuard.swift:81 and OAuthAuthorizationCodeFlow.swift:163: the Linux OAuth sessions still inherit urlCache.
    StreamingSession now clears urlCache because cancelling a task during corelibs' initial URLCache lookup can trap in TaskRegistry. The short-lived sessions that oauthData(for:redirects:validator:) and OAuthAuthorizationCodeFlow.perform create from configuration call data(for:), which cancels the underlying task when the Swift task is cancelled. They look exposed to the same trap, and OAuth endpoints shouldn't be served from URLCache anyway. Consider copying the configuration and setting urlCache = nil under #if canImport(FoundationNetworking).

  2. design/linux.md is stale.

    • Around lines 28-35 and 72-77, it doesn't mention that StreamingSession has no urlCache on Linux, so ServerCard.fetch(from:session:) doesn't read session.configuration.urlCache there.
    • Lines 66-70 still describe the old pattern where the mocks check stopLoading() before each callback and hold no lock. URLProtocolStop replaces that with dispatch onto the task's workQueue and a recursive lock across the check and the callback.

Nits

  • URLProtocolStop.ifLoading (Tests/MCPTests/Helpers/URLProtocolStop.swift:45-54): add an early guard !isStopped else { return } so the Mirror reflection and queue dispatch are skipped once stopped. The check inside workQueue.async stays authoritative.
  • URLProtocolStopTests.stopWaitsForCallInProgress (Tests/MCPTests/URLProtocolStopTests.swift:20-27): the fixed 0.2s sleep can expire before stop() runs on a loaded runner. The test would then pass without checking that stop() waits for the in-progress call. Have the stopping thread signal just before stop(), and have the calling thread wait on that signal.

varun06
varun06 previously approved these changes Dec 1, 2026
…ulator

Most failures in the CI runs of #372 and #410 came from the tests, not
from the SDK. Each cause:

- offThreadPool ran blocking work, such as a read() on a pipe, on
  DispatchQueue.global(). On Linux the Swift global executor runs on
  libdispatch's global queues, so those reads held the cooperative
  pool's threads: in about one full run in eight on two CPUs the whole
  process froze for about 30 seconds (a thread dump showed five workers
  blocked in read() and one running every async job), and dozens of
  tests failed on their time limits at once, among them the
  HTTPClientTransportTests.swift:2759 and :2888 failures. It now runs
  each work item on a Thread of its own, as do the two streaming mocks
  that block while they wait. OffThreadPoolTests blocks 24 work items
  until all have started: with the Dispatch queue only 23 started within
  10 seconds on Linux.

- The mock URL protocols checked a "stopped" flag and then called their
  client, so a task cancelled in between was called after it had left
  its session ("Trying to access a behaviour for a task that in not in
  the registry", MockURLProtocol.load()). They also called it from a
  Swift task or a Dispatch thread, while every corelibs URLProtocolClient
  method reads the session's task registry, two dictionaries without a
  lock, as the session's work queue changes it ("Bad pointer dereference
  at 0x10" in URLSession.behaviour(for:)). URLProtocolStop now holds a
  lock across the check and the call, and on Linux makes each call on
  the task's work queue, where corelibs makes its own protocols' calls
  and runs stopLoading(); the queue is internal, so the helper finds it
  with Mirror. A stress test that sends 1000 requests, 50 at a time, on
  one session crashed in 8 of 10 runs with the calls made in place, and
  in none of 10 on the work queue.

- The four sign-in tests of "Discovery timeout over HTTP" assumed the
  server/discover POST reaches the authorizer within the 1-second
  discovery timeout. On a loaded runner it can come later, the timer
  abandons the probe, and connect moves on to initialize. The sign-in
  now lasts until release(); an attempt whose sign-in started after the
  deadline does not test the timer and is run again with a longer
  timeout (1, 4, then 12 seconds). With the timer changed to give up
  instead of waiting for a sign-in, all four fail. They also wait at
  most 30 seconds for connect, then record the attempt's state and
  cancel it, instead of holding the suite.

- Limits that only stop a hang are raised: nextIncoming() in
  StatelessGatingTests from 2 to 30 seconds, and the second-response
  test at HTTPClientTransportTests.swift:2888 from 5 to 30. The 2759 and
  2888 failures now print the outcome; 2759 ("fails promptly") keeps its
  2 seconds.

- testRoundtrip() raced each step against a 10-second Task.sleep of its
  own, and failed with that sleep's CancellationError on the iOS
  simulator when a trivial test took 26.7 seconds to finish. The steps
  now await the client's calls directly, the concurrent ones with async
  let, and the test's .timeLimit is the only limit.

- Every .timeLimit in the suite (59 tests) is 2 minutes instead of 1.
  These limits only stop a hang, and a stall of the simulator alone has
  taken 27 seconds of the minute.

With these and the next commit, 60 of 60 full test runs passed in a
2-CPU RHEL UBI 9 container (scripts/ci-linux.sh --cpus 2), against 23 of
27 before, with four 30-second freezes.

Assisted-by: Claude
…reaming

Both crash the process on swift-corelibs-foundation (release/6.1) when
a task is cancelled as it finishes or while it starts.

OAuthAuthorizationCodeFlow, without an OAuthAuthorizationDelegate,
crashed with

  SWIFT TASK CONTINUATION MISUSE: data(for:delegate:) tried to resume
  its continuation more than once, throwing ... Code=-999 "cancelled"
  ... https://localhost:8080/oauth/authorize?response_type=code...

perform sends the authorization request on its own no-redirect session
and ended with `defer { noRedirectSession.invalidateAndCancel() }`. A
task's success path calls the completion handler, which resumes the
data(for:) continuation, and only then sets the task to .completed
(_ProtocolClient.urlProtocolDidFinishLoading). The resumed caller can
run the defer in between: cancel() still sees .running, and its failure
path completes the task a second time. The request has always ended
when the defer runs, so the session is now invalidated with
finishTasksAndInvalidate(), as the guarded session of
URLSession.oauthData(for:redirects:validator:) already is. Cancelling
the caller still cancels the request through data(for:)'s own
cancellation handler. A stress run (40,000 authorizations, 12 busy
threads on 8 CPUs, Swift 6.1 on Ubuntu 24.04) crashed in 2 of 2 runs
before the change and in none of 6 after it; with fewer busy threads it
did not crash in 28 runs, so no test in the suite can show it reliably.

HTTPClientTransport crashed with

  FoundationNetworking/TaskRegistry.swift:118: Fatal error: Trying to
  access a behaviour for a task that in not in the registry
  URLSession.behaviour(for:)
  _ProtocolClient.urlProtocol(task:didFailWithError:)
  closure #1 in closure #2 in closure #1 in URLSessionTask.cancel()

StreamingSession, which streams HTTPClientTransport's responses and
ServerCard.fetch's on Linux, took the configuration as given, and
URLSessionConfiguration.ephemeral has an in-memory URLCache. With a
cache, corelibs first looks each request up in it, and a task cancelled
during that lookup can be failed after it has left its session's
registry. The session now copies the configuration and sets urlCache to
nil. MCP requests are never answered from a cache, and a server card is
revalidated with its ETag through fetch(from:ifNoneMatch:session:); on
Linux ServerCard.fetch therefore no longer reads the session's cache.
Apple platforms do not use this session. In 60 full test runs on two
CPUs, with the test fixes of the previous commit, the crash happened 11
times without the change and never in 60 runs with it.

The short-lived OAuth sessions that
URLSession.oauthData(for:redirects:validator:) and
OAuthAuthorizationCodeFlow.perform make on Linux also took the caller's
configuration, cache included, and data(for:) cancels their task when
the calling task is cancelled, so they were open to the same trap. They
now use the same copy without urlCache
(URLSessionConfiguration.withoutURLCache()); OAuth responses are not
meant to be served from a cache anyway.

The interleaving cannot be forced from a test, so the regression tests
check that each of these sessions has no cache: the streaming session
directly, and the OAuth sessions through a URLProtocol that reads the
session of its task. They fail without the change, and the streaming
test also checks that the caller's configuration keeps its own cache.

Assisted-by: Claude
@jeanmatthieu

Copy link
Copy Markdown
Contributor Author

Thanks @varun06, all four are addressed and folded into the existing three commits.

Should-fix

  1. OAuth sessions and urlCache. Agreed, they had the same exposure. A new internal URLSessionConfiguration.withoutURLCache() (Linux only, next to addingAdditionalHeaders(of:)) is now used by StreamingSession, by the guarded session in URLSession.oauthData(for:redirects:validator:), and by the no-redirect session in OAuthAuthorizationCodeFlow.perform. Apple platforms are unchanged. Two Linux regression tests cover the OAuth sessions: OAuthURLValidatorTests.testGuardedSessionHasNoURLCache and OAuthAuthorizationCodeFlowTests.performSessionHasNoURLCache. They use URLCacheProbe, a test URLProtocol that reads its task's session with Mirror, the same way URLProtocolStop finds the work queue. Both fail without the change. The CHANGELOG entry now mentions the OAuth sessions.
  2. design/linux.md. It now says that StreamingSession drops urlCache, so ServerCard.fetch on Linux doesn't read session.configuration.urlCache. The mock bullet now describes URLProtocolStop: calls on the task's work queue, and a recursive lock held across the check and the call. Two new bullets cover the URLCache trap and finishTasksAndInvalidate(), and a line under "Differences by design" covers the cache.

Nits

  • ifLoading(_:_:) now returns early when the stop is already set. The check on the work queue still decides.
  • stopWaitsForCallInProgress: the stopping thread now signals just before stop(), and the call waits for that signal before it holds the lock for 0.2 s. The call also records whether it saw isStopped, so a stop() that doesn't wait fails the test with "call after stop". The 0.2 s is still a hold and not a synchronization point: nothing outside the lock shows that stop() is blocked on it. But the hold can only reduce how often the test catches a regression. It can't fail a correct implementation.

Retested on the new head (f69fc9a6) with every CI job: macOS (including iOS), tvOS, visionOS, Mac Catalyst, RHEL UBI 9 and Ubuntu 24.04. All 14 GitHub checks pass too. The results are in the PR description.

@jeanmatthieu
jeanmatthieu merged commit 757270a into rel/1.0.0 Dec 1, 2026
14 checks passed
@jeanmatthieu
jeanmatthieu deleted the fix/additional-ci-failures branch December 1, 2026 09:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants