Commit Graph
2973 Commits
Author SHA1 Message Date
Rick Newton-Rogers 0e7d4e9534 Fix flakey testHalfCloseOwnOutputWithPopulatedBuffer on iOS sim (#3551)
### 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.
2026-03-17 19:19:37 +00:00
Rick Newton-Rogers e313684789 Fix flakey testScheduledCallbackNotExecutedBeforeDeadline (#3550)
### 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.
2026-03-16 11:36:02 +00:00
Cory Benfield b9d20d3476 Benchmarks for channel pipeline creation (#3531)
Motivation:

Creating channel pipelines is a fairly expensive operation. We should
try to know how expensive.

Modifications:

Add benchmarks for ChannelPipeline setup.

Result:

We'll know more.

Some results in a Linux VM on my M4 Max laptop:

```
=================
NIOCoreBenchmarks
=================

ChannelPipeline.init(0 handlers)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         3 │         3 │         3 │         3 │         3 │         3 │         3 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       156 │       177 │       214 │       322 │       367 │       989 │      2148 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

ChannelPipeline.init(1 handler)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         5 │         5 │         5 │         5 │         5 │         5 │         5 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       269 │       290 │       301 │       463 │       501 │       583 │       611 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

ChannelPipeline.init(3 handlers)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         9 │         9 │         9 │         9 │         9 │         9 │         9 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       477 │       521 │       540 │       553 │       574 │       817 │       907 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

ChannelPipeline.init(10 handlers)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │        23 │        23 │        23 │        23 │        23 │        23 │        23 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │      1263 │      1363 │      1404 │      1679 │      2146 │      2482 │      3133 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```
2026-03-16 11:23:45 +00:00
Rick Newton-Rogers b31565862a Pass inputs through env vars (#3549)
Pass workflow inputs through environment variables instead of inline
template expansion

### Motivation

* `${{ inputs.* }}` expressions used directly in `run:` blocks are
expanded by GitHub Actions before the shell runs, which can allow code
injection via template expansion (see
https://docs.zizmor.sh/audits/#template-injection).

### Modifications

* Move `${{ inputs.* }}` and `${{ matrix.config.* }}` references out of
`run:` blocks and into step-level `env:` blocks across 13 workflow
files.

### Result

* All high-confidence `template-injection` findings from `zizmor` are
resolved.
* No changes should be required in downstream caller workflows

This can be seen successfully in use via test commits here:
- https://github.com/apple/swift-nio/actions/runs/23000641572?pr=3549
- https://github.com/apple/swift-log/actions/runs/23001027416?pr=427
- https://github.com/grpc/grpc-swift-2/actions/runs/23001010064?pr=43
2.96.0
2026-03-12 12:57:22 +00:00
Rick Newton-Rogers daec044c3f Replace Task.sleep(for:) with Task.sleep(nanoseconds:) in `EventL… (#3548)
…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`.
2026-03-12 09:50:18 +00:00
Rick Newton-Rogers e7a0c5264f Add macos swift xcode mappings (#3546)
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
2026-03-11 16:48:43 +01:00
Rick Newton-Rogers 12f5bab201 Remove .timeLimit from EventLoopTest Swift Testing attributes (#3545)
### 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.
2026-03-11 14:06:54 +00:00
Vladimir Kukushkin 66e1c447ac Increase Docker daemon wait timeout for Windows (#3544)
Give Windows docker daemon more time to become available.
2026-03-10 16:53:54 +00:00
scottmarchant c06f48669a test: Port EventLoopTest to Swift Testing. (#3503)
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.
2026-03-10 14:25:05 +00:00
Cory Benfield 5b3cab2bb0 Make MTELG's support for CPU pinning public (#3543)
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_.
2026-03-09 16:58:55 +00:00
Rick Newton-Rogers 2fdfe86c6a Add debug_output_enabled parameter to macOS CI workflow (#3542)
### Motivation

* xcodebuild output is suppressed with `-quiet` in the macOS tests
workflow, making it hard to diagnose CI failures on the main branch.

### Modifications

* Add a `debug_output_enabled` boolean input to `macos_tests.yml`
(defaults to `false`), which controls a `QUIET_ARG` env var used by all
xcodebuild invocations.
* When `debug_output_enabled` is `true`, `-quiet` is elided and full
xcodebuild output is emitted.
* Enable `debug_output_enabled` in `main.yml` so nightly and main-branch
push builds produce verbose output.

### Result

* PR builds remain concise (default behaviour unchanged).
* Main-branch builds now include full xcodebuild output for easier
failure triage.
2026-03-09 15:57:47 +00:00
George Barnett 57a73c653b Deprecate System.udpMaxSegments (#3541)
Motivation:

System.udpMaxSegments purports to expose the value of UDP_MAX_SEGMENTS.
However this doesn't appear to be part of the UAPI so it always returns
nil.

Modifications:

- Deprecate `System.udpMaxSegments`
- Remove the C shim
- Update tests

Result:

After your change, what will change.
2026-03-09 15:46:31 +00:00
Stepan Ulyanin 182ae0b4f9 Add the replaceExisting to the _NIOFileSystem copyItem (#3535)
Adds the changes from https://github.com/apple/swift-nio/pull/3508 to
the `_NIOFileSystem`.
### Motivation:

We have added capability to overwrite regular files and symbolic links
to `NIOFS` `FileSystem.copyItem` in
https://github.com/apple/swift-nio/pull/3508. Now we want to port the
same logic to `_NIOFileSystem`.

### Modifications:

- Adds a new `FileSystemProtocol.copyItem` requirement with
`replaceExisting: bool` parameter along with a default implementation.
- Adds an implementation of the new `FileSystemProtocol.copyItem`
requirement to `_NIOFileSystem`'s `FileSystem` struct for regular files
and symbolic links.

### Notes

It seems that the tests for `FileSystem` are only in `NIOFS` - so no
tests are added in this PR.
2026-03-09 10:59:41 +00:00
Rick Newton-Rogers 7ba045dc7d Extend timeout in testShutdownCancelsOutstandingScheduledCallbacks (#3537)
Extend timeout in testShutdownCancelsOutstandingScheduledCallbacks

### Motivation:

* `testShutdownCancelsOutstandingScheduledCallbacks` can be flaky,
  particularly on slower systems like simulated devices in CI.
* In some circumstances the task can be executed before it has chance to
  be cancelled.

### Modifications:

* Schedule the task for the far future so that it is available to be
  cancelled even on slower systems.

### Result:

Less flaky tests.
2026-03-06 09:38:25 +00:00
Mihai ChioreanandCory Benfield acf9bbe0fd Support scoped IPv6 addresses in SocketAddress.init(ipAddress:port:) (#3525)
### Motivation

`SocketAddress.init(ipAddress:port:)` uses `inet_pton` to parse IP
address strings. `inet_pton` does not support the `%scope` suffix used
in IPv6 link-local addresses (e.g., `fe80::1%eth0`), causing these
addresses to fail with `failedToParseIPString`. This forces downstream
consumers like grpc-swift-nio-transport to reimplement scoped IPv6
parsing using `getaddrinfo` themselves.

Related: https://github.com/grpc/grpc-swift-nio-transport/issues/147

### Modifications

When the IP address string contains a `%` character, fall back to
`getaddrinfo` with `AI_NUMERICHOST` instead of `inet_pton`. This
properly parses the `%scope` suffix and sets `sin6_scope_id` in the
resulting `sockaddr_in6`. The scoped path is extracted into a private
`_parseScopedIPv6` helper, guarded with `#if !os(Windows) && !os(WASI)`.
The non-scoped `inet_pton` path is completely unchanged.

Added 5 tests:
- Named scope (`fe80::1%lo`) — verifies `sin6_scope_id` matches
`if_nametoindex`
- Numeric scope (`fe80::1%1`) — verifies numeric index parsing
- Scoped vs non-scoped inequality — different `sin6_scope_id` means
different addresses
- Invalid scopes rejected — empty scope and nonexistent interface both
throw
- Non-scoped regression — `::1` still works with `scope_id == 0`

### Result

`SocketAddress(ipAddress: "fe80::1%eth0", port: 80)` now succeeds and
preserves the scope ID in `sin6_scope_id`. Non-scoped addresses continue
to work exactly as before.

### Context

This came up while working on IPv6 link-local support in
[grpc-swift-nio-transport#146](https://github.com/grpc/grpc-swift-nio-transport/pull/146),
where the workaround was to use `getaddrinfo` directly in the gRPC
layer. The reviewer suggested upstreaming this to swift-nio so the
workaround can be removed.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-03-06 08:49:57 +00:00
Mike Drob 41c5f57611 shutdown simulators before launching more tests (#3539)
Shut down simulators between test runs

### Motivation:

I suspect the CI machines are underpowered and we see simulator load
failures during testing because we are running out of resources.

### Modifications:

Add a command to shutdown the simulators before running each simulator
test.

### Result:

Hopefully, tests will pass more reliably.
2026-03-05 10:26:00 +00:00
Fabian Fett ada5f7690b Improve NIOAsyncChannel performance with UnsafeContinuations (#3521)
Let's improve NIOAsyncChannels performance, by using UnsafeContinuations
instead of CheckedContinuations.

### Motivation:

We want to improve the performance for our async APIs.

### Modifications:

- Introduce a new typealias `NIOUnsafeContinuation` that behaves like a
UnsafeContinuation in release mode and like a CheckedContinuation in
debug mode.
- Use the `NIOUnsafeContinuation` inside the `NIOAsyncWriter`
- Use the `NIOUnsafeContinuation` inside the
`NIOThrowingAsyncSequenceProducer`

### Result:

Fewer allocations
2026-03-04 11:09:34 +00:00
Rick Newton-Rogers 1e51266e86 Static sdk version (#3534)
Fix static Linux SDK version hardcoding

### Motivation

* Nightly CI was failing with a checksum mismatch because the static
Linux SDK filename was hardcoded to `_static-linux-0.0.1`, but the
SDK has since been released as `0.1.0` with a different checksum.
* The swift.org releases API returns a `version` field alongside
the checksum for the `static-sdk` platform, so the version can be
resolved dynamically.

### Modifications

* Added `extract_static_sdk_version()` to read the `version` field from
the releases API response.
* In the `version` install path, override `sdk_suffix` with the
API-provided version rather than the hardcoded `0.0.1`.

### Result

* The correct SDK filename (`_static-linux-0.1.0`) is now resolved
and hopefully will continue to work for future version bumps.
2026-03-03 11:36:58 +01:00
Rick Newton-Rogers 83509ed06d ByteBuffer custom allocator support (#3526)
### Motivation

* Other libraries often have byte buffer storage with similar concepts
as NIO's `ByteBuffer`, linear storage with reader and writer indices -
it would be nice to have efficient conversion to and from these objects.
* Efficienct conversion would likely mean taking ownership of the byte
storage allocated by the other object and exposing `ByteBuffer`s
internals so that they may be owned by another object, there is no API
for this currently.

### Modifications

* Added new methods behind `CustomByteBufferAllocator` SPI.
* Added public `ByteBuffer` initializer for adopting
externally-allocated memory
* Made `ByteBufferAllocator` initializer public with custom
`malloc`/`realloc`/`free`/`memcpy` hooks
* Updated `realloc` signature to pass old capacity alongside new
capacity to allow implementations to copy over bytes
* Added `withVeryUnsafeMutableBytesWithStorageManagement` for mutable
storage access
* Updated all existing tests using internal allocator API to use the new
API
* Added tests for custom allocator functionality

### Result

* Custom allocators can manage `ByteBuffer` memory with full size
information
* External systems can transfer memory ownership to `ByteBuffer`
* System allocator maintains zero overhead due to inlining of the
wrapper
* API (SPI) is extensible for future allocation system integrations
2026-03-02 10:52:17 +00:00
Stepan Ulyanin fff2515d6e Add symlinkat, renameatx_np, and unlinkat system call wrappers to the _NIOFileSystem module (#3524)
Ports the added system calls from `NIOFS` (from
https://github.com/apple/swift-nio/pull/3505) to `_NIOFileSystem`:

> Adds three new system call wrappers for the `symlinkat`,
`renameatx_np`, and `unlinkat` system calls.

### Motivation:

`_NIOFileSystem` module is around for backward compatibility - hence, we
are porting the new feature to it.

### Modifications:

Exactly same as in https://github.com/apple/swift-nio/pull/3505 but
applied to the `_NIOFileSystem`:

> Related to https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470. This PR adds syscall
wrappers needed to atomically overwrite existing files or symlinks at
the destination during copy operations. On Linux, atomic overwrites
require a "copy to temp file, then rename" strategy. We use the `*at`
family of syscalls (which operate relative to directory file
descriptors) to avoid TOCTOU race conditions.
2026-03-02 10:00:35 +00:00
Cory Benfield d38344d14b Improve the performance of looking up the current SEL (#3530)
Motivation:

Right now we store our selectable event loop reference in a NIO
ThreadSpecificVariable. That's nice enough, but this has become a hot
code path in cases where users are using the complete concurrency
override. In those cases, the ThreadSpecificVariable forces us to both
call `pthread_getspecific` and to end up needing to perform a dynamic
cast to our expected type.

These dynamic casts are costly: in one sample project where we spent
fully 7.84% of the runtime in dispatching tasks onto the EL, the cost of
that dynamic cast _alone_ was 0.5% of the runtime, with
pthread_getspecific being another 0.2%. This is 10% of the cost of
dispatching a job, entirely unnecessarily.

Modifications:

- Use some fancy C thread-locals, which have much better performance:
see #3302 for more on that.
- Use Unamanged to pass the self reference into and out of the
thread-local, avoiding dynamic casts.

Result:

Further improved performance for concurrency takeover.

Before this change:

```
any() from event loop thread (fast path): 30.654833 ns/iteration
any() from outside (fallback path): 17.881084 ns/iteration
```

After this change:

```
any() from event loop thread (fast path): 11.571958 ns/iteration
any() from outside (fallback path): 17.52175 ns/iteration
```

Nearly a 3x speedup on that particular operation. Not so bad.

Note the irony that before this change it was actually more expensive to
call `any` from _on_ an EL thread than off it. Both calls had to call
pthread_getspecific, which means all of this cost was the runtime type
conversion.
2026-02-27 16:46:58 +00:00
Rick Newton-Rogers 79404950fa Scope benchmark threshold diff to Thresholds/ directory (#3529)
### Motivation

* `check_benchmark_thresholds.sh` runs `git add --intent-to-add .` and
`git diff HEAD` to show updated threshold files when benchmarks regress.
* The unscoped `.` caused the diff to include everything in the working
tree, including the `.build` directory, producing noisy output.

### Modifications

* Pass `${benchmark_package_path}/Thresholds/` to both `git add
--intent-to-add` and `git diff HEAD --` so only threshold files appear
in the diff.

### Result

* The diff printed on benchmark failure shows only threshold file
changes.
2026-02-27 15:10:34 +00:00
Rick Newton-Rogers 92daddf89b Disable Swift 5.10 CI jobs by default (#3528)
### Motivation

* Swift 5.10 is no longer actively supported and CI does not require it

### Modifications

* Default Swift 5.10 CI jobs to disabled

### Result

* Swift 5.10 CI jobs will not run unless opted-in
2026-02-27 14:38:11 +00:00
Cory Benfield 41fc4a7aff Make concurrency take over cheaper (#3527)
Motivation:

When using concurrency takeover, we currently spend nearly half the
runtime checking if our SelectableEventLoop has an enqueue function. We
know it does, but we just haven't given the compiler enough evidence.
This patch rewrites the code to prove it to the compiler.

Modifications:

- Expose internal functions without erased types on MTELG
- Use these internal functions, and call directly to SEL, eliminiating
the as!.

Result:

Massive perf improvement in task enqueueing.
2026-02-27 13:58:35 +00:00
Rick Newton-Rogers fb69e42d77 Add parallel execution mode for integration tests (#3522)
Add parallel execution mode for integration tests

### Motivation:

Integration tests regularly take 21m in CI; they're the long pole.

### Modifications:

* Allocation count tests are now run in parallel if
`NIO_ALLOC_COUNTER_TESTS_PARALLEL` is `true`, tests in a given file
are still in serial.
* Test output is catted to different files and recovered and printed in
the order in which the tests were started.

### Result:

Integration test execution (and therefore a PR's CI checks) goes from
21m to 10m
2026-02-27 11:47:06 +00:00
Rick Newton-Rogers abe12cf13b Apple platforms CI issues (#3519)
Apple platform simulator CI failures

### Motivation

* Several tests failed when testing against simulators for Apple
platforms (iOS, tvOS, watchOS, visionOS)

### Modifications

* Added `@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)` to each
`@Test` method in `NIOThreadPoolTest`, `EventLoopFutureTest`, and
`NIOTransportAccessibleChannelCoreTests` to match the availability of
the APIs they use (`timeLimit` and `withUnsafeTransportIfAvailable`).
* Removed `.timeLimit(.minutes(1))` from the `@Suite` declarations on
`NIOThreadPoolTest` and `EventLoopFutureTest` - the `@Suite` macro
cannot be used with `@available`, so `timeLimit` cannot be used.
* Skip `testHomeDirectoryFromPasswd` on simulator targets via
`#if targetEnvironment(simulator)` / `XCTSkip`, since simulators retu>
success but nil information when invoking `getpwuid_r`.

### Result

* Apple simulator platform builds and test runs no longer fail due to
these issues. Some infrastructure issues remain to be resolved
separately.
2026-02-26 13:03:18 +00:00
Franz Busch 8d19278bde Wait for the docker daemon on Windows (#3520)
Sometimes the docker daemon on Windows runners isn't ready immediately.
This adds a step to wait for it to become ready.
2026-02-26 10:18:47 +01:00
Rick Newton-Rogers 8f6f8361ff benchmark diff missing new threshold files (#3516)
### Motivation

* When threshold files don't exist yet, `thresholds update` creates new
untracked files. `git diff HEAD` only shows changes to tracked files, so
newly created threshold files were silently omitted from the diff.

### Modifications

* Run `git add --intent-to-add .` before `git diff HEAD` so that
untracked files are registered in the index and appear in the diff
output without staging their contents.

### Result

* The diff output now includes newly created threshold files.
2026-02-23 13:29:00 +00:00
Rick Newton-Rogers 83b0fcd82d Benchmark diffs not being output on threshold regression (#3515)
### Motivation

* `check_benchmark_thresholds.sh` was updated to check for exit code 2
from `swift package benchmark thresholds check` to distinguish threshold
regression from build errors.
* It seems SwiftPM's `CommandPlugin` infrastructure always exits with
code 1 when `performCommand` throws, regardless of the error's raw
value. So the exit code is never 2, causing all regressions to fall
through to the `else` branch and be misreported as build errors, with no
diff output.

### Modifications

* Remove the `rc == 2` check and instead attempt `thresholds update` for
any non-zero `rc` from `thresholds check`.
* Use the result of `thresholds update` to distinguish regression
(success) from build error (failure).
* Remove `--exit-code` from `git diff` to prevent `set -uo pipefail`
from aborting the script before output is fully flushed.

### Result

* Benchmark threshold regressions correctly output the `=== BEGIN DIFF
===` section again.
* Actual build errors are still correctly detected and reported.
2026-02-20 15:54:04 +00:00
Rick Newton-Rogers 535c2f8260 switch from main to 0.0.7 for swiftlang workflows (#3514)
Motivation

* `@main` references to `swiftlang/github-workflows` are deprecated.

Modifications

* Replace `@main` with `@0.0.7` in all workflow files.

Result

* Workflow files reference a pinned version of
`swiftlang/github-workflows`.
2026-02-20 13:40:26 +00:00
Si Beaumont e932d3c4d8 Workaround test crashing when compiled in release mode on Swift 6.2 (#3511)
### Motivation:

Our post-merge, pre-release pipelines run tests for our supported Swift
versions in both debug and release mode. The recent PR to add
`withUnsafeTransportIfAvailable` added some tests for various valid and
invalid usages of the API. One of the invalid usages was causing the
tests to crash, when compiled in release mode, in the Swift runtime:

```
% docker run --rm -it -v $PWD:/pwd -w /pwd swift:6.2 swift test --filter testUnderlyingSocketAccessForSocketBasedChannel
[1/1] Planning build
Building for debugging...
[1/1] Write swift-version-24593BA9C3E375BF.txt
Build complete! (2.38s)
Test Suite 'Selected tests' started at 2026-02-18 13:28:18.905
Test Suite 'Selected tests' passed at 2026-02-18 13:28:18.905
         Executed 0 tests, with 0 failures (0 unexpected) in 0.0 (0.0) seconds
◇ Test run started.
↳ Testing Library Version: 6.2.3 (48a471ab313e858)
↳ Target Platform: aarch64-unknown-linux-gnu
◇ Suite NIOTransportAccessibleChannelCoreTests started.
◇ Test testUnderlyingSocketAccessForSocketBasedChannel() started.
✔ Test testUnderlyingSocketAccessForSocketBasedChannel() passed after 0.005 seconds.
✔ Suite NIOTransportAccessibleChannelCoreTests passed after 0.005 seconds.
✔ Test run with 1 test in 1 suite passed after 0.005 seconds.
```

```
% docker run --rm -it -v $PWD:/pwd -w /pwd swift:6.2 swift test -c release --filter testUnderlyingSocketAccessForSocketBasedChannel
[1/1] Planning build
Building for production...
[1/1] Write swift-version-24593BA9C3E375BF.txt
Build complete! (2.12s)
Test Suite 'Selected tests' started at 2026-02-18 13:27:12.102
Test Suite 'Selected tests' passed at 2026-02-18 13:27:12.103
         Executed 0 tests, with 0 failures (0 unexpected) in 0.0 (0.0) seconds
◇ Test run started.
↳ Testing Library Version: 6.2.3 (48a471ab313e858)
↳ Target Platform: aarch64-unknown-linux-gnu
◇ Suite NIOTransportAccessibleChannelCoreTests started.
◇ Test testUnderlyingSocketAccessForSocketBasedChannel() started.

*** Signal 11: Backtracing from 0xffff8854b1ec... done ***

*** Program crashed: Bad pointer dereference at 0x0000000000000000 ***

Platform: arm64 Linux (Ubuntu 24.04.4 LTS)

Thread 0 "NIO-ELT-1-#1" crashed:

  0                0x0000ffff8854b1ec tryCast(swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetMetadata<swift::InProcess> const*&, swift::TargetMetadata<swift::InProcess> const*&, bool, bool, bool) + 52 in libswiftCore.so
  1 [ra]           0x0000ffff8854b148 swift_dynamicCast + 79 in libswiftCore.so
  2 [ra] [system]  0x0000aaaab8668588 specialized ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable<A, B>(of:_:) + 135 in swift-nioPackageTests.xctest at //<compiler-generated>
  3 [ra]           0x0000aaaab8668148 closure #1 in NIOTransportAccessibleChannelCoreTests.testUnderlyingSocketAccessForSocketBasedChannel() + 3103 in swift-nioPackageTests.xctest at /tmp/swift-generated-sources/@__swiftmacro_13NIOPosixTests0049NIOTransportAccessibleChannelCoreTestsswift_IhHJqfMX55_16_33_309B77F97E02F918EDFF07092681CD49Ll6expectfMf8_.swift:1:40
  4 [ra] [thunk]   0x0000aaaab866be1c partial apply for closure #1 in NIOTransportAccessibleChannelCoreTests.testUnderlyingSocketAccessForSocketBasedChannel() + 15 in swift-nioPackageTests.xctest at //<compiler-generated>
  5 [ra]           0x0000aaaab7f410ec closure #1 in EventLoop.submit<A>(_:) + 95 in swift-nioPackageTests.xctest at /pwd/Sources/NIOCore/EventLoop.swift:1030:69
  6 [ra] [inlined] 0x0000aaaab841d468 closure #1 in SelectableEventLoop.run(_:) in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:618:17
  7 [ra] [inlined] 0x0000aaaab841d468 specialized withAutoReleasePool<A>(_:) in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:49:16
  8 [ra] [inlined] 0x0000aaaab841d468 SelectableEventLoop.run(_:) in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:615:9
  9 [ra]           0x0000aaaab841d468 SelectableEventLoop.runOneLoopTick(selfIdentifier:) + 535 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:809:22
 10 [ra]           0x0000aaaab8423e5c SelectableEventLoop.run() + 331 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/SelectableEventLoop.swift:923:38
 11 [ra] [inlined] 0x0000aaaab83de614 static MultiThreadedEventLoopGroup.runTheLoop(thread:uniqueID:parentGroup:canEventLoopBeShutdownIndividually:selectorFactory:initializer:metricsDelegate:_:) in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift:117:22
 12 [ra]           0x0000aaaab83de614 closure #1 in static MultiThreadedEventLoopGroup.setupThreadAndEventLoop(name:uniqueID:parentGroup:selectorFactory:initializer:metricsDelegate:) + 1255 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift:139:41
 13 [ra] [thunk]   0x0000aaaab83e1eec partial apply for closure #1 in static MultiThreadedEventLoopGroup.setupThreadAndEventLoop(name:uniqueID:parentGroup:selectorFactory:initializer:metricsDelegate:) + 39 in swift-nioPackageTests.xctest at //<compiler-generated>
 14 [ra] [thunk]   0x0000aaaab843f534 thunk for @escaping @callee_guaranteed (@guaranteed NIOThread) -> () + 23 in swift-nioPackageTests.xctest at //<compiler-generated>
 15 [ra]           0x0000aaaab84409dc closure #1 in closure #1 in static ThreadOpsPosix.run(handle:args:) + 319 in swift-nioPackageTests.xctest at /pwd/Sources/NIOPosix/ThreadPosix.swift:186:21
 16 [ra]           0x0000ffff86af595c <unknown> in libc.so.6
...


Registers:

 x0 0x0000ffff62fddfe0  48 60 00 58 ff ff 00 00 e0 e0 fd 62 ff ff 00 00  H`·Xÿÿ··ààýbÿÿ··
 x1 0x0000000000000000  0
 x2 0x0000ffff62fddff0  40 b4 01 5c ff ff 00 00 20 83 d1 b8 aa aa 00 00  @´·\ÿÿ·· ·Ñ¸ªª··
 x3 0x0000ffff58002038  03 03 00 00 00 00 00 00 01 00 00 00 01 00 00 00  ················
 x4 0x0000ffff62fddfa8  00 00 00 00 00 00 00 00 00 e0 fd 62 ff ff 00 00  ·········àýbÿÿ··
 x5 0x0000ffff62fddfa0  38 20 00 58 ff ff 00 00 00 00 00 00 00 00 00 00  8 ·Xÿÿ··········
 x6 0x0000000000000001  1
 x7 0x0000000000000000  0
 x8 0x0000000000000000  0
 x9 0x0000ffff886cf4e8  98 73 54 88 ff ff 00 00 08 be 5b 88 ff ff 00 00  ·sT·ÿÿ···¾[·ÿÿ··
x10 0x000000000000ffff  65535
x11 0x0000000000000000  0
x12 0x0000000000000000  0
x13 0x0000000000000001  1
x14 0x0000aaaab8e3ff2c  05 00 00 00 d4 2e a7 ff 00 00 03 00 51 00 00 00  ····Ô.§ÿ····Q···
x15 0x0000000000000009  9
x16 0x0000aaaab8d70520  f8 b0 54 88 ff ff 00 00 b4 45 55 88 ff ff 00 00  ø°T·ÿÿ··´EU·ÿÿ··
x17 0x0000ffff8854b0f8  ff 43 01 d1 fd 7b 02 a9 f6 57 03 a9 f4 4f 04 a9  ÿC·Ñý{·©öW·©ôO·©
x18 0x0000000000000000  0
x19 0x0000ffff58002038  03 03 00 00 00 00 00 00 01 00 00 00 01 00 00 00  ················
x20 0x0000ffff62fddff0  40 b4 01 5c ff ff 00 00 20 83 d1 b8 aa aa 00 00  @´·\ÿÿ·· ·Ñ¸ªª··
x21 0x0000000000000006  6
x22 0x0000000000000000  0
x23 0x0000aaaab86688b0  09 00 40 f9 09 01 00 f9 c0 03 5f d6 ff c3 00 d1  ··@ù···ùÀ·_Öÿ÷Ñ
x24 0x0000ffff5c01b440  f0 9d d9 b8 aa aa 00 00 03 00 00 00 08 00 00 00  ð·Ù¸ªª··········
x25 0x0000aaaab8d18320  0c 9c e2 b8 aa aa 00 00 ec 3c 3a b8 aa aa 00 00  ··â¸ªª··ì<:¸ªª··
x26 0x0000ffff62fde170  6e 69 6c 00 00 00 00 00 00 00 00 00 00 00 00 e3  nil············ã
x27 0x0000ffff62fde0e0  2d 00 00 00 00 00 00 d0 a0 3b de b8 aa aa 00 80  -······Ð ;Þ¸ªª··
x28 0x0000ffff886c6c28  02 02 00 00 00 00 00 00 30 b0 6f 88 ff ff 00 00  ········0°o·ÿÿ··
 fp 0x0000ffff62fddf30  b0 df fd 62 ff ff 00 00 48 b1 54 88 ff ff 00 00  °ßýbÿÿ··H±T·ÿÿ··
 lr 0x0000ffff8854b148  1f 08 00 71 c0 00 00 54 1f 04 00 71 c1 00 00 54  ···qÀ··T···qÁ··T
 sp 0x0000ffff62fddf00  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ················
 pc 0x0000ffff8854b1ec  68 01 40 f9 69 00 40 f9 1f fd 1f f1 f3 83 88 1a  h·@ùi·@ù·ý·ñó···


Images (20 omitted):

0x0000aaaab7d20000–0x0000aaaab8cd6d00 a17d4d145f2d2621f7b9d43c2b2d2a754b69002b swift-nioPackageTests.xctest /pwd/.build/aarch64-unknown-linux-gnu/release/swift-nioPackageTests.xctest
0x0000ffff86a70000–0x0000ffff86c09ec1 d5ef86dde36cbd3289566cf5098226035d76f2e1 libc.so.6                    /usr/lib/aarch64-linux-gnu/libc.so.6
0x0000ffff88160000–0x0000ffff8869e0c8 f62b9374639c58d0b60814a6fbec69d2b596cfc7 libswiftCore.so              /usr/lib/swift/linux/libswiftCore.so

Backtrace took 0.62s

error: Exited with unexpected signal code 11
```

The test is fine for both debug and release mode on Swift 6.0, 6.1, and
6.3-nightly.

### Modifications:

Since this is a valid construction and the crash is a Swift bug, and
since it only manifests on a specific Swift version, and since it's only
triggered when mis-using the API, we can just not perform this part of
the test on Swift 6.2. The API is fully functional when used correctly.

### Result:

Running NIO tests, compiled in release mode, no longer crashes on Swift
6.2.3.

### Local testings:

With this branch:

```
% docker run --rm -it -v $PWD:/pwd -w /pwd swift:6.2 swift test -c release --filter testUnderlyingSocketAccessForSocketBasedChannel
[1/1] Planning build
Building for production...
[8/8] Linking swift-nioPackageTests.xctest
Build complete! (38.46s)
Test Suite 'Selected tests' started at 2026-02-18 14:23:12.902
Test Suite 'Selected tests' passed at 2026-02-18 14:23:12.902
         Executed 0 tests, with 0 failures (0 unexpected) in 0.0 (0.0) seconds
◇ Test run started.
↳ Testing Library Version: 6.2.3 (48a471ab313e858)
↳ Target Platform: aarch64-unknown-linux-gnu
◇ Suite NIOTransportAccessibleChannelCoreTests started.
◇ Test testUnderlyingSocketAccessForSocketBasedChannel() started.
✔ Test testUnderlyingSocketAccessForSocketBasedChannel() passed after 0.002 seconds.
✔ Suite NIOTransportAccessibleChannelCoreTests passed after 0.003 seconds.
✔ Test run with 1 test in 1 suite passed after 0.003 seconds.
```
2.95.0
2026-02-18 15:11:55 +00:00
Stepan UlyaninandGeorge Barnett be8fdc13c0 Allow to copy files and symlinks while overwriting the destination (#3508)
Adds capability to NIOFS to copy regular files and symlink, allowing to
overwrite the destination.

### Motivation:

Per https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470 we want to add
`replaceExisting: bool` to `FileSystem.copyItem`.

### Modifications:

1. Adds `replaceExisting: bool` parameter to
`FileSystemProtocol.copyItem`.
2. Adds `replaceExisting: bool` parameter to `FileSystem.copyItem` and
implementation for regular files and symbolic links.
3. Adds tests.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2026-02-18 08:57:33 +00:00
Si BeaumontandAgam Dua b0e024792a Add opt-in API for channels to expose their underlying transport (#3509)
## Motivation

NIO channels abstract over an underlying transport mechanisms (sockets,
pipes, etc.), which users typically need not interact with. However,
there are scenarios where users need direct access to the underlying
transport for low-level operations that work outside NIOs abstraction.
One example is performing out out-of-band operations on the underlying
file descriptor for a socket-based channel.

This PR adds a structured way to access the underlying transport of a
channel, for channels that choose to implement it.

## Modifications

- Add a new `public protocol
NIOTransportAccessibleChannelCore<Transport>` which provides a scoped
`withUnsafeTransport(_:)`, used for channel implementations to opt-in.
- Add conformance to
`NIOTransportAccessibleChannel<NIOBSDSocket.Handle>` for
`BaseSocketChannel`, to make this API available for all socket-based
channels, including channels returned from the socket-based bootstrap
public APIs.
- Add public API
`ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable(_:)`

Note that not all channels need to or should their transport, which is
why this was added as an additional protocol that refines `ChannelCore`,
vs. extending `Channel` or `ChannelCore` with a default implementation.

The protocol uses a primary associated type allowing channels to provide
typed access to the transport. E.g. this could be used in NIO Transport
Services to expose the underlying `NWConnection`, if desired.

The method itself is spelled with "unsafe", uses scoped access, and has
clear documentation that users must not violated any of NIOs assumptions
about the state of the underlying transport. It's very much not intended
for every day use. It being on `ChannelCore` should defer users of the
low-level API, since `Channel._channelCore` is marked as for NIO
internal use, and the public `withUnsafeTransportIfAvailable(_:)` will
take care of the runtime checks for channels that have opted into this
API.

## Result

- New opt-in API for channel implementations to expose their underlying
transport
- All socket-based channels from NIOPosix now expose the underlying
socket file descriptor
- New API
`ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable(_:)`
for users

---------

Co-authored-by: Agam Dua <agam_dua@apple.com>
2026-02-17 16:12:58 +00:00
Fabian Fett 2fdda6c78e Fix benchmark succeeding – even though Benchmark build failed (#3502)
### Motivation:

Currently if there is an error in the Benchmark targets, that prevents
the Benchmark to build correctly, we still get a CI success.

### Modifications:

- Check for the threshold changed error

### Result:

- More reliable CI
2026-02-17 10:30:44 +00:00
Si Beaumont c329d1e173 Fix C++ interop CI script to work with changes in SwiftPM (#3510)
### Motivation:

SwiftPM behaviour has changed in recent Swift nightlies.

In most recent released version of Swift, SwiftPM will use the parent
directory name for the source and test target directory too, even when
it contains a period:

```
% docker run -it swift:6.2 bash -c 'mkdir -p /tmp/foo.bar && cd /tmp/foo.bar && swift package init'
Creating library package: foo.bar
Creating Package.swift
Creating .gitignore
Creating Sources
Creating Sources/foo.bar/foo_bar.swift
Creating Tests/
Creating Tests/foo.barTests/
Creating Tests/foo.barTests/foo_barTests.swift
```

Note in the above how it replaces the `.` with a `_` in the source
files, but the directories retain the `.`.

In the recent nightly-main, SwiftPM has also started replacing `.` with
`_` in the target directory names:

```
% docker run -it swiftlang/swift:nightly-main bash -c 'cat /etc/motd && mkdir -p /tmp/foo.bar && cd /tmp/foo.bar && swift package init'
################################################################
#                                                              #
# Swift Nightly Docker Image                                   #
# Tag: swift-DEVELOPMENT-SNAPSHOT-2026-02-06-a                 #
#                                                              #
################################################################
Creating library package: foo.bar
Creating Package.swift
Creating .gitignore
Creating Sources
Creating Sources/foo_bar/foo_bar.swift
Creating Tests/
Creating Tests/foo_barTests/
Creating Tests/foo_barTests/foo_barTests.swift
```

Probably this
https://github.com/swiftlang/swift-package-manager/pull/9252.

This breaks our CI automation, only on nightly-main, because we run
`swift package init` in a directory created by `mktemp -d`, which, by
default, follows the pattern `tmp.XXXXXXX`.

### Modifications:

Create temporary directory for Swift package using explicit pattern
containing no periods.

### Result:

C++ interop CI should now work again on nightly-main Swift, and continue
to work on all supported Swift versions.
2026-02-11 17:13:33 +00:00
Raphael d948192838 Don't send (in)active when channel closes directly (#3497)
### Motivation

Issue #2773 reports a problem where channels can receive
`channelInactive` before `channelActive`. This breaks expectations and
should not happen. Instead of sending them in the wrong order, this PR
suppresses both of them in those cases.

### Modifications

* Add a test to reproduce the problematic behavior.
* Update the state machine to split the active state into two. This
decouples succeeding the promise from sending the signal. Transiting to
closing only sends `channelInactive` when originating from the state
that sent `channelActive`.

### Result

Address #2773.

Edit: Updated modifications to reflect latests commit.
2026-02-11 15:46:19 +00:00
Kushal Pisavadia 9b92dcd5c2 Replace ConditionLock with wake-one signalling NIOThreadPoolWorkAvailable (#3507)
**TL;DR** This change leads to a ~90% reduction in observed system CPU
time for some use cases by waking a single thread, instead of all idle
threads.

# Changes

Inlining the commit messages here.

## Add NIOThreadPool submit throughput benchmarks

### Motivation

`NIOThreadPool` had no benchmarks measuring submit overhead. This makes
it difficult to evaluate the cost of signalling changes or to catch
latency regressions.

### Modifications

Add thread pool submit benchmarks, covering use cases with 4-thread and
16-thread pools.

### Result

`NIOThreadPool` submit throughput and context-switch overhead are now
tracked by benchmarks.

### Benchmark Results

<details>

```
NIOThreadPool.serial_wakeup(16 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        77 │        78 │        79 │        80 │        80 │        92 │        92 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │       106 │       107 │       108 │       109 │       110 │       116 │       116 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │      1649 │      1752 │      1768 │      1795 │      1826 │      1929 │      1929 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │      1701 │      1805 │      1821 │      1849 │      1879 │      1987 │      1987 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        51 │        52 │        52 │        53 │        53 │        57 │        57 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │       167 │       177 │       178 │       181 │       183 │       200 │       200 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

NIOThreadPool.serial_wakeup(4 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        44 │        44 │        44 │        45 │        45 │        45 │        45 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        65 │        65 │        65 │        66 │        66 │        67 │        67 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │       159 │       162 │       163 │       165 │       166 │       169 │       169 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │       178 │       182 │       183 │       185 │       186 │       190 │       190 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        19 │        19 │        20 │        20 │        20 │        21 │        21 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        76 │        79 │        79 │        80 │        80 │        82 │        82 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```

</details>

## Replace `ConditionLock` with wake-one signalling
`NIOThreadPoolWorkAvailable`

### Motivation

`NIOThreadPool` used `ConditionLock` which calls
`pthread_cond_broadcast` on every state change, waking all threads when
only one work item is enqueued. This causes a thundering-herd problem.

### Modifications

Add `NIOThreadPoolWorkAvailable` in NIOConcurrencyHelpers that uses
`pthread_cond_signal` (wake-one) for work submission and
`pthread_cond_broadcast` only for shutdown. Replace
`ConditionLock<_WorkState>` and the `_WorkState` enum in `NIOThreadPool`
with this new primitive.

### Result

Submitting a work item wakes exactly **one** thread instead of all
threads.

### Benchmark Results

<details>

```
NIOThreadPool.serial_wakeup(16 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        20 │        20 │        20 │        20 │        20 │        20 │        20 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        40 │        40 │        40 │        40 │        40 │        40 │        40 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │        47 │        49 │        49 │        50 │        50 │        55 │        55 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │        57 │        58 │        59 │        60 │        61 │        67 │        67 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        10 │        10 │        10 │        10 │        10 │        12 │        12 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        54 │        55 │        56 │        56 │        57 │        65 │        65 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

NIOThreadPool.serial_wakeup(4 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        20 │        20 │        20 │        20 │        20 │        20 │        20 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        40 │        40 │        40 │        40 │        40 │        40 │        40 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │        45 │        46 │        46 │        47 │        57 │        75 │        75 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │        54 │        55 │        56 │        57 │        68 │        87 │        87 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (μs) *   │      9055 │      9372 │      9478 │      9765 │     10887 │     12585 │     12585 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        52 │        53 │        53 │        54 │        64 │       124 │       124 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```

</details>
2.94.1
2026-02-10 20:01:35 +00:00
Stepan Ulyanin db01d87942 Add symlinkat, renameatx_np, and unlinkat system call wrappers (#3505)
Adds three new system call wrappers for the `symlinkat`, `renameatx_np`,
and `unlinkat` system calls.

### Motivation:

Related to https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470. This PR adds syscall
wrappers needed to atomically overwrite existing files or symlinks at
the destination during copy operations. On Linux, atomic overwrites
require a "copy to temp file, then rename" strategy. We use the `*at`
family of syscalls (which operate relative to directory file
descriptors) to avoid TOCTOU race conditions.

### Modifications:

1. Adds three system call wrappers for the `symlinkat`, `renameatx_np`,
and `unlinkat` system calls.
2. Adds related tests
3. Updates the `FileSystemError` for `symlink` and `unlink` to take in
the system call name to allow for the `*at` names to be passed.
2026-02-09 08:38:25 +00:00
Si Beaumont edad6d8a9b Clarify state and relationship of NIOFileSystem and _NIOFileSystem in API docs (#3504)
### Motivation:

`NIOFileSystem` currently exposes the same API as `_NIOFileSystem`,
which is not API stable. `NIOFileSystem`
was created in error, and its lack of underscore incorrectly implies API
stability. Users who are currently importing `NIOFileSystem` should
ideally move to `_NIOFileSystem`. However this isn't made clear in the
docs:

1. The README talks about the non-underscored `NIOFileSystem`.
2. There are no hosted API docs `NIOFileSystem`.
3. The hosted API docs for `NIO` point to the docs for `NIOFileSystem`
-- results in 404.

### Modifications:

- Update the README to refer to `_NIOFileSystem`.
- Update the hosted API docs for `NIO` to point to docs for
`_NIOFileSystem`.
- Add hosted API docs for `NIOFileSystem` with a statement explaining
the situation and pointing people to the docs
  for `_NIOFileSystem`.

### Result:

Clearer documentation on the state and relationship of the
`NIOFileSystem` and `_NIOFileSystem` modules.
2026-02-06 18:56:42 +00:00
scottmarchant 90ed88baab test: Port NIOThreadPoolTest to Swift Testing. (#3490)
Ports NIOThreadPoolTest in NIOPosix from XCTest to Swift Testing.

### Motivation:

Tests should use the latest Swift Testing framework when possible.

### Modifications:

- Ported `NIOThreadPoolTest` from XCTest to Swift Testing
- Updated test implementation from Dispatch to Swift Concurrency as
needed to support test functionality

### Result:

All tests continue to pass, NIOThreadPoolTest now has more modern Swift
Testing syntax.
2026-02-06 15:19:18 +00:00
scottmarchant e0476c6072 test: Port EventLoopFutureTest to Swift Testing. (#3491)
Port `EventLoopFutureTest` to Swift Testing. Includes some adjustments
to ensure tests are ran from the event loop, among other minor changes

### Motivation:

Tests should use the latest Swift Testing framework when possible.

### Modifications:

- Ported `EventLoopFutureTest ` from XCTest to Swift Testing
- Consolidated instantiations of `EmbeddedEventLoop()` into a private
function called `makeEventLoop` to allow for easier injection of a
different loop from a single location.
- Migrated some `.wait` usages to `.get` to allow tests to run async.

### Result:

All tests continue to pass, EventLoopFutureTest now has more modern
Swift Testing syntax.
2026-02-05 08:24:43 +00:00
Fabian Fett 6a6f7d7c33 Centralize UnsafeTransfer in NIOCore (#3492)
We have a number of copies of `UnsafeTransfer` and two copies of
`UnsafeMutableTransferBox` in our code base. Before introducing more of
those, lets centralize to just one using a `package` access modifier.
2026-02-03 10:27:30 +00:00
Franz Busch c90e69406b Fix Xcode 26.2 CI copy and paste error (#3499) 2026-01-28 16:32:30 +00:00
Franz Busch d1aaf4371a Add support for Xcode 26.2 (#3498)
Adds the required new inputs to the macOS tests and benchmark reusable
workflows
2026-01-28 16:47:02 +01:00
Franz Busch 5e72fc1029 Move nightly-next CI to 6.3 (#3496)
This PR moves the nightly-next CI to use the 6.3 images. Since those
checks should be non required on any user of this package and the name
of the check doesn't change with moving images this should be a
non-breaking change.
2.94.0
2026-01-27 16:32:59 +01:00
Si Beaumont 37ffc4b8d5 Add API to enable throwing in EmbeddedChannel.getOption and .setOption if channel is closed (#3495)
### Motivation:

Channels based on `BaseSocketChannel` throw in both `getOption` and
`setOption` if the channel has been closed, since the `setsockopt` will
fail. However, the current behavior of `EmbeddedChannel` is options
remain writable and readable on closed channels.

There are situations where we'd like to be able to model the runtime
behaviour of the real channel in tests, e.g. to test this fix:
https://github.com/apple/swift-nio-extras/pull/304.

### Modifications:

- Add API to enable throwing in `EmbeddedChannel.getOption` and
`.setOption` if channel is closed.
- Add a test for this new behavior.

### Result:

- New API to enable throwing in `EmbeddedChannel.getOption` and
`.setOption` if channel is closed.
- No observable change for existing users of `EmbeddedChannel`.
2026-01-27 12:06:55 +00:00
dependabot[bot] b2a14468d9 Bump actions/checkout from 6.0.1 to 6.0.2 (#3493)
Bumps [actions/checkout](https://github.com/actions/checkout) from 6.0.1
to 6.0.2.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/actions/checkout/releases">actions/checkout's
releases</a>.</em></p>
<blockquote>
<h2>v6.0.2</h2>
<h2>What's Changed</h2>
<ul>
<li>Add orchestration_id to git user-agent when ACTIONS_ORCHESTRATION_ID
is set by <a
href="https://github.com/TingluoHuang"><code>@​TingluoHuang</code></a>
in <a
href="https://redirect.github.com/actions/checkout/pull/2355">actions/checkout#2355</a></li>
<li>Fix tag handling: preserve annotations and explicit fetch-tags by <a
href="https://github.com/ericsciple"><code>@​ericsciple</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2356">actions/checkout#2356</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/actions/checkout/compare/v6.0.1...v6.0.2">https://github.com/actions/checkout/compare/v6.0.1...v6.0.2</a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/actions/checkout/blob/main/CHANGELOG.md">actions/checkout's
changelog</a>.</em></p>
<blockquote>
<h1>Changelog</h1>
<h2>v6.0.2</h2>
<ul>
<li>Fix tag handling: preserve annotations and explicit fetch-tags by <a
href="https://github.com/ericsciple"><code>@​ericsciple</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2356">actions/checkout#2356</a></li>
</ul>
<h2>v6.0.1</h2>
<ul>
<li>Add worktree support for persist-credentials includeIf by <a
href="https://github.com/ericsciple"><code>@​ericsciple</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2327">actions/checkout#2327</a></li>
</ul>
<h2>v6.0.0</h2>
<ul>
<li>Persist creds to a separate file by <a
href="https://github.com/ericsciple"><code>@​ericsciple</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2286">actions/checkout#2286</a></li>
<li>Update README to include Node.js 24 support details and requirements
by <a href="https://github.com/salmanmkc"><code>@​salmanmkc</code></a>
in <a
href="https://redirect.github.com/actions/checkout/pull/2248">actions/checkout#2248</a></li>
</ul>
<h2>v5.0.1</h2>
<ul>
<li>Port v6 cleanup to v5 by <a
href="https://github.com/ericsciple"><code>@​ericsciple</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2301">actions/checkout#2301</a></li>
</ul>
<h2>v5.0.0</h2>
<ul>
<li>Update actions checkout to use node 24 by <a
href="https://github.com/salmanmkc"><code>@​salmanmkc</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2226">actions/checkout#2226</a></li>
</ul>
<h2>v4.3.1</h2>
<ul>
<li>Port v6 cleanup to v4 by <a
href="https://github.com/ericsciple"><code>@​ericsciple</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2305">actions/checkout#2305</a></li>
</ul>
<h2>v4.3.0</h2>
<ul>
<li>docs: update README.md by <a
href="https://github.com/motss"><code>@​motss</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/1971">actions/checkout#1971</a></li>
<li>Add internal repos for checking out multiple repositories by <a
href="https://github.com/mouismail"><code>@​mouismail</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/1977">actions/checkout#1977</a></li>
<li>Documentation update - add recommended permissions to Readme by <a
href="https://github.com/benwells"><code>@​benwells</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2043">actions/checkout#2043</a></li>
<li>Adjust positioning of user email note and permissions heading by <a
href="https://github.com/joshmgross"><code>@​joshmgross</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2044">actions/checkout#2044</a></li>
<li>Update README.md by <a
href="https://github.com/nebuk89"><code>@​nebuk89</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2194">actions/checkout#2194</a></li>
<li>Update CODEOWNERS for actions by <a
href="https://github.com/TingluoHuang"><code>@​TingluoHuang</code></a>
in <a
href="https://redirect.github.com/actions/checkout/pull/2224">actions/checkout#2224</a></li>
<li>Update package dependencies by <a
href="https://github.com/salmanmkc"><code>@​salmanmkc</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/2236">actions/checkout#2236</a></li>
</ul>
<h2>v4.2.2</h2>
<ul>
<li><code>url-helper.ts</code> now leverages well-known environment
variables by <a href="https://github.com/jww3"><code>@​jww3</code></a>
in <a
href="https://redirect.github.com/actions/checkout/pull/1941">actions/checkout#1941</a></li>
<li>Expand unit test coverage for <code>isGhes</code> by <a
href="https://github.com/jww3"><code>@​jww3</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/1946">actions/checkout#1946</a></li>
</ul>
<h2>v4.2.1</h2>
<ul>
<li>Check out other refs/* by commit if provided, fall back to ref by <a
href="https://github.com/orhantoy"><code>@​orhantoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/1924">actions/checkout#1924</a></li>
</ul>
<h2>v4.2.0</h2>
<ul>
<li>Add Ref and Commit outputs by <a
href="https://github.com/lucacome"><code>@​lucacome</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/1180">actions/checkout#1180</a></li>
<li>Dependency updates by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a>- <a
href="https://redirect.github.com/actions/checkout/pull/1777">actions/checkout#1777</a>,
<a
href="https://redirect.github.com/actions/checkout/pull/1872">actions/checkout#1872</a></li>
</ul>
<h2>v4.1.7</h2>
<ul>
<li>Bump the minor-npm-dependencies group across 1 directory with 4
updates by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/1739">actions/checkout#1739</a></li>
<li>Bump actions/checkout from 3 to 4 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/1697">actions/checkout#1697</a></li>
<li>Check out other refs/* by commit by <a
href="https://github.com/orhantoy"><code>@​orhantoy</code></a> in <a
href="https://redirect.github.com/actions/checkout/pull/1774">actions/checkout#1774</a></li>
<li>Pin actions/checkout's own workflows to a known, good, stable
version. by <a href="https://github.com/jww3"><code>@​jww3</code></a> in
<a
href="https://redirect.github.com/actions/checkout/pull/1776">actions/checkout#1776</a></li>
</ul>
<h2>v4.1.6</h2>
<ul>
<li>Check platform to set archive extension appropriately by <a
href="https://github.com/cory-miller"><code>@​cory-miller</code></a> in
<a
href="https://redirect.github.com/actions/checkout/pull/1732">actions/checkout#1732</a></li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/actions/checkout/commit/de0fac2e4500dabe0009e67214ff5f5447ce83dd"><code>de0fac2</code></a>
Fix tag handling: preserve annotations and explicit fetch-tags (<a
href="https://redirect.github.com/actions/checkout/issues/2356">#2356</a>)</li>
<li><a
href="https://github.com/actions/checkout/commit/064fe7f3312418007dea2b49a19844a9ee378f49"><code>064fe7f</code></a>
Add orchestration_id to git user-agent when ACTIONS_ORCHESTRATION_ID is
set (...</li>
<li>See full diff in <a
href="https://github.com/actions/checkout/compare/8e8c483db84b4bee98b60c0593521ed34d9990e8...de0fac2e4500dabe0009e67214ff5f5447ce83dd">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/checkout&package-manager=github_actions&previous-version=6.0.1&new-version=6.0.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-26 09:24:06 +00:00
scottmarchant 5bf0267df4 build: Elide NIOPosix for WASI platforms only (#3485)
### Motivation:

Packages that consume NIOPosix should be able to compile to WASI
platforms without special configurations. This change elides the
NIOPosix source from WASI platforms to simplify configuration.

Without this change:

```swift
dependencies: [
    // Without this PR, downstream packages must maintain exhaustive platform list to exclude `.wasi`:
    .product(
        name: "NIOPosix",
        package: "swift-nio",
        condition: .when(platforms: [
            .macOS,
            .macCatalyst,
            .iOS,
            .tvOS,
            .watchOS,
            .visionOS,
            .driverKit,
            .linux,
            .windows,
            .android,
            .openbsd,
            // .wasi // <-- Need to exclude this, because there is no exclusion list api for SPM conditionals
        ])
    ),
]
```

With this change:

```swift
dependencies: [
    // Without this PR, downstream packages can consume NIOPosix simply:
    .product(name: "NIOPosix", package: "swift-nio"),
]
```

### Modifications:

- Add compiler directives (`#if !os(WASI)`) to all source files in
NIOPosix

### Result:

Downstream packages can compile to wasm without manually excluding the
NIOPosix dependency.

### Testing performed

- Verified `swift build --swift-sdk wasm32-unknown-wasip1 --target
NIOPosix` compiles, which demonstrates proper elision of source files in
NIOPosix that aren't wasm-ready.
- Confirmed GitHub [checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21151341738).
2026-01-23 16:39:32 +00:00
scottmarchant 3f80264185 build: Elide NIOEmbedded for WASI platforms only (#3484)
### Motivation:

Packages that consume NIOEmbedded should be able to compile to WASI
platforms without special configurations. This change elides the
NIOEmbedded source from WASI platforms to simplify configuration.

Without this change:

```swift
dependencies: [
    // Without this PR, downstream packages must maintain exhaustive platform list to exclude `.wasi`:
    .product(
        name: "NIOEmbedded",
        package: "swift-nio",
        condition: .when(platforms: [
            .macOS,
            .macCatalyst,
            .iOS,
            .tvOS,
            .watchOS,
            .visionOS,
            .driverKit,
            .linux,
            .windows,
            .android,
            .openbsd,
            // .wasi // <-- Need to exclude this, because there is no exclusion list api for SPM conditionals
        ])
    ),
]
```

With this change:

```swift
dependencies: [
    // Without this PR, downstream packages can consume NIOEmbedded simply:
    .product(name: "NIOEmbedded", package: "swift-nio"),
]
```

### Modifications:

- Fix compiler directive using in AsyncTestingChannel.swift to include
an extension

### Result:

Packages can compile to wasm without manually excluding the NIOEmbedded
dependency.

### Testing performed

- Verified `swift build --swift-sdk wasm32-unknown-wasip1 --target
NIOEmbedded` compiles, which demonstrates proper elision of source files
in NIOEmbedded that aren't wasm-ready.
- Confirmed GitHub [checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21151287289).
2026-01-22 18:58:24 +00:00
scottmarchant c337170d91 chore: Elide mutex variable from Lock class when it is unused (#3483)
### Motivation:

In reviewing a copy of this file in swift-log, @czechboy0
[noticed](https://github.com/apple/swift-log/pull/398#discussion_r2685605800)
that the `mutex` variable is essentially unused and unnecessarily
allocated for certain conditions. It is possible the compiler elided
usage. But given the unconditional variable reference in the `deinit`,
the compiler may not be able to.

This change ensures the `mutex` property is completely elided except in
the conditions where it is used.

### Modifications:

- Adjusted compiler directive pattern to completely elide the `mutex`
property for conditions where it would be unused.
- Adjusted `deinit` to avoid referencing `mutex` unless it is compiled
into the `Lock` class

### Result:

The `mutex` property is no longer allocated or even compiled into the
`Lock` class for unsupported configurations. All unit tests and checks
pass.

### Research:

The `deinit` used to have a blanket call to `mutex.deallocate()`. This
has been moved into the platform-specific checks within the `deinit`.
This allows complete elision of the `mutex` property altogether. The
`_runtime(_multithreaded)` condition [appears to be rooted to this
implementation](https://github.com/swiftlang/swift/blob/ffc51b914602765c5d680241796dbd3c3711fa6b/lib/Basic/LangOptions.cpp#L490).
Diving deeper, all [operating systems in this
list](https://github.com/swiftlang/swift/blob/ffc51b914602765c5d680241796dbd3c3711fa6b/lib/Basic/LangOptions.cpp#L554)
except for UnknownOS and WASI result in `_runtime(_multithreaded)`
returning true. That means that `OpenBSD` (and many other operating
systems besides windows) were almost certainly using the `#elseif
(compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) &&
_runtime(_multithreaded))` condition in the `deinit`. In conclusion,
moving `mutex.deallocate()` up into the conditional clauses inside
`deinit` should be identical to the previous implementation for all
operating systems except `llvm::Triple::UnknownOS`. And
`llvm::Triple::UnknownOS` is likely not to have every compiled anyways
due to the [check on line
32](https://github.com/apple/swift-nio/blob/main/Sources/NIOConcurrencyHelpers/lock.swift#L32).

So in summary, it is expected that this clean up will compile identical
to the previous implementation for all platforms except WASI platforms
that don't have pthread support. For non-pthread WASI platforms, the
unused `mutex` is properly elided from compilation altogether.

### Testing Done:

- Confirmed that unit tests pass locally using Xcode
- Verified [PR checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21149729751)
2026-01-22 17:57:10 +00:00