Motivation
* External callers of `macos_benchmarks.yml` (e.g. swift-log) currently invoke the reusable workflow once per benchmark package, paying self-hosted macOS runner-recycling cost for each invocation.
* There was no way to consolidate multiple packages into a single workflow call.
Modifications
* Add a new `benchmark_package_paths` input to `.github/workflows/macos_benchmarks.yml` and mark the singular `benchmark_package_path` as deprecated. The run step forwards both inputs straight to the script via `BENCHMARK_PACKAGE_PATH` and `BENCHMARK_PACKAGE_PATHS` environment variables; the workflow itself does no path parsing.
* Teach `scripts/check_benchmark_thresholds.sh` to accept `BENCHMARK_PACKAGE_PATHS` as either a JSON array of strings (auto-detected by a leading `[`, requires `jq`) or a newline-separated list, falling back to the legacy `BENCHMARK_PACKAGE_PATH` when unset or when the JSON form is an empty array.
* The script now loops over the resolved package list, wraps each iteration in a GitHub Actions `::group::`, and emits an `::error::` summary listing failed packages at the end, exiting non-zero if any failed.
Result
* A single workflow invocation runs all listed packages serially on each Swift/Xcode runner, paying runner-recycling cost once per Swift version instead of once per (version x package).
* Existing single-package callers keep working unchanged.
* Adopters of the script in other contexts (e.g. the Linux `benchmarks.yml`) can pick up multi-package support by passing `BENCHMARK_PACKAGE_PATHS` without reimplementing parsing or failure-collection logic.
### Motivation
We want our tests to pass in reasonable time.
### Changes
- Disable test
`ByteBufferCrashTests.setBytesWithoutContigiousStorageMoreThanUInt32maxBytes`
- Do not initialize data in `ByteBufferCrashTests.
takingOwnershipOfPointerThatsToLarge`
### Result
Tests are faster again.
Add configurable HTTP/1 decoder parsing limits
### Motivation:
The HTTP/1 decoder previously enforced a single hardcoded limit (80 KB per header field) and placed no cap on the total header-block size or the number of header fields per message. That made resource use unpredictable on requests with very many or very large headers, and there was no way for users to tune the limits for their workload.
### Modifications:
- Introduce a new public `NIOHTTPDecoderLimitConfiguration` exposing three parsing limits:
- maxHeaderFieldSize — maximum size of a single header field (name + value). Default: 80 KB.
- maxHeaderListSize — maximum total bytes of all header field names and values combined per message. Default: 2 MB.
- maxHeaderFieldCount — maximum number of header fields per message, including trailers. Default: 256.
- Plumb the configuration through `HTTPDecoder` / `HTTPRequestDecoder` / `HTTPResponseDecoder` initializers. The existing initializers continue to work unchanged via convenience overloads that fall back to
default limits.
- Expose the configuration on `NIOUpgradableHTTPServerPipelineConfiguration` and `NIOUpgradableHTTPClientPipelineConfiguration` so users of the typed pipeline setup can override the defaults.
- Track per-message totals in `BetterHTTPParser` and reject with `HTTPParserError.headerOverflow` when a limit is exceeded; counters reset at each new message so HTTP/1 pipelined connections behave
correctly.
- Add tests covering the success and error paths for each limit, the default behaviors, and that trailer fields count toward the field-count cap.
### Result:
Users can configure the HTTP/1 decoder's per-field-size, total-list-size, and field-count limits. Existing call sites continue to compile and run unchanged, now with bounded defaults across all three dimensions instead of just one.
## Summary
Trivial typo fix in the Swift Concurrency user-facing documentation.
In
[`Sources/NIOCore/Docs.docc/swift-concurrency.md`](https://github.com/apple/swift-nio/blob/main/Sources/NIOCore/Docs.docc/swift-concurrency.md),
the NIOAsyncChannel websocket-upgrade walkthrough reads:
> switch over the the `upgradeResult`. Importantly, we have to `await`
the
Drops the duplicate "the".
## Test plan
- [x] `grep -rEn '\b(the the|of of|in in|and and|that that|is is|to
to)\b' --include='*.swift' --include='*.md' Sources` — exit 1 after the
fix (was the only hit before).
## Scope
One-character change in one Markdown file. No code, no behavior, no API.
Co-authored-by: Cory Benfield <lukasa@apple.com>
The `getifaddrs` is only available on Android API 24+. So, to make
`swift-nio` compile on API 23, we need to add `@available` annotations
to the functions that use it. Which are just the two interface enumerate
functions.
### Result:
`swift-nio` can be compiled for Android 23.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
When connecting to services with multiple DNS records (e.g. Kubernetes
headless services), getaddrinfo returns addresses in a deterministic
order, causing all connections to go to the same backend. SwiftNIO now
provides a RandomizedDNSResolver that shuffles results.
### Modifications:
Add a dnsResolver property to HTTPClient.Configuration with two options:
.system (default, current behavior) and randomized (uses NIO's
RandomizedDNSResolver to shuffle DNS results). Apply the resolver to
ClientBootstrap during connection creation.
### Result:
Users can opt into randomized DNS resolution by setting
config.dnsResolver = .randomized, enabling load distribution across
multiple backend IPs while preserving the default behavior.
---------
Co-authored-by: Pavan sai kumar alladi <p_alladi@apple.com>
### Motivation
* The versioned `linux_nightly_6_1_enabled` input was deprecated a while
back in favour of `linux_nightly_next_enabled`, but the workflows still
combined the two with `||`/`&&` to keep the old name working.
* Now that callers have migrated, the shim is unnecessary complexity.
### Modifications
* In `unit_tests.yml`, `cxx_interop.yml`, and `benchmarks.yml`, replace
`inputs.linux_nightly_6_1_enabled || inputs.linux_nightly_next_enabled`
(and the `&&` variants) with just `inputs.linux_nightly_next_enabled`.
### Result
* `MATRIX_LINUX_NIGHTLY_NEXT_ENABLED` is driven solely by
`linux_nightly_next_enabled`.
Allow concurrent calls of `_createDirectory()` for file paths with
shared ancestors.
### Motivation:
The current implementation of
`_createDirectory(withIntermediateDirectories: true)` does not catch and
continue during execution when the intermediate directory path it is
trying to create already exists.
The current loop looks like this:
```swift
// Successfully made a directory, construct its children.
while let subdirectory = droppedComponents.popLast() {
path.append(subdirectory)
switch Syscall.mkdir(at: path, permissions: permissions) {
case .success:
continue
case let .failure(errno):
return .failure(.mkdir(errno: errno, path: path, location: .here()))
}
}
```
If we are concurrently trying to create directories `/foo/bar/dir1` and
`foo/bar/dir2`, we can fail with an error like `directory /foo already
exists` because one of the two task's `mkdir` syscall on line 928
errored with a `fileExists` error.
### Modifications:
The code adds the same logic already present on lines 894-907 of
`FileSystem.swift` to the failure case while iterating over the
subdirectory paths:
If the syscall errors because the directory already exists, (but didn't
exist during the loop on lines 886-923), we can safely continue. Another
task must have beaten our task to creating the directory, but that is
ok.
### Result:
Without this change, it would be difficult to actually call the
`FileSystem.createDirectory(withIntermediateDirectories: true)` function
in concurrent tasks, because if you were creating directories with
common ancestors, at least one of the 2 tasks would error due to the
race condition on directory creation. With this change, the
`createDirectory()` function can now be called concurrently without this
race issue potentially causing an error. I added the change to both the
`NIOFS` and `_NIOFileSystem` directories since they seem to be copies of
each other.
Co-authored-by: David Stern <d_stern@apple.com>
Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length.
### Motivation:
There are already some APIs for writing length-prefixed strings and
bytes with a custom strategy for encoding the length, but there weren't
helpers to read them.
### Modifications:
- Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length
- Add tests for the new APIs
- Fix DocC comments and improve the related article
### Result:
New APIs are added for reading length-prefixed strings and bytes with a
custom strategy for encoding the length.
### Motivation
* Xcode 15.4, 16.0, 16.1, 16.2, and 26 beta were already deprecated
and defaulted to `false` with no callers enabling them — redundant code.
* Xcode 16.3, 16.4, 26.0, and 26.1 will soon be uninstalled from the
runners. Their inputs are kept so downstream callers don't break, but
they should no longer produce any matrix entries.
### Modifications
* Remove input declarations, shell variables, matrix construction
blocks, and environment variable mappings for 15.4/16.0/16.1/16.2/26
beta entirely.
* Remove the matrix logic for 16.3/16.4/26.0/26.1 but retain the input
declarations as no-ops, with descriptions communicating they have no
effect.
### Result
* Less dead code in the shared workflow.
* Callers still passing `xcode_16_3` through `xcode_26_1` inputs get no
error but also no job — a graceful no-op while they migrate to
`swift_*` inputs.
### Motivation
* The `swift_*` inputs request Xcodes by Swift version with symlinks on
the runners owning the mapping. This more directly expresses the
library support window.
* All callers should migrate to `swift_6_1/6_2/6_3_enabled` instead of
specifying Xcode versions directly.
### Modifications
* Default `xcode_16_3/16_4/26_0/26_1/26_2_enabled` to `false` and mark
their descriptions as deprecated.
* Default `swift_6_1/6_2/6_3_enabled` to `true`.
### Result
* Repos still passing `xcode_*_enabled: true` explicitly continue to
work until they migrate.
This PR is a step towards having full support for FreeBSD in SwiftNIO.
It builds on #3494 to enable full compilation of the NIOCore target.
### Motivation:
Currently, SwiftNIO doesn't not compile on FreeBSD. This PR ensures that
at least the **NIOCore** module compiles correctly on FreeBSD.
### Modifications:
* Make `swift build --target NIOCore` work on FreeBSD.
### Result:
Using the available Swift FreeBSD x86_64 toolchain, it is now possible
to run `swift build --target NIOCore` successfully.
Strip Transfer-Encoding when Content-Length is present in HTTPEncoder
### Motivation
When `correctlyFrameTransportHeaders()` detected a `Content-Length`
header, it returned `.contentLength` without removing any existing
`Transfer-Encoding` header.
### Changes
- Remove `Transfer-Encoding` header, if a `Content-Length` header is
present
### Result
NIO sends either a `Content-Length` header or a `Transfer-Encoding`
header, but not both.
### Motivation:
Internally, `FTSInfo` always casted up to `CInt` from `UInt16` but for
some reason it only accepted `UInt16`. Let's add a `CInt` constructor
too.
### Modifications:
- Make internal `FTSInfo` constructible from `CInt` and `UInt16`.
### Result:
- Slightly better platform compatibility
- Possibly fewer casts
Split FoundationEssentials extensions from NIOFoundationCompat
### Motivation:
Resolves#3038
### Modifications:
Split NIOFoundationCompat into two and only import FoundationEssentials
and NIOFoundationEssentialsCompat where appropriate.
### Result:
ByteBuffer/Codable extensions can be used without vendoring the code or
linking to Foundation.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Fabian Fett <fabianfett@apple.com>
Add multi-version matrix support to Wasm Swift SDK workflow
### Motivation:
The WASM CI only ran against nightly-main, making it impossible to
distinguish toolchain regressions from code issues. Other repos in the
ecosystem using `swiftlang/github-workflows` already test against
`nightly-main`, `nightly-6.3`, and `6.3` by default.
### Modifications:
- Add `nightly_main_enabled`, `nightly_6_3_enabled`, and
`release_6_3_enabled` boolean inputs to `wasm_swift_sdk.yml` (all
defaulting to `true`, matching the coverage of
`swiftlang/github-workflows/swift_package_test.yml`) and update the
matrix generation to emit the appropriate entry per enabled version.
- Update `install_swift_sdk.sh` to support non-main branch snapshots by
deriving the API and download paths from `INSTALL_SWIFT_BRANCH` rather
than hardcoding `main`/`development`.
- Fail early with a clear message if the branch snapshot API returns no
results, rather than hitting an unbound variable error.
### Result:
WASM builds are now tested against multiple Swift versions, providing a
stable baseline to identify nightly-only regressions. Callers using the
workflow without arguments get the new default coverage automatically;
those who want to narrow the matrix can set specific version inputs to
`false`.
---------
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Translate `HTTPHeaderValidationTests` to Swift testing
### Motivation:
We want to add tests that use parameterized testing to
`HTTPHeaderValidationTests`. In order to allow this we first need to
translate this file to use Swift Testing instead of XCTest.
### Modifications:
- Mechanical translation of `HTTPHeaderValidationTests` from XCTest to
Swift testing.
### Result:
We can add parameterized tests to HTTPHeaderValidationTests.
### Motivation:
A recent PR (#3574) added support for customising the container
environment used for the matrix job for users of the reusable workflow.
It supported a custom Dockerfile and controlling `--cap-add` options to
the `docker run` command. Users who require this fine-grained control
with `--cap-add` also will benefit from being able to control the
`--security-opt` of the `docker run` command.
### Modifications:
- Add support for `--security-opt` docker flags in custom CI jobs
### Result:
Users of the reusable matrix CI workflow can control the
`--security-opt` for the container.
As observed by @weissi https://github.com/apple/swift-nio/issues/3382
### Motivation:
When `getaddrinfo` fails, SwiftNIO throws `SocketAddressError.unknown`
which discards the error code. This makes it impossible for callers to
distinguish between different failure reasons (e.g., `EAI_NONAME` vs
`EAI_AGAIN`), which is needed for retry logic and diagnostics.
### Modifications:
- Add `SocketAddressError.UnknownHost` struct that carries `host`,
`port`, `errorCode` (from `getaddrinfo`), and `errorDescription` (from
`gai_strerror`).
- Update `SocketAddress.makeAddressResolvingHost` and
`GetaddrinfoResolver` to throw/fail with the new error type on both
POSIX and Windows paths.
- Update existing test catch blocks to use the new error type.
- Add `testGetaddrinfoErrorCodeIsPreserved` to verify the error code is
captured.
### Result:
Callers can now inspect the `getaddrinfo` error code when host
resolution fails, enabling more specific error handling. Resolves
https://github.com/apple/swift-nio/issues/3382
### Questions for reviewer
1. **Should `case unknown(host:port:)` be deprecated?** — This enum case
is no longer thrown after this PR. Callers catching `.unknown` will
silently stop matching. Should I add
`@available(*, deprecated, renamed: "UnknownHost")` to provide a
migration path?
2. **Should the doc comment on `makeAddressResolvingHost` be updated?**
— The `- Throws:` line still references `SocketAddressError.unknown`
instead of the new
`SocketAddressError.UnknownHost`.
---------
Co-authored-by: Si Beaumont <beaumont@apple.com>
### Motivation
* Some consumers need to run CI inside custom Docker images with
additional Linux capabilities. The shared matrix workflows had no way to
express this — consumers had to maintain entirely bespoke CI workflows
instead.
### Modifications
* Added `MATRIX_LINUX_DOCKERFILE` and
`MATRIX_LINUX_DOCKER_CAPABILITIES_JSON` environment variables to
`generate_matrix.sh`. These propagate as `dockerfile` (string) and
`docker_capabilities` (JSON array) fields in the matrix JSON. Defaults
are empty/`[]` so existing callers are unaffected.
* Extended `add_matrix_entry()` with two optional trailing parameters
for the new fields.
* In `swift_test_matrix.yml`:
- Made the "Pull Docker image" step conditional — skipped when a
`dockerfile` is provided.
- Added a "Build Docker image from Dockerfile" step that builds the
image with `--build-arg SWIFT_IMAGE=<matrix image>` so consumers can
parameterise the Swift base image.
- Added `--cap-add` flags to `docker run` when `docker_capabilities` is
non-empty.
### Result
* Consumers can set `MATRIX_LINUX_DOCKERFILE` to a repo-relative path
and `MATRIX_LINUX_DOCKER_CAPABILITIES_JSON` to a JSON array of
capabilities. The matrix will build their Dockerfile per Swift version
and run containers with the requested capabilities.
* Existing consumers that don't set these variables see no change.
### Motivation
* The nightly Swift container images were still using `jammy` (Ubuntu
22.04) while the release images for 6.2+ have moved to `noble` (Ubuntu
24.04). We should align them.
### Modifications
* Changed `linux_nightly_next_container_image` and
`linux_nightly_main_container_image` in `generate_matrix.sh` from
`-jammy` to `-noble`.
### Result
* Nightly CI jobs now use noble-based images, consistent with the 6.2+
release images.
Motivation:
Swift 6.0 is no longer supported, we should bump the tools version and
remove it from our CI.
Modifications:
* Bump the Swift tools version to Swift 6.1
* Remove Swift 6.0 jobs where appropriate in main.yml, pull_request.yml
* Set language mode 5 in Benchmarks package manifest
Result:
Code reflects our support window.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Fix Windows Docker daemon not starting before polling
### Motivation:
When a Windows runner is restored from a saved VM image, the Docker
service sometimes fails to start during the "second boot" due to a
failure creating the required virtual switches.
Manually restarting the Docker service resolves the issue every time.
### Modifications:
Before polling `docker info`, check whether the Docker service is
running and start it if it is not.
### Result:
The Docker daemon becomes available reliably on Windows runners.
### Motivation:
An upcoming change in the library template adds a code snippet. Since
our cxx interop compatibility test script does not account for that
tests fail on nightly.
### Modifications:
Insert a newline character before other modifications.
### Result:
The cxx interop compatibility tests pass again on nightly.
### Motivation
* Swift 6.3 has been released, we should add it to our CI coverage.
### Modifications
* Update `apple/swift-nio/scripts/generate_matrix.sh`
* Update `apple/swift-nio/scripts/check-matrix-job.sh`
* Update reusable adopters of `swift_test_matrix.yml`
* Update end-user adopter workflows of `swift_test_matrix.yml`
* Remove stale `NIGHTLY_6_1` fallback shims from `generate_matrix.sh`
* Migrate `linux_nightly_6_1_arguments_override` to
`linux_nightly_next_arguments_override` in `main.yml` and
`pull_request.yml`
* Copy benchmark thresholds from 6.2
### Result
* NIO tests against Swift 6.3 in CI and downstream repositories can
opt-in.
* A successful run using the new Swift 6.3 jobs:
https://github.com/apple/swift-nio/actions/runs/23841350537/job/69497505715?pr=3565
Motivation:
I have no clear picture of why the package-benchmark packages have shown
sudden performance regressions without any associated code or infra
change, but they have.
Modifications:
Increased the thresholds
Result:
CI passes again
### Motivation:
`testCanPinThreadsToCores` crashes with a precondition failure
(`pthread_setaffinity_np failed: 22`) on CI environments where the
container's available CPUs don't start from 0.
```console
% docker run --rm -v $PWD:/pwd -w /pwd swift:6.2 nproc
8
```
Running the test in an environment where the CPUs didn't start from 0
crashed:
```console
% docker run --rm -v $PWD:/pwd -w /pwd --cpuset-cpus="2-3" swift:6.2 nproc
2
```
```console
% docker run --rm -v $PWD:/pwd -w /pwd --cpuset-cpus="2-3" swift:6.2 swift test --filter testCanPinThreadsToCores
...
◇ Suite "NIOThreadPoolTest" started.
◇ Test testCanPinThreadsToCores() started.
NIOPosix/LinuxCPUSet.swift:78: Precondition failed: pthread_setaffinity_np failed: 22
*** Signal 5: Backtracing from 0xf358a1ceb140... done ***
*** Program crashed: System trap at 0x0000f358a1ceb140 ***
Platform: arm64 Linux (Ubuntu 24.04.4 LTS)
Thread 0 "TP-#0" crashed:
0 0x0000f358a1ceb140 _assertionFailure(_:_:file:line:flags:) + 164 in libswiftCore.so
1 [ra] 0x0000ba727f86c0a0 static NIOThread.currentAffinity.setter + 939 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/LinuxCPUSet.swift:78:13
2 [ra] 0x0000ba727f878b48 closure #2 in NIOThreadPool._start(threadNamePrefix:) + 295 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/NIOThreadPool.swift:365:47
3 [ra] [thunk] 0x0000ba727f8fc5a0 thunk for @escaping @callee_guaranteed (@guaranteed NIOThread) -> () + 23 in swift-nioPackageTests.xctest at //<compiler-generated>
4 [ra] 0x0000ba727f8ff5c8 closure #1 in closure #1 in static ThreadOpsPosix.run(handle:args:) + 767 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/ThreadPosix.swift:186:21
5 [ra] [thunk] 0x0000ba727f8ff678 @objc closure #1 in closure #1 in static ThreadOpsPosix.run(handle:args:) + 11 in swift-nioPackageTests.xctest at //<compiler-generated>
6 [ra] 0x0000f358a03d595c <unknown> in libc.so.6
...
```
Also, when there was just one CPU, this test would pass but wasn't
actually testing the pinning because it was using
`min(1, System.coreCount / 2)` instead of `max`, which clamped down to 0
for the loop.
### Modifications:
- Select from available CPU IDs using `NIOThread.currentAffinity.cpuIds`
- Use `max` instead of `min` to still run the test on single core
environments.
### Result:
The test no longer crashes on CPU-restricted environments:
```console
% docker run --rm -v $PWD:/pwd -w /pwd --cpuset-cpus="2-3" swift:6.2 swift test --filter testCanPinThreadsToCores
...
◇ Suite "NIOThreadPoolTest" started.
◇ Test testCanPinThreadsToCores() started.
✔ Test testCanPinThreadsToCores() passed after 0.001 seconds.
✔ Suite "NIOThreadPoolTest" passed after 0.001 seconds.
✔ Test run with 1 test in 1 suite passed after 0.001 seconds.
```
## Summary
- NIOFileSystem's `open` syscall error mapping only handled `EACCES`
(`.permissionDenied`) but not `EPERM` (`.notPermitted`), causing EPERM
errors (e.g., on network volumes) to be classified as "unknown" instead
of `permissionDenied`
- Added `.notPermitted` alongside `.permissionDenied` in the `open()`
switch case in `FileSystemError+Syscall.swift` (both `NIOFS` and
`_NIOFileSystem` modules)
- Added corresponding test expectation for the new errno mapping
## Motivation
Other syscall handlers in the same file (`remove`, `symlink`, `unlink`,
`futimens`) already correctly handle both `.permissionDenied` and
`.notPermitted` as `permissionDenied`. The `open` handler was missing
this treatment.
Fixes#3559
## Test plan
- [x] Updated `testErrnoMapping_open` to verify `.notPermitted` maps to
`.permissionDenied`
- [ ] CI will validate on all supported Swift versions
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Motivation:
Similar to MultiThreadedEventLoopGroup, it is useful in some NUMA
circumstances to be able to pin thread pools to specific CPUs. This can
minimise the overheads of moving memory around across NUMA nodes.
Modifications:
Added a pinned CPUs initializer to NIOThreadPool
Result:
Users have more flexibility.
### Motivation
*
`MTELGScheduledCallbackTests.testCancelAfterShutdownDoesNotCallCancellationCallbackAgain`
is failing on iOS simulator CI. It schedules a callback with a
`.milliseconds(1)` deadline, then shuts down, expecting shutdown to
cancel the callback. On the simulator the 1ms timer fires before
shutdown processes, so the callback executes instead of being cancelled.
* This is the same class of bug previously fixed for
`testScheduledCallbackNotExecutedBeforeDeadline` in dcecf0cb.
### Modifications
* Change the scheduled callback deadline from `.milliseconds(1)` to
`.hours(1)` in
`testCancelAfterShutdownDoesNotCallCancellationCallbackAgain` (the
observed failure).
* Speculatively apply the same fix to
`testCancelExecutesCancellationCallback`,
`testCancelAfterCancelDoesNotCallCancellationCallbackAgain`, and
`testShutdownDoesNotCancelCancelledCallbacksAgain` which have the same
pattern.
* The `EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` subclasses use
virtual time so this does not extend test duration.
### Result
* Scheduled callback cancellation tests no longer depend on real-time
precision and should not flake on slow CI runners or simulators.
### Motivation
* `testFlatBlockingMapOnto` sets up a `flatMapBlocking` chain that
dispatches work to `DispatchQueue.global()`, but never waits for the
chain to complete before returning. The `defer` block calls
`syncShutdownGracefully()`, which shuts down the event loop while the
GCD dispatch is still in-flight. When the GCD work completes and tries
to deliver its result back to the event loop, it finds the loop already
shut down, causing a crash. On fast machines the GCD work completes
before shutdown, but on slow iOS simulators shutdown wins the race
consistently. This crash also kills whichever other test happens to be
running concurrently (typically
`testRepeatedTaskThatIsCancelledAfterRunningAtLeastTwiceNotifies`).
### Modifications
* Capture the `EventLoopFuture` from the `flatMapBlocking` chain and
call `.wait()` on it before the function returns, ensuring the GCD
dispatch delivers its result back to the event loop before shutdown
begins. Move the assertions from the `.whenSuccess` closure to after the
`.wait()`.
### Result
* The event loop is no longer shut down while GCD work is in-flight,
fixing the crash on iOS simulator CI.
### Motivation
`testCopyFileReplacingExistingFileSucceeds` (and
`testCopySymlinkReplacingExistingSymlinkSucceeds`) verify that no .tmp-
prefixed files are left behind after a `copyItem(replaceExisting: true)`
call on Linux. However, both tests create their files in the shared
system temp directory (e.g. /tmp) and then scan that entire directory
for .tmp- files. When other tests run in parallel, their in-flight
`copyItem(replaceExisting: true)` operations leave transient .tmp- files
in the same directory, causing spurious failures.
### Changes
- Both tests now create a dedicated subdirectory for their files, so the
temp file scan only sees files belonging to that specific test.
- Cleanup is handled via `addTeardownBlock` to ensure the subdirectory
is removed even if the test fails early.
### Results
The temp file assertions are no longer affected by concurrent test
activity or other processes writing to the shared temp directory,
eliminating the flakiness.
Increase job timeout for macOS tests from 30 to 60 minutes.
### Motivation:
We see test jobs getting cancelled, for example:
https://github.com/apple/swift-nio/actions/runs/23240305356
### Modifications:
Increase test time.
### Result:
Test jobs will complete.
This PR adds support for FreeBSD to the `CNIOSHA1` target and the
`NIOConcurrencyHelpers` target.
### Motivation:
This PR is partial because the `NIOCore` target still can't be built,
and the existing PR #3398 includes almost the same changes too.
However, #3398 is a little bit old. Besides, the source code in
`NIOConcurrencyHelpers` is used in other repositories now, for example:
- https://github.com/apple/swift-log/pull/398
- https://github.com/apple/swift-log/pull/387 was merged before
swift-nio is fixed.
So I think it's important to fix `NIOConcurrencyHelpers` first, even if
the entire swift-nio is yet to be fixed.
### Modifications:
- Make `swift build --target NIOConcurrencyHelpers` work on FreeBSD
- Make `swift build --target CNIOSHA1` work on FreeBSD
### Result:
The following commands finished successfully.
```shell
swift build --target NIOConcurrencyHelpers
swift build --target CNIOSHA1
```
Environment:
- FreeBSD 15.0-RELEASE-p1 x86_64
- [Swift on FreeBSD Preview
toolchain](https://forums.swift.org/t/swift-on-freebsd-preview/83064)
```
Swift version 6.3-dev (LLVM b58b2a34d509492, Swift cf535d8b998d09b)
Target: x86_64-unknown-freebsd14.3
Build config: +assertions
```
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation
* `testHalfCloseOwnOutputWithPopulatedBuffer` asserts that writing to a
half-closed channel produces `ChannelError.outputClosed`. However, after
flushing the buffered write and the FIN, the remote peer can process
both and fully close the connection before the subsequent write is
processed. When this happens the channel is fully closed and the write
fails with `.ioOnClosedChannel` instead.
* This race seems to be more likely on iOS simulators in CI.
### Modifications
* Accept either `.outputClosed` or `.ioOnClosedChannel` as valid errors
from the post-half-close write.
### Result
* The test no longer flakes on iOS simulator CI runs.
### Motivation
*
`MTELGScheduledCallbackTests.testScheduledCallbackNotExecutedBeforeDeadline`
is flakey on macOS CI. It schedules a callback with a 1ms deadline,
sleeps for 1µs via `Task.sleep`, then asserts the callback hasn't fired.
On a loaded CI runner, `Task.sleep` can overshoot well past 1ms, causing
the callback to fire before the assertion.
### Modifications
* Increase the scheduled callback deadline from `.milliseconds(1)` to
`.hours(1)` in `_BaseScheduledCallbackTests`. This makes it impossible
for the short sleep to overshoot past the deadline. The
`EmbeddedEventLoop` and `NIOAsyncTestingEventLoop` subclasses use
virtual time so this change is harmless to them.
### Result
* The test reliably asserts that a callback is not executed before its
deadline without depending on real-time sleep precision.
…oopTest`
### Motivation
* `Task.sleep(for:)` and the `Duration` literals (`.milliseconds`,
`.seconds`) require iOS 16.0+, tvOS 16.0+, and watchOS 9.0+, so these
calls cause build failures on simulator test destinations in CI.
### Modifications
* Replaced all five `Task.sleep(for:)` calls in `EventLoopTest.swift`
with the universally available `Task.sleep(nanoseconds:)`.
### Result
* `EventLoopTest` compiles for iOS, tvOS, and watchOS simulator
destinations. Verified locally with `xcodebuild build-for-testing`.
Add Swift-version-based inputs to macOS CI workflows
### Motivation
- The macOS CI runners now provide symbolic links mapping Swift versions
to Xcode apps ( `Xcode_swift_6.1.app`, `Xcode_swift_6.2.app`,
`Xcode_swift_6.3.app`), decoupling CI from specific Xcode versions.
- Several Xcode versions (`16.3`, `26.0`, `26.1`, `26.2`) are being
deprecated and removed from runners.
- The `-require-explicit-sendable` build argument overrides on Xcode
16.2/16.3 are no longer needed.
### Modifications
- Added `swift_6_1_enabled`, `swift_6_2_enabled`, `swift_6_3_enabled`
inputs (with corresponding `build_arguments_override`,
`test_arguments_override`, setup_command) to `macos_tests.yml`, all
defaulting to false.
- Added macos_ `swift_6_1_enabled`, macos_ `swift_6_2_enabled`, macos_
`swift_6_3_enabled` inputs to `macos_benchmarks.yml`.
- Added matrix entries using the `Xcode_swift_6.X.app` symlink paths.
- All existing `xcode_*` inputs remain unchanged for backwards
compatibility with downstream consumers.
- Enabled the new Swift-version inputs in main.yml and pull_request.yml,
removing the old `xcode_16_2/16_3` build argument overrides.
### Result
- SwiftNIO CI now runs macOS jobs for Swift `6.1`, `6.2`, and `6.3`
using the stable `Xcode_swift_6.X.app` symlinks.
- Downstream consumers are unaffected.
An example of this working here
https://github.com/apple/swift-nio/actions/runs/22960228328/job/66648462048?pr=3546
### Motivation
* `.timeLimit` from Swift Testing requires iOS 16.0+, watchOS 9.0+, and
tvOS 16.0+, but the package's deployment targets are lower, causing
build failures on all iOS/watchOS/tvOS simulator test steps in CI.
### Modifications
* Removed `.timeLimit(.minutes(1))` from the `@Suite` attribute on
`MultiThreadedEventLoopGroupTests`.
* Removed `.timeLimit(.minutes(1))` from the `@Test` attribute on
`testRepeatedTaskThatCancelsItselfNotifiesOnlyWhenFinished`.
### Result
* Tests should compile on iOS, watchOS, and tvOS simulator destinations.
* The CI job timeout still guards against hung tests.
Port `EventLoopTest` to Swift Testing.
### Motivation:
Tests should use the latest Swift Testing framework when possible.
### Modifications:
- Ported `EventLoopTest ` from XCTest to Swift Testing
### Result:
All tests continue to pass, EventLoopTest now has more modern Swift
Testing syntax.
Motivation:
NIO has had support for CPU pinning for 8 years, but nobody has ever
used it. Ask me how I know?
Modifications:
- Make the CPU pinning constructor public.
Result:
Users can pin MTELG threads to specific CPU cores, _finally_.