diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 774b41c..77668ed 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,6 +47,89 @@ jobs: with: fail_ci_if_error: true verbose: true + # A test process that crashes, such as one in a simulator, fails + # the job without saying why in the log. The test results and the + # crash reports that macOS writes for the process explain it. + - name: Upload Test Results and Crash Reports + if: failure() + uses: actions/upload-artifact@v7 + with: + name: xcode-test-results-${{ matrix.platforms }} + path: | + .build/derivedData/*/Logs/Test/*.xcresult + ~/Library/Logs/DiagnosticReports/*.ips + if-no-files-found: ignore + retention-days: 7 + # Xcode 27 can't download the iOS 18 simulator runtime, but the + # `macos-15` image has it installed, so this job copies its disk image + # and passes it to `spm-minimum-ios` as an artifact. + minimum-ios-runtime: + name: Copy Minimum iOS Simulator + runs-on: macos-15 + # Copying and uploading the 9 GB disk image takes a few minutes, so + # stop a stalled upload after 15 minutes rather than at GitHub's + # six-hour default. + timeout-minutes: 15 + permissions: + contents: read + steps: + - name: Checkout Repo + uses: actions/checkout@v7 + - name: Copy the Simulator Runtime + run: Scripts/copy-ios-18-simulator.sh runtime + - name: Upload the Simulator Runtime + uses: actions/upload-artifact@v7 + with: + name: ios-18-simulator-runtime + path: runtime + # Skip compressing the 9 GB disk image, which only slows the upload. + compression-level: 0 + # Only `spm-minimum-ios` needs the image, minutes later. + retention-days: 1 + spm-minimum-ios: + name: Build Xcode Minimum iOS + needs: minimum-ios-runtime + runs-on: xcode-27 + # A test that deadlocks keeps the test run from ending, so stop the + # job after 50 minutes rather than at GitHub's six-hour default. + timeout-minutes: 50 + permissions: + contents: read + steps: + - name: Checkout Repo + uses: actions/checkout@v7 + - name: Select Xcode Version + run: sudo xcode-select --switch /Applications/Xcode_27.2.app/Contents/Developer + - name: Download the Simulator Runtime + uses: actions/download-artifact@v8 + with: + name: ios-18-simulator-runtime + path: runtime + - name: Install the Simulator Runtime + run: Scripts/install-ios-18-simulator.sh runtime/iphonesimulator_18.5_22F77.dmg + - name: Build and Test Framework + run: Scripts/build.swift iOS18 + - name: Prepare Coverage Reports + run: ./Scripts/prepare-coverage-reports.sh + - name: Upload Coverage Reports + if: success() + uses: codecov/codecov-action@v7 + with: + fail_ci_if_error: true + verbose: true + # A test process that crashes, such as one in a simulator, fails + # the job without saying why in the log. The test results and the + # crash reports that macOS writes for the process explain it. + - name: Upload Test Results and Crash Reports + if: failure() + uses: actions/upload-artifact@v7 + with: + name: xcode-test-results-iOS18 + path: | + .build/derivedData/*/Logs/Test/*.xcresult + ~/Library/Logs/DiagnosticReports/*.ips + if-no-files-found: ignore + retention-days: 7 spm-swift: name: Swift Build Xcode runs-on: xcode-27 @@ -62,6 +145,45 @@ jobs: run: sudo xcode-select --switch /Applications/Xcode_27.2.app/Contents/Developer - name: Build and Test Framework run: xcrun swift test -c release -Xswiftc -enable-testing + # A test process that crashes fails the job without saying why in + # the log. The crash report that macOS writes for it explains it. + - name: Upload Crash Reports + if: failure() + uses: actions/upload-artifact@v7 + with: + name: swift-build-xcode-crash-reports + path: ~/Library/Logs/DiagnosticReports/*.ips + if-no-files-found: ignore + retention-days: 7 + tsan: + name: "Thread Sanitizer on macOS" + runs-on: xcode-27 + # A test that deadlocks keeps the test run from ending, so stop the + # job after 15 minutes rather than at GitHub's six-hour default. + timeout-minutes: 15 + permissions: + contents: read + steps: + - name: Checkout Repo + uses: actions/checkout@v7 + - name: Select Xcode Version + run: sudo xcode-select --switch /Applications/Xcode_27.2.app/Contents/Developer + - name: Build With Thread Sanitizer + run: xcrun swift build --build-tests --sanitize=thread + # When Thread Sanitizer reports a data race, the test process exits + # with an error, which fails this step. + - name: Test With Thread Sanitizer + run: xcrun swift test --skip-build --sanitize=thread + # A test process that crashes fails the job without saying why in + # the log. The crash report that macOS writes for it explains it. + - name: Upload Crash Reports + if: failure() + uses: actions/upload-artifact@v7 + with: + name: thread-sanitizer-crash-reports + path: ~/Library/Logs/DiagnosticReports/*.ips + if-no-files-found: ignore + retention-days: 7 linux: name: "Build and Test on Linux" runs-on: ubuntu-24.04 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 129b496..5974a5f 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -79,7 +79,9 @@ jobs: export PATH="$TOOLCHAIN:$DEVELOPER_DIR/usr/bin:$PATH" SDKROOT=$(xcrun --sdk macosx --show-sdk-path) export SDKROOT - arch -arm64 "$TOOLCHAIN/swift" build --target AsyncQueue + # Under the CodeQL tracer, SwiftPM's sandbox-exec cannot launch the compiled manifest + # ("Bad CPU type in executable"), so build without SwiftPM's sandbox. + arch -arm64 "$TOOLCHAIN/swift" build --target AsyncQueue --disable-sandbox - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v4 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..0c8b223 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,46 @@ +# swift-async-queue + +## Tests + +All tests must be deterministic. A test gives the same result on every +run of the same code: on correct code it passes every run, and on the +regression it guards it fails every run, or hangs, in which case CI's +job timeout is the failure. + +- Force the interleaving a test needs with semaphores, manual + executors, and test hooks. +- Never rely on sleeps, wall-clock timeouts, polling, or repetition. +- CI runs each test once. + +A few older tests loop in the hope of catching a bad interleaving: the +`sendsEventsInOrder` tests, the `executesAsyncBlocksAtomically` tests, +and `task_isNotReentrant` and `throwingTask_isNotReentrant`. They stay +as backstops because no deterministic test catches what they catch yet. +Delete a probabilistic test only once a deterministic test fails 10 of +10 runs for every bug it catches. + +## Coverage + +Code coverage must stay at 100%, the target in `codecov.yml`. + +## Concurrency + +Never cancel, resume, or escalate a task while holding a lock. That +includes the runtime's own lock on a task, which it holds while it runs +the task's cancellation and priority escalation handlers: do that work +after the lock is released, or from a new task. + +## Performance + +Prefer the faster code over the shorter code on the path that enqueues +a task. + +## Style + +`guard` is fine, but don't return early from an `if` without an `else`. + +## Documentation + +Write the README and documentation comments in the plain style of The +Swift Programming Language's chapter on concurrency. Use the terms it +uses, and don't invent new concepts. diff --git a/README.md b/README.md index c00ab17..70f3a0e 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,11 @@ [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fdfed%2Fswift-async-queue%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/dfed/swift-async-queue) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fdfed%2Fswift-async-queue%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/dfed/swift-async-queue) -A library of queues that enable sending ordered tasks from nonisolated to asynchronous contexts. +When you create several tasks from synchronous or `nonisolated` code, Swift doesn't guarantee the order in which they run, even if they all call the same actor. The queues in this library run tasks in the order you enqueue them. -## Task Ordering and Swift Concurrency +## Task ordering in Swift concurrency -Tasks sent from a nonisolated context to an asynchronous context in Swift Concurrency are inherently unordered. Consider the following test: +The following test creates 100 tasks in a loop. Each task calls the same actor and expects to be the next one to run: ```swift @Test @@ -38,15 +38,23 @@ func actorTaskOrdering() async { } ``` -Because the `Task` is spawned from a nonisolated execution context, the ordering of the scheduled asynchronous work is not guaranteed. +In the code above, the loop creates the tasks in order, but the tasks can run on the actor in a different order. When they do, the expectation fails. An [actor](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Actors) runs only one piece of code at a time, but it doesn't promise to run tasks in the order you create them. The queues in this library do. -While [actors](https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID645) are great at serializing tasks, there is no simple way in the standard Swift library to send ordered tasks to them from a nonisolated synchronous context, or from multiple execution contexts. +## Choosing a queue -### Executing asynchronous tasks in FIFO order +To enqueue a task, call `Task(on:)` with a queue instead of `Task.init`. Like `Task.init`, it works from synchronous code and returns the new task, so you can await its value or cancel it. -Use a `FIFOQueue` to execute asynchronous tasks enqueued from a nonisolated context in FIFO order. Tasks sent to one of these queues are guaranteed to begin _and end_ executing in the order in which they are enqueued. A `FIFOQueue` executes tasks in a similar manner to a `DispatchQueue`: enqueued tasks execute atomically, and the program will deadlock if a task executing on a `FIFOQueue` awaits results from the queue on which it is executing. +- Use a `FIFOQueue` when each task must finish before the next task starts. +- Use an `ActorQueue` when tasks must start in order on your own actor. The next task can start while an earlier one is suspended. +- Use `MainActor.queue` when tasks must start in order on the main actor. +- Use a `CancellableQueue` around a `FIFOQueue` or an `ActorQueue` when you need to cancel all of its tasks at once. + +## Running tasks one at a time with `FIFOQueue` + +A `FIFOQueue` runs one task at a time, first in, first out. Each task waits until every task enqueued before it has finished, including a task that is suspended at an `await`. So tasks start and finish in the order you enqueue them, much like work on a serial `DispatchQueue`. + +For example, here's how you might use a `FIFOQueue` so that the counter counts in order: -A `FIFOQueue` can easily execute asynchronous tasks from a nonisolated context in FIFO order: ```swift @Test func fIFOQueueOrdering() async { @@ -80,23 +88,35 @@ func fIFOQueueOrdering() async { } ``` -FIFO execution has a key downside: the queue must wait for all previously enqueued work – including suspended work – to complete before new work can begin. If you desire new work to start when a prior task suspends, utilize an `ActorQueue`. +In the code above, `incrementAndAssertCountEquals(_:)` is `nonisolated`, so synchronous code can call it. The closure you pass to `Task(on:)` is the task's *operation*. Here, the operation doesn't run on the actor, so it uses `await` to call `increment()` and read `count`. + +Keep these points in mind when you use a `FIFOQueue`: + +- Inside a task on a `FIFOQueue`, don't await another task that you enqueue on the same queue. The new task waits for the current task to finish, and the current task waits for the new one, so both wait forever. +- If the next task should start while one is suspended at an `await`, use an `ActorQueue`. +- To run the operation on an actor, call `Task(on:isolatedTo:)` with that actor. The operation receives the actor, so it can use the actor's state without `await`. -### Sending ordered asynchronous tasks to Actors from a nonisolated context +## Running tasks on your actor with `ActorQueue` -Use an `ActorQueue` to send ordered asynchronous tasks to an `actor`'s isolated context from nonisolated or synchronous contexts. Tasks sent to an actor queue are guaranteed to begin executing in the order in which they are enqueued. However, unlike a `FIFOQueue`, execution order is guaranteed only until the first [suspension point](https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID639) within the enqueued task. An `ActorQueue` executes tasks within its adopted actor's isolated context, resulting in `ActorQueue` task execution having the same properties as `actor` code execution: code between suspension points is executed atomically, and tasks sent to a single `ActorQueue` can await results from the queue without deadlocking. +An `ActorQueue` runs tasks on your own actor, and the tasks start in the order you enqueue them. Once a task starts, it behaves like any other code on the actor: -An instance of an `ActorQueue` is designed to be utilized by a single `actor` instance: tasks sent to an `ActorQueue` utilize the isolated context of the queue‘s adopted `actor` to serialize tasks. As such, there are a couple requirements that must be met when dealing with an `ActorQueue`: -1. The lifecycle of any `ActorQueue` should not exceed the lifecycle of its `actor`. It is strongly recommended that an `ActorQueue` be a `private let` constant on the adopted `actor`. Enqueuing a task to an `ActorQueue` instance after its adopted `actor` has been deallocated will result in a crash. -2. An `actor` utilizing an `ActorQueue` should set the adopted execution context of the queue to `self` within the `actor`’s `init`. Failing to set an adopted execution context prior to enqueuing work on an `ActorQueue` will result in a crash. +- When the task suspends at an `await`, the next task can start. +- Between [suspension points](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Defining-and-Calling-Asynchronous-Functions), the task runs without interruption from other code on the actor. +- A task can enqueue another task on the same queue and await its value. Unlike on a `FIFOQueue`, this doesn't wait forever. + +Each `ActorQueue` belongs to one actor. To set one up: + +1. Store the queue in a `private let` property of the actor, so that the queue can't outlive the actor. Enqueuing a task after the actor is deallocated crashes. +2. In the actor's `init`, call `queue.adoptExecutionContext(of: self)` once. This tells the queue which actor to run its tasks on. Enqueuing a task before this call crashes. + +For example, here's the counter again, using an `ActorQueue`: -An `ActorQueue` can easily enqueue tasks that execute on an actor’s isolated context from a nonisolated context in order: ```swift @Test func actorQueueOrdering() async { actor Counter { init() { - // Adopting the execution context in `init` satisfies requirement #2 above. + // Calling `adoptExecutionContext(of:)` in `init` is step 2 above. queue.adoptExecutionContext(of: self) } @@ -109,7 +129,7 @@ func actorQueueOrdering() async { } private var count = 0 - // Making the queue a private let constant satisfies requirement #1 above. + // Storing the queue in a `private let` property is step 1 above. private let queue = ActorQueue() } @@ -125,11 +145,14 @@ func actorQueueOrdering() async { } ``` -### Sending ordered asynchronous tasks to the `@MainActor` from a nonisolated context +In the code above, the operation receives the actor as `myself`. The operation runs on the actor, so it reads and changes `count` without `await`. + +## Running tasks on the main actor with `MainActor.queue` + +`MainActor.queue` is an `ActorQueue` that runs tasks on the main actor. It's ready to use, with no setup. As with any `ActorQueue`, tasks start in the order you enqueue them, and when a task suspends at an `await`, the next task can start. -Use `MainActor.queue` to send ordered asynchronous tasks to the `@MainActor`’s isolated context from nonisolated or synchronous contexts. Tasks sent to this queue type are guaranteed to begin executing in the order in which they are enqueued. The `MainActor.queue` is an `ActorQueue` that runs within the `@MainActor` global context: execution order is guaranteed only until the first [suspension point](https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID639) within the enqueued task. Similarly, code between suspension points is executed atomically, and tasks sent to the `MainActor.queue` can await results from the queue without deadlocking. +For example, here's how you might enqueue tasks on the main actor from a `nonisolated` method: -A `MainActor.queue` can easily execute asynchronous tasks from a nonisolated context in FIFO order: ```swift @MainActor @Test @@ -164,11 +187,14 @@ func mainActorQueueOrdering() async { } ``` -### Cancelling all executing and pending tasks +In the code above, the operation runs on the main actor, so it uses `self` without `await`. -Use a `CancellableQueue` to wrap a `FIFOQueue` or `ActorQueue` when you need the ability to cancel all currently executing and pending tasks at once. This is useful for scenarios like cancelling in-flight network requests when a view disappears, or abandoning a batch of operations when a user initiates a new action. +## Cancelling tasks with `CancellableQueue` -A `CancellableQueue` wraps an underlying queue and tracks all tasks enqueued on it. Calling `cancelTasks()` will cancel both the currently executing task and any tasks waiting in the queue. Tasks that have already completed are unaffected, and tasks enqueued after `cancelTasks()` is called will execute normally. +A `CancellableQueue` wraps a `FIFOQueue` or an `ActorQueue` and lets you cancel all of its tasks at once. For example, you might cancel a view's network requests when the view disappears, or cancel the work for a search when the user starts a new one. + +- Calling `cancelTasks()` cancels every unfinished task that you enqueued on the `CancellableQueue`, whether it's running or waiting. +- Tasks that already finished aren't affected. Tasks you enqueue afterward run as usual. ```swift @Test @@ -181,17 +207,17 @@ func cancellableQueueExample() async { } nonisolated - func loadImage(from url: URL) -> Task { + func loadImage(from url: URL) -> Task { Task(on: cancellableQueue) { myself in guard let image = try await myself.fetchImage(from: url) else { return nil } try Task.checkCancellation() - return myself.processImage(image) + return await myself.processImage(image) } } nonisolated func cancelAllLoads() { - // Cancels the currently loading image and any queued load requests. + // Cancels the image that is loading and the loads that are waiting. cancellableQueue.cancelTasks() } @@ -213,7 +239,7 @@ func cancellableQueueExample() async { let task2 = loader.loadImage(from: URL(string: "https://example.com/2.png")!) let task3 = loader.loadImage(from: URL(string: "https://example.com/3.png")!) - // Cancel all pending and executing loads. + // Cancel every load that hasn't finished. loader.cancelAllLoads() // All tasks are now cancelled. @@ -223,16 +249,75 @@ func cancellableQueueExample() async { } ``` -A `CancellableQueue` can also wrap a `FIFOQueue` for FIFO-ordered cancellable tasks: +In the code above, each load calls `Task.checkCancellation()` after it fetches the image. A cancelled load throws `CancellationError` there, so it doesn't process the image. Cancelled tasks still run in order; see [Cancellation](#cancellation). + +A `CancellableQueue` can also wrap a `FIFOQueue`: + ```swift let cancellableQueue = CancellableQueue(underlyingQueue: FIFOQueue()) Task(on: cancellableQueue) { - // This work can be cancelled via cancellableQueue.cancelTasks() + // Calling `cancellableQueue.cancelTasks()` cancels this task. await performWork() } ``` +## Task-local values, priority, and cancellation + +`Task(on:)` creates a new [unstructured task](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Unstructured-Concurrency), as `Task.init` does, and your operation runs in that task. So the task behaves like a task you create with `Task.init`: for example, your operation sees the [task-local values](https://developer.apple.com/documentation/swift/tasklocal) of the code that enqueues it. + +### Priority + +- A task runs at the priority you pass to `Task(on:)`. If you pass `nil`, it runs at the priority of the code that enqueues it, as with `Task.init`. +- `FIFOQueue(priority:)` and `ActorQueue(priority:)` give each of the queue's tasks at least that priority. A task that would run at a lower priority runs at the queue's priority instead. `MainActor.queue` has no priority of its own. +- On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, a task waiting in a queue raises the tasks ahead of it to its own priority. On earlier releases, they keep their own priority. + +### Cancellation + +Cancellation is [cooperative](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Task-Cancellation), as it is for any Swift task: + +- Calling a task's `cancel()` method, or calling `cancelTasks()` on the `CancellableQueue` you enqueued it on, marks the task as cancelled right away. +- The task keeps its place in the queue. Its operation still runs, in the same order as if you hadn't cancelled it. +- The operation decides how to respond. It can check `Task.isCancelled`, or call `Task.checkCancellation()` to throw a `CancellationError`. +- An operation that doesn't check for cancellation runs to completion, and the tasks behind it wait for it as usual. + +## Checking whether a queue has work left + +A `FIFOQueue` has an `isIdle` property, and an `ActorQueue` has a `hasStartedAllWork` property: + +- A `FIFOQueue` is idle when every task you enqueued on it has finished. A task that is suspended at an `await` hasn't finished. +- An `ActorQueue` has started all of its work when every task you enqueued on it has started running on the actor. The operations of its tasks might not have finished. + +Either value can change as soon as you read it: a task you enqueue afterward makes it `false` again. + +For example, here's how an actor that keeps one `FIFOQueue` per document might remove the queues it no longer needs: + +```swift +actor DocumentStore { + func save(_ contents: String, as name: String) -> Task { + let queue = queues[name] ?? FIFOQueue() + queues[name] = queue + return Task(on: queue) { + await self.write(contents, as: name) + } + } + + func removeIdleQueues() { + queues = queues.filter { !$0.value.isIdle } + } + + private func write(_ contents: String, as name: String) async { + // Write implementation… + } + + private var queues = [String: FIFOQueue]() +} +``` + +In the code above, the actor both enqueues the tasks and reads `isIdle`, so no task can be enqueued between the check and the removal. An actor that keeps `ActorQueue`s can remove them the same way by reading `hasStartedAllWork`. + +`CancellableQueue` has neither property. To check one, keep a reference to the queue it wraps, and read that queue's property. + ## Installation To install swift-async-queue in your project with [Swift Package Manager](https://github.com/apple/swift-package-manager), the following lines can be added to your `Package.swift` file: diff --git a/Scripts/build.swift b/Scripts/build.swift index d5a0447..ff9b06a 100755 --- a/Scripts/build.swift +++ b/Scripts/build.swift @@ -22,6 +22,9 @@ enum TaskError: Error { enum Platform: String, CaseIterable, CustomStringConvertible { case iOS + /// The minimum iOS version. Scripts/install-ios-18-simulator.sh + /// installs its simulator runtime, which Xcode 27 can't download. + case iOS18 case tvOS case macOS case macCatalyst @@ -33,6 +36,9 @@ enum Platform: String, CaseIterable, CustomStringConvertible { case .iOS: "platform=iOS Simulator,OS=27.2,name=iPad (A16)" + case .iOS18: + "platform=iOS Simulator,OS=18.5,name=iPad (10th generation)" + case .tvOS: "platform=tvOS Simulator,OS=27.2,name=Apple TV 4K (4th generation)" @@ -50,7 +56,8 @@ enum Platform: String, CaseIterable, CustomStringConvertible { var sdk: String { switch self { - case .iOS: + case .iOS, + .iOS18: "iphonesimulator" case .tvOS: @@ -107,9 +114,6 @@ for rawPlatform in rawPlatforms { xcodeBuildArguments.append("YES") xcodeBuildArguments.append("build") xcodeBuildArguments.append("test") - xcodeBuildArguments.append("-test-iterations") - xcodeBuildArguments.append("100") - xcodeBuildArguments.append("-run-tests-until-failure") try execute(commandPath: "/usr/bin/xcodebuild", arguments: xcodeBuildArguments) } diff --git a/Scripts/copy-ios-18-simulator.sh b/Scripts/copy-ios-18-simulator.sh new file mode 100755 index 0000000..890c3f9 --- /dev/null +++ b/Scripts/copy-ios-18-simulator.sh @@ -0,0 +1,40 @@ +#!/bin/zsh +# Copies the disk image of the iOS 18.5 simulator runtime from the +# `macos-15` runner, which has it installed, into the given directory, so +# that a job on the `xcode-27` runner can install it with +# Scripts/install-ios-18-simulator.sh. +# +# Xcode 27 can't download the runtime itself: +# `xcodebuild -downloadPlatform iOS -buildVersion 22F77` fails with +# "iOS 22F77 is not available for download". Xcode 26 on `macos-15` can +# export the installed runtime with +# `xcodebuild -downloadPlatform iOS -buildVersion 22F77 -exportPath`, but +# that fails at random with "Unable to connect to simulator.", so this +# script copies the disk image that is already on the runner instead. +# +# Usage: copy-ios-18-simulator.sh directory + +set -euo pipefail + +# The build of iOS 18.5. Scripts/build.swift tests on iOS 18.5. +build=22F77 +directory=$1 + +runtimes=$(xcrun simctl runtime list -j) +# simctl lists each runtime's disk image under "path". +image=$(print -r -- "$runtimes" | python3 -c ' +import json, sys +build = sys.argv[1] +runtimes = json.load(sys.stdin).values() +print(next((runtime["path"] for runtime in runtimes if runtime.get("build") == build and runtime.get("path")), "")) +' $build) + +if [[ -z $image ]]; then + print -r -- "$runtimes" + echo "::error::The runner has no disk image of the iOS $build simulator runtime." + exit 1 +fi + +mkdir -p $directory +cp $image $directory/iphonesimulator_18.5_$build.dmg +ls -la $directory diff --git a/Scripts/install-ios-18-simulator.sh b/Scripts/install-ios-18-simulator.sh new file mode 100755 index 0000000..7a81073 --- /dev/null +++ b/Scripts/install-ios-18-simulator.sh @@ -0,0 +1,80 @@ +#!/bin/zsh +# Installs the iOS 18.5 simulator runtime from the disk image that +# Scripts/copy-ios-18-simulator.sh copied, and creates the iPad that +# Scripts/build.swift's iOS18 platform tests on. Run it on the `xcode-27` +# runner with Xcode 27.2 selected. +# +# Usage: install-ios-18-simulator.sh image + +set -euo pipefail + +image=$1 +if [[ ! -f $image ]]; then + echo "::error::The iOS 18.5 simulator image $image doesn't exist." + exit 1 +fi +uuid_pattern='[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}' + +echo "::group::Free disk space" +# The runner's simulator runtimes take up so much of its disk that +# adding the 9 GB iOS 18.5 image fails with "Cannot copy the image +# because the disk is almost full". Delete every runtime except the 27.2 +# runtime of each platform, and also the second iOS 27.2 runtime, build +# 24B91016s, which is for iPhone only. A runtime that can't be deleted +# only frees less space; adding the image below fails if it isn't +# enough. +df -h / +runtimes=$(xcrun simctl runtime list) +print -r -- "$runtimes" +unused_runtimes=(${(f)"$( + { + grep -v ' 27\.2 (' <<<"$runtimes" + grep '24B91016s' <<<"$runtimes" + } | grep -oE $uuid_pattern || true +)"}) +for runtime in $unused_runtimes; do + sudo xcrun simctl runtime delete $runtime || true +done +# `simctl runtime delete` returns while the runtime is still being +# deleted, and its space is free only once it is gone. +for attempt in {1..60}; do + if [[ $(xcrun simctl runtime list) != *Deleting* ]]; then + break + fi + sleep 5 +done +if [[ $(xcrun simctl runtime list) == *Deleting* ]]; then + echo "::warning::Some simulator runtimes are still being deleted after 5 minutes, so adding the iOS 18.5 image may run out of disk space." +fi +xcrun simctl runtime list +df -h / +echo "::endgroup::" + +echo "::group::Add the iOS 18.5 runtime" +sudo xcodebuild -runFirstLaunch +# If `xcodebuild -importPlatform` doesn't add the runtime, add it with +# simctl instead. +sudo xcodebuild -importPlatform $image || true +if [[ $(xcrun simctl list runtimes) != *'iOS 18.'* ]]; then + if ! sudo xcrun simctl runtime add $image; then + echo "::endgroup::" + echo "::error::Neither xcodebuild -importPlatform nor simctl runtime add could add $image." + exit 1 + fi +fi +# Build the runtime's dyld shared cache now rather than during the +# simulator's first boot. +sudo xcrun simctl runtime dyld_shared_cache update --all || true +xcrun simctl list runtimes +echo "::endgroup::" + +runtime=$(xcrun simctl list runtimes | grep -oE 'com\.apple\.CoreSimulator\.SimRuntime\.iOS-18-[0-9-]+' | tail -1 || true) +if [[ -z $runtime ]]; then + echo "::error::Xcode does not list an iOS 18 simulator runtime after adding $image." + exit 1 +fi +# Scripts/build.swift finds the iPad by its name and iOS version. +if [[ $(xcrun simctl list devices 'iOS 18.5') != *'iPad (10th generation) ('* ]]; then + xcrun simctl create 'iPad (10th generation)' com.apple.CoreSimulator.SimDeviceType.iPad-10th-generation $runtime +fi +xcrun simctl list devices 'iOS 18.5' diff --git a/Sources/AsyncQueue/ActorQueue.swift b/Sources/AsyncQueue/ActorQueue.swift index 9d882ef..57ccb07 100644 --- a/Sources/AsyncQueue/ActorQueue.swift +++ b/Sources/AsyncQueue/ActorQueue.swift @@ -20,12 +20,12 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -/// A queue that enables enqueuing ordered asynchronous tasks from a nonisolated context onto an adopted actor's isolated context. -/// Tasks are guaranteed to begin executing in the order in which they are enqueued. However, if a task suspends it will allow subsequently enqueued tasks to begin executing. -/// This queue exhibits the execution behavior of an actor: tasks sent to this queue can re-enter the queue, and tasks may execute in non-FIFO order when a task suspends. +/// A queue that runs tasks on an actor and starts them in the order you enqueue them. +/// You can enqueue tasks from synchronous or `nonisolated` code. +/// Once a task starts, it behaves like any other code on the actor: when it suspends at an `await`, the next task can start, +/// and it can enqueue another task on the same queue and await its value. /// -/// An `ActorQueue` ensures tasks sent from a nonisolated context to a single actor's isolated context begin execution in order. -/// Here is an example of how an `ActorQueue` should be utilized within an actor: +/// Each `ActorQueue` belongs to one actor. Here is an example of how to use an `ActorQueue` within an actor: /// ```swift /// public actor LogStore { /// @@ -49,47 +49,57 @@ /// } /// ``` /// -/// - Warning: The `ActorQueue`'s conformance to `@unchecked Sendable` is safe if and only if `adoptExecutionContext(of:)` is called only from the adopted actor's `init` method. -/// - Precondition: The lifecycle of an `ActorQueue` must not exceed that of the adopted actor. +/// - Warning: The `ActorQueue`'s conformance to `@unchecked Sendable` is safe if and only if `adoptExecutionContext(of:)` is called only from the `init` method of the actor you pass to it. +/// - Precondition: An `ActorQueue` must not outlive the actor you pass to `adoptExecutionContext(of:)`. public final class ActorQueue: @unchecked Sendable { // MARK: Initialization - /// Instantiates an actor queue. - /// - Parameter name: Human readable name of the queue. - public init(name: String? = nil) { - let (taskStream, taskStreamContinuation) = AsyncStream.makeStream() - self.taskStreamContinuation = taskStreamContinuation - - Task(name: name) { - // In an ideal world, we would isolate this `for await` loop to the `ActorType`. - // However, there's no good way to do that without retaining the actor and creating a cycle. - for await actorTask in taskStream { - // Await switching to the ActorType context. - await actorTask.task(actorTask.executionContext) - } - } - } - - deinit { - taskStreamContinuation.finish() + /// Creates an actor queue. + /// - Parameter priority: The lowest priority at which the queue's tasks run. + /// A task that would run at a lower priority runs at this priority instead. + /// Pass `nil` to run each task at the priority you pass to `Task(on:)`, + /// or, if you pass `nil` there too, at the priority of the code that enqueues it. + public init(priority: TaskPriority? = nil) { + minimumPriority = MinimumPriority(priority) } // MARK: Public - /// Sets the actor context within which each `enqueue` and `enqueueAndWait`ed task will execute. - /// It is recommended that this method be called in the adopted actor’s `init` method. - /// **Must be called prior to enqueuing any work on the receiver.** + /// Sets the actor on which this queue runs its tasks. + /// Call this method once, in that actor's `init`, before you enqueue any task on this queue. /// - /// - Parameter actor: The actor on which the queue's task will execute. This parameter is not retained by the receiver. - /// - Warning: Calling this method more than once will result in an assertion failure. + /// - Parameter actor: The actor on which this queue runs its tasks. + /// This queue doesn't retain the actor, but each enqueued task retains it until the task finishes. + /// - Warning: Calling this method more than once causes an assertion failure. public func adoptExecutionContext(of actor: ActorType) { assert(weakExecutionContext == nil) // Adopting multiple executionContexts on the same queue is API abuse. weakExecutionContext = actor } - // MARK: Fileprivate + /// Whether every task you enqueued on this queue has started running on the actor. + /// + /// A task counts from the moment you enqueue it until it starts running on the actor. + /// So this property can be `true` while the operations of its tasks haven't finished. + /// A task runs alongside the code that enqueues it, so the task might start running on the actor before that code reads this property. + /// If that code is running on the actor, though, the task can't start running there until the code suspends or returns. + /// + /// The value can change as soon as you read it: a task you enqueue afterward makes it `false` again. + /// If one actor enqueues every task on the queue, that actor can read this property and then remove the queue + /// without suspending between the read and the removal. + /// No task can be enqueued in between, so every task enqueued on the removed queue has started running on the queue's actor. + public var hasStartedAllWork: Bool { + turns.isIdle + } - fileprivate let taskStreamContinuation: AsyncStream.Continuation + // MARK: Internal + + /// Hands out turns to begin executing on the adopted actor, in the order in which tasks are enqueued. + let turns = Turns() + + /// The priority that the queue gives each of its tasks at least. + let minimumPriority: MinimumPriority + + // MARK: Fileprivate /// The actor on whose isolated context our tasks run, force-unwrapped. /// Utilize this accessor to retrieve the weak execution context in order to avoid repeating the below comment. @@ -100,19 +110,6 @@ public final class ActorQueue: @unchecked Sendable { weakExecutionContext! } - fileprivate struct ActorTask: Sendable { - init( - executionContext: ActorType, - task: @escaping @Sendable (isolated ActorType) async -> Void, - ) { - self.executionContext = executionContext - self.task = task - } - - let executionContext: ActorType - let task: @Sendable (isolated ActorType) async -> Void - } - // MARK: Private /// The actor on whose isolated context our tasks run. @@ -126,29 +123,33 @@ public final class ActorQueue: @unchecked Sendable { extension Task { /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. + /// as part of a new unstructured task isolated to the queue's actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. - /// - priority: The priority of the operation task. + /// - priority: The priority of the task. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -158,54 +159,43 @@ extension Task { on actorQueue: ActorQueue, operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { - let delivery = Delivery() - let semaphore = Semaphore() - let task = ActorQueue.ActorTask( - executionContext: actorQueue.executionContext, - task: { executionContext in - await semaphore.wait() - delivery.execute({ @Sendable executionContext in - await delivery.sendValue(operation(executionContext)) - }, in: executionContext, name: name, priority: priority) - }, - ) - actorQueue.taskStreamContinuation.yield(task) - self.init(name: name, priority: priority) { - await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let executionContext = actorQueue.executionContext + let turn = actorQueue.turns.reserve() + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { + await turn.begin() + return await execute(operation, on: executionContext, endingTurn: turn) } + turn.register(self) } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. + /// as part of a new unstructured task isolated to the queue's actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -215,58 +205,43 @@ extension Task { on actorQueue: ActorQueue, operation: @escaping @Sendable (isolated ActorType) async throws -> Success, ) where Failure == any Error { - let delivery = Delivery() - let semaphore = Semaphore() - let task = ActorQueue.ActorTask( - executionContext: actorQueue.executionContext, - task: { executionContext in - await semaphore.wait() - delivery.execute({ @Sendable executionContext in - do { - try await delivery.sendValue(operation(executionContext)) - } catch { - await delivery.sendFailure(error) - } - }, in: executionContext, name: name, priority: priority) - }, - ) - actorQueue.taskStreamContinuation.yield(task) - self.init(name: name, priority: priority) { - try await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return try await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let executionContext = actorQueue.executionContext + let turn = actorQueue.turns.reserve() + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { + await turn.begin() + return try await execute(operation, on: executionContext, endingTurn: turn) } + turn.register(self) } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. + /// as part of a new unstructured task isolated to the main actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -276,54 +251,53 @@ extension Task { on actorQueue: ActorQueue, operation: @MainActor @escaping () async -> Success, ) where Failure == Never { - let delivery = Delivery() - let semaphore = Semaphore() - let task = ActorQueue.ActorTask( - executionContext: actorQueue.executionContext, - task: { executionContext in - await semaphore.wait() - delivery.execute({ @Sendable executionContext in - await delivery.sendValue(operation()) - }, in: executionContext, name: name, priority: priority) - }, - ) - actorQueue.taskStreamContinuation.yield(task) - self.init(name: name, priority: priority) { - await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let turn = actorQueue.turns.reserve() + let taskPriority = actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority) + if turn.wasCurrentWhenReserved { + // The task's turn begins without waiting, so start the task on the main actor rather than hop there. + self.init(name: name, priority: taskPriority) { @MainActor in + await turn.begin() + return await executeOnMainActor(operation, endingTurn: turn) + } + } else { + // A task that waits for its turn resumes on the global concurrent executor whichever executor it waits on, + // so wait there rather than take an extra turn on the main actor. + self.init(name: name, priority: taskPriority) { + await turn.begin() + return await executeOnMainActor(operation, endingTurn: turn) + } } + turn.register(self) } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. + /// as part of a new unstructured task isolated to the main actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -333,36 +307,60 @@ extension Task { on actorQueue: ActorQueue, operation: @escaping @MainActor () async throws -> Success, ) where Failure == any Error { - let delivery = Delivery() - let semaphore = Semaphore() - let task = ActorQueue.ActorTask( - executionContext: actorQueue.executionContext, - task: { executionContext in - await semaphore.wait() - delivery.execute({ @Sendable executionContext in - do { - try await delivery.sendValue(operation()) - } catch { - await delivery.sendFailure(error) - } - }, in: executionContext, name: name, priority: priority) - }, - ) - actorQueue.taskStreamContinuation.yield(task) - self.init(name: name, priority: priority) { - try await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return try await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let turn = actorQueue.turns.reserve() + let taskPriority = actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority) + if turn.wasCurrentWhenReserved { + // The task's turn begins without waiting, so start the task on the main actor rather than hop there. + self.init(name: name, priority: taskPriority) { @MainActor in + await turn.begin() + return try await executeOnMainActor(operation, endingTurn: turn) + } + } else { + // A task that waits for its turn resumes on the global concurrent executor whichever executor it waits on, + // so wait there rather than take an extra turn on the main actor. + self.init(name: name, priority: taskPriority) { + await turn.begin() + return try await executeOnMainActor(operation, endingTurn: turn) + } } + turn.register(self) } } +// MARK: - Execution + +/// Executes `operation` on `actor`, ending `turn` as soon as the task is isolated to `actor`. +/// +/// Ending the turn lets the next enqueued task hop to `actor`. That task cannot execute on `actor` +/// until `operation` suspends or returns, so tasks begin executing in the order in which they were enqueued. +private func execute( + _ operation: (isolated ActorType) async throws -> Success, + on actor: isolated ActorType, + endingTurn turn: Turn, +) async rethrows -> Success { + turn.end() + return try await operation(actor) +} + +/// Executes `operation` on the main actor, ending `turn` as soon as the task is isolated to the main actor. +/// +/// Ending the turn lets the next enqueued task hop to the main actor. That task cannot execute on the main actor +/// until `operation` suspends or returns, so tasks begin executing in the order in which they were enqueued. +@MainActor +private func executeOnMainActor( + _ operation: @MainActor () async throws -> Success, + endingTurn turn: Turn, +) async rethrows -> Success { + turn.end() + return try await operation() +} + extension MainActor { /// A global instance of an `ActorQueue`. + /// + /// This queue has no priority of its own: each task runs at the priority you pass to `Task(on:)`, + /// or, if you pass `nil`, at the priority of the code that enqueues it. + /// Pass a `priority` to `Task(on:)` when you enqueue important work from low-priority code. public static var queue: ActorQueue { mainActorQueue } diff --git a/Sources/AsyncQueue/CancellableQueue.swift b/Sources/AsyncQueue/CancellableQueue.swift index 23ca121..b317ab8 100644 --- a/Sources/AsyncQueue/CancellableQueue.swift +++ b/Sources/AsyncQueue/CancellableQueue.swift @@ -25,32 +25,39 @@ #else import Foundation #endif -#if canImport(Dispatch) - import Dispatch -#endif +import Synchronization -/// A queue wrapper that enables cancelling all currently executing and pending tasks. -/// -/// A `CancellableQueue` wraps either a `FIFOQueue` or an `ActorQueue` and tracks all tasks enqueued on it. +/// A queue that wraps a `FIFOQueue` or an `ActorQueue` and lets you cancel all of its unfinished tasks at once. public final class CancellableQueue: Sendable { // MARK: Initialization - /// Instantiates a cancellable queue. - /// - Parameter underlyingQueue: The queue whose work can be cancelled. + /// Creates a cancellable queue. + /// - Parameter underlyingQueue: The `FIFOQueue` or `ActorQueue` to wrap. public init(underlyingQueue: UnderlyingQueue) { self.underlyingQueue = underlyingQueue } // MARK: Public - /// Cancels currently executing and pending tasks. Does not affect tasks enqueued after this method is called. + /// Cancels every unfinished task that you enqueued on this queue, whether it's running or waiting. + /// Tasks that you enqueue afterward aren't affected. + /// + /// If another thread is still enqueuing a task when you call this method, the task is cancelled as soon as it's enqueued. /// /// If another call to this method is in progress, this call may return before the other call finishes cancelling the tasks it found. public func cancelTasks() { - let cancellations = taskIdentifierToCancelMap.withLock { - let cancellations = $0.values.compactMap(\.self) - // Keep reservations so that tasks that have not yet registered remain cancellable. - $0 = $0.filter { $0.value == nil } + let cancellations = taskIdentifierToState.withLock { taskIdentifierToState in + var cancellations = [@Sendable () -> Void]() + taskIdentifierToState = taskIdentifierToState.compactMapValues { state in + switch state { + case let .registered(cancel): + cancellations.append(cancel) + return nil + case .reserved, .cancellationRequested: + // The task has not registered its `cancel` closure yet, so cancel it once it does. + return .cancellationRequested + } + } return cancellations } // Cancelling a task synchronously runs its cancellation handlers, which may call back into this queue. @@ -66,56 +73,106 @@ public final class CancellableQueue: Sendable { /// Reserving before the task starts ensures the task's removal of the identifier can never be processed before the reservation. func reserveTaskIdentifier() -> UUID { let identifier = UUID() - taskIdentifierToCancelMap.writeAsync { - $0.updateValue(nil, forKey: identifier) + taskIdentifierToState.withLock { + $0[identifier] = .reserved } return identifier } /// Registers the `cancel` closure for a task whose identifier was previously reserved. + /// Cancels the task if `cancelTasks()` was called after the identifier was reserved. func registerCancellation(forTaskWithIdentifier identifier: UUID, _ cancel: @escaping @Sendable () -> Void) { - taskIdentifierToCancelMap.writeAsync { - // Skip registration if the identifier was already removed because the task already finished. - if $0.keys.contains(identifier) { - $0[identifier] = cancel + let isCancellationRequested = taskIdentifierToState.withLock { taskIdentifierToState in + switch taskIdentifierToState[identifier] { + case .reserved: + taskIdentifierToState[identifier] = .registered(cancel) + return false + case .cancellationRequested: + taskIdentifierToState[identifier] = nil + return true + case .registered, nil: + // The task already finished, so there is nothing to cancel. + return false } } + if isCancellationRequested { + // Cancel only after releasing the lock. See `cancelTasks()`. + cancel() + } } /// Removes the identifier of a task that has finished executing. func taskDidFinish(withIdentifier identifier: UUID) { - taskIdentifierToCancelMap.writeAsync { + taskIdentifierToState.withLock { $0[identifier] = nil } } + /// Tracks the task that `createTask` creates to perform `operation`, so that `cancelTasks()` can cancel it. + /// Reserves the task's identifier before the task is created and registers its `cancel` closure afterward, + /// so that the task may finish, or `cancelTasks()` may be called, while it is being created. + /// + /// Always inlined: without `@inline(__always)`, the generic call is not inlined, and enqueuing a task on a + /// `CancellableQueue` measured about 11% slower. + @inline(__always) + func trackTask( + performing operation: sending Operation, + createdBy createTask: (_ identifier: UUID, _ operation: sending Operation) -> Task, + ) -> Task { + let identifier = reserveTaskIdentifier() + let task = createTask(identifier, operation) + registerCancellation(forTaskWithIdentifier: identifier, task.cancel) + return task + } + // MARK: Fileprivate fileprivate let underlyingQueue: UnderlyingQueue - fileprivate let taskIdentifierToCancelMap = Lock<[UUID: (@Sendable () -> Void)?]>(value: [:]) + /// The state of each enqueued task that has not finished executing. + /// Never cancel a task while holding this lock: cancellation handlers run synchronously and may call back into this queue. + fileprivate let taskIdentifierToState = Mutex<[UUID: TaskState]>([:]) + + fileprivate enum TaskState: Sendable { + /// The task is being enqueued, and has not registered its `cancel` closure yet. + case reserved + /// `cancelTasks()` was called before the task registered its `cancel` closure, so the task is cancelled when it registers. + case cancellationRequested + /// The task registered its `cancel` closure. + case registered(@Sendable () -> Void) + } } extension Task { /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the queue's actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -125,35 +182,45 @@ extension Task { on actorQueue: CancellableQueue>, operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { - let identifier = actorQueue.reserveTaskIdentifier() - self.init(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { - defer { - actorQueue.taskDidFinish(withIdentifier: identifier) - } - return await operation($0) - }) - actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) + self = actorQueue.trackTask(performing: operation) { identifier, operation in + Task(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { + defer { + actorQueue.taskDidFinish(withIdentifier: identifier) + } + return await operation($0) + }) + } } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the queue's actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -163,35 +230,45 @@ extension Task { on actorQueue: CancellableQueue>, operation: @escaping @Sendable (isolated ActorType) async throws -> Success, ) where Failure == any Error { - let identifier = actorQueue.reserveTaskIdentifier() - self.init(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { - defer { - actorQueue.taskDidFinish(withIdentifier: identifier) - } - return try await operation($0) - }) - actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) + self = actorQueue.trackTask(performing: operation) { identifier, operation in + Task(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { + defer { + actorQueue.taskDidFinish(withIdentifier: identifier) + } + return try await operation($0) + }) + } } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the main actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -201,35 +278,45 @@ extension Task { on actorQueue: CancellableQueue>, operation: @MainActor @escaping () async -> Success, ) where Failure == Never { - let identifier = actorQueue.reserveTaskIdentifier() - self.init(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { - defer { - actorQueue.taskDidFinish(withIdentifier: identifier) - } - return await operation() - }) - actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) + self = actorQueue.trackTask(performing: operation) { identifier, operation in + Task(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { + defer { + actorQueue.taskDidFinish(withIdentifier: identifier) + } + return await operation() + }) + } } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task on behalf of the current actor. - /// The operation will not execute until all prior tasks have - /// completed or suspended. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the main actor. + /// The operation doesn't run until every task enqueued before it has finished or suspended. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished or suspended. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -239,105 +326,164 @@ extension Task { on actorQueue: CancellableQueue>, operation: @escaping @MainActor () async throws -> Success, ) where Failure == any Error { - let identifier = actorQueue.reserveTaskIdentifier() - self.init(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { - defer { - actorQueue.taskDidFinish(withIdentifier: identifier) - } - return try await operation() - }) - actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) + self = actorQueue.trackTask(performing: operation) { identifier, operation in + Task(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { + defer { + actorQueue.taskDidFinish(withIdentifier: identifier) + } + return try await operation() + }) + } } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task that inherits the current isolated context. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task that runs with the same actor isolation as the code that enqueues it. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. + /// - priority: The priority of the task. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - fifoQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult public init( name: String? = nil, + priority: TaskPriority? = nil, on fifoQueue: CancellableQueue, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success, ) where Failure == Never { - let identifier = fifoQueue.reserveTaskIdentifier() - self.init(name: name, on: fifoQueue.underlyingQueue, operation: { - defer { - fifoQueue.taskDidFinish(withIdentifier: identifier) + self = fifoQueue.trackTask(performing: operation) { identifier, operation in + if isolation(of: operation) === MainActor.shared { + // Isolate this wrapper to the main actor too, so that the underlying queue can start and end the task there. + Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: { @MainActor in + defer { + fifoQueue.taskDidFinish(withIdentifier: identifier) + } + return await operation() + }) + } else { + Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: { + defer { + fifoQueue.taskDidFinish(withIdentifier: identifier) + } + return await operation() + }) } - return await operation() - }) - fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) + } } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task that inherits the current isolated context. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task that runs with the same actor isolation as the code that enqueues it. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. + /// - priority: The priority of the task. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - fifoQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult public init( name: String? = nil, + priority: TaskPriority? = nil, on fifoQueue: CancellableQueue, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success, ) where Failure == any Error { - let identifier = fifoQueue.reserveTaskIdentifier() - self.init(name: name, on: fifoQueue.underlyingQueue, operation: { - defer { - fifoQueue.taskDidFinish(withIdentifier: identifier) + self = fifoQueue.trackTask(performing: operation) { identifier, operation in + if isolation(of: operation) === MainActor.shared { + // Isolate this wrapper to the main actor too, so that the underlying queue can start and end the task there. + Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: { @MainActor in + defer { + fifoQueue.taskDidFinish(withIdentifier: identifier) + } + return try await operation() + }) + } else { + Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, operation: { + defer { + fifoQueue.taskDidFinish(withIdentifier: identifier) + } + return try await operation() + }) } - return try await operation() - }) - fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) + } } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task isolated to the given actor. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the given actor. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - fifoQueue: The queue on which to enqueue the task. /// - isolatedActor: The actor to which the operation is isolated. /// - operation: The operation to perform. @@ -349,35 +495,46 @@ extension Task { isolatedTo isolatedActor: ActorType, operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { - let identifier = fifoQueue.reserveTaskIdentifier() - self.init(name: name, priority: priority, on: fifoQueue.underlyingQueue, isolatedTo: isolatedActor, operation: { - defer { - fifoQueue.taskDidFinish(withIdentifier: identifier) - } - return await operation($0) - }) - fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) + self = fifoQueue.trackTask(performing: operation) { identifier, operation in + Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, isolatedTo: isolatedActor, operation: { + defer { + fifoQueue.taskDidFinish(withIdentifier: identifier) + } + return await operation($0) + }) + } } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task isolated to the given actor. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. - /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// as part of a new unstructured task isolated to the given actor. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. + /// Calling the queue's `cancelTasks()` method cancels the task if it hasn't finished. + /// + /// You need to keep a reference to the task + /// if you want to cancel it by calling the `Task.cancel()` method. + /// Discarding your reference to a task + /// doesn't implicitly cancel that task, + /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - fifoQueue: The queue on which to enqueue the task. /// - isolatedActor: The actor to which the operation is isolated. /// - operation: The operation to perform. @@ -389,45 +546,13 @@ extension Task { isolatedTo isolatedActor: ActorType, operation: @Sendable @escaping (isolated ActorType) async throws -> Success, ) where Failure == any Error { - let identifier = fifoQueue.reserveTaskIdentifier() - self.init(name: name, priority: priority, on: fifoQueue.underlyingQueue, isolatedTo: isolatedActor, operation: { - defer { - fifoQueue.taskDidFinish(withIdentifier: identifier) - } - return try await operation($0) - }) - fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) - } -} - -// MARK: - Lock - -private final class Lock: @unchecked Sendable { - // MARK: Initialization - - init(value: State) { - unsafeValue = value - } - - // MARK: Fileprivate - - /// Executes `body` while holding the lock. - /// - Warning: `body` must not cancel a task, resume a continuation, or otherwise call out to code that may re-enter this lock. - fileprivate func withLock(_ body: @Sendable (inout State) throws -> R) rethrows -> R { - try lockQueue.sync { - try body(&unsafeValue) - } - } - - fileprivate func writeAsync(_ body: @Sendable @escaping (inout State) -> Void) { - lockQueue.async { - body(&self.unsafeValue) + self = fifoQueue.trackTask(performing: operation) { identifier, operation in + Task(name: name, priority: priority, on: fifoQueue.underlyingQueue, isolatedTo: isolatedActor, operation: { + defer { + fifoQueue.taskDidFinish(withIdentifier: identifier) + } + return try await operation($0) + }) } } - - // MARK: Private - - private var unsafeValue: State - - private let lockQueue = DispatchQueue(label: "ReadWriteLock.Queue", target: DispatchQueue.global()) } diff --git a/Sources/AsyncQueue/FIFOQueue.swift b/Sources/AsyncQueue/FIFOQueue.swift index b22f37a..8159041 100644 --- a/Sources/AsyncQueue/FIFOQueue.swift +++ b/Sources/AsyncQueue/FIFOQueue.swift @@ -20,68 +20,116 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -/// A queue that executes asynchronous tasks enqueued from a nonisolated context in FIFO order. -/// Tasks are guaranteed to begin _and end_ executing in the order in which they are enqueued. -/// Asynchronous tasks sent to this queue work as they would in a `DispatchQueue` type. Attempting to `enqueueAndWait` this queue from a task executing on this queue will result in a deadlock. +/// A queue that runs one task at a time, in the order you enqueue them: first in, first out. +/// You can enqueue tasks from synchronous or `nonisolated` code. +/// Each task waits until every task enqueued before it has finished, so tasks start and finish in the order you enqueue them. +/// A task that is suspended at an `await` hasn't finished. +/// Inside a task on this queue, don't await another task that you enqueue on the same queue: +/// each task waits for the other, so both wait forever. public final class FIFOQueue: Sendable { // MARK: Initialization - /// Instantiates a FIFO queue. - /// - Parameter name: Human readable name of the queue. - /// - Parameter priority: The baseline priority of the tasks added to the asynchronous queue. - public init(name: String? = nil, priority: TaskPriority? = nil) { - let (taskStream, taskStreamContinuation) = AsyncStream.makeStream() - self.taskStreamContinuation = taskStreamContinuation + /// Creates a FIFO queue. + /// - Parameter priority: The lowest priority at which the queue's tasks run. + /// A task that would run at a lower priority runs at this priority instead. + /// Pass `nil` to run each task at the priority you pass to `Task(on:)`, + /// or, if you pass `nil` there too, at the priority of the code that enqueues it. + public init(priority: TaskPriority? = nil) { + minimumPriority = MinimumPriority(priority) + turns = Turns() + } - Task.detached(name: name, priority: priority) { - for await fifoTask in taskStream { - await fifoTask.task() - } + #if DEBUG + /// Creates a FIFO queue that hands out turns from `turns`. Used by tests. + init(turns: Turns) { + minimumPriority = MinimumPriority(nil) + self.turns = turns } - } + #endif - deinit { - taskStreamContinuation.finish() - } + // MARK: Public - // MARK: Fileprivate + /// Whether every task you enqueued on this queue has finished. + /// + /// A task counts from the moment you enqueue it until its operation returns or throws. + /// A task that is suspended at an `await` hasn't finished, + /// so an operation that reads this property on its own queue always reads `false`. + /// A cancelled task hasn't finished either: it keeps its place in the queue, and its operation still runs. + /// A task runs alongside the code that enqueues it, so the task might finish before that code reads this property. + /// If the task's operation needs an actor that the code is running on, though, + /// the task can't finish until the code suspends or returns. + /// + /// The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again. + /// If one actor enqueues every task on the queue, that actor can read this property and then safely remove an idle queue, + /// without suspending between the read and the removal. + /// No task can be enqueued in between, and a task that the actor enqueues afterward on a new queue + /// runs after every task on the removed queue, because they have all finished. + /// For example, an actor that keeps one queue per document can remove the queues of documents whose work has finished: + /// + /// ```swift + /// actor DocumentStore { + /// func save(_ contents: String, as name: String) -> Task { + /// let queue = queues[name] ?? FIFOQueue() + /// queues[name] = queue + /// return Task(on: queue) { + /// await self.write(contents, as: name) + /// } + /// } + /// + /// func removeIdleQueues() { + /// queues = queues.filter { !$0.value.isIdle } + /// } + /// + /// private func write(_ contents: String, as name: String) async { + /// // Write implementation… + /// } + /// + /// private var queues = [String: FIFOQueue]() + /// } + /// ``` + public var isIdle: Bool { + turns.isIdle + } - fileprivate struct FIFOTask: Sendable { - init(task: @escaping @Sendable () async -> Void) { - self.task = task - } + // MARK: Internal - let task: @Sendable () async -> Void - } + /// Hands out turns to execute, in the order in which tasks are enqueued. + let turns: Turns - fileprivate let taskStreamContinuation: AsyncStream.Continuation + /// The priority that the queue gives each of its tasks at least. + let minimumPriority: MinimumPriority } extension Task { /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task that inherits the current isolated context. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. + /// as part of a new unstructured task that runs with the same actor isolation as the code that enqueues it. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - fifoQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -91,51 +139,65 @@ extension Task { on fifoQueue: FIFOQueue, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success, ) where Failure == Never { - let delivery = Delivery() - let semaphore = Semaphore() - let executeOnce = UnsafeClosureHolder(operation: operation) - let task = FIFOQueue.FIFOTask { - await semaphore.wait() - await delivery.execute({ @Sendable delivery in - await delivery.sendValue(executeOnce.operation()) - }, in: delivery, name: name, priority: priority).value - } - fifoQueue.taskStreamContinuation.yield(task) - self.init(name: name) { - await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let turn = fifoQueue.turns.reserve() + let taskPriority = fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority) + if isolation(of: operation) === MainActor.shared { + let operation = UncheckedSendable(operation) + if turn.wasCurrentWhenReserved { + // The task's turn begins without waiting, so start the task on the main actor rather than hop there. + self.init(name: name, priority: taskPriority) { @MainActor in + await turn.begin() + return await executeOnMainActor(operation, endingTurn: turn) + } + } else { + // A task that waits for its turn resumes on the global concurrent executor whichever executor it waits on, + // so wait there rather than take an extra turn on the main actor. + self.init(name: name, priority: taskPriority) { + await turn.begin() + return await executeOnMainActor(operation, endingTurn: turn) + } + } + } else { + // A task can switch from the global concurrent executor to an idle actor, and back, without enqueuing a job, + // so a task whose operation is isolated to any other actor gains nothing from starting or ending there. + self.init(name: name, priority: taskPriority) { + await turn.begin() + defer { turn.end() } + return await operation() + } } + turn.register(self) } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task that inherits the current isolated context. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. + /// as part of a new unstructured task that runs with the same actor isolation as the code that enqueues it. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. + /// + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - fifoQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -145,56 +207,65 @@ extension Task { on fifoQueue: FIFOQueue, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success, ) where Failure == any Error { - let delivery = Delivery() - let semaphore = Semaphore() - let executeOnce = UnsafeThrowingClosureHolder(operation: operation) - let task = FIFOQueue.FIFOTask { - await semaphore.wait() - await delivery.execute({ @Sendable delivery in - do { - try await delivery.sendValue(executeOnce.operation()) - } catch { - delivery.sendFailure(error) + let turn = fifoQueue.turns.reserve() + let taskPriority = fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority) + if isolation(of: operation) === MainActor.shared { + let operation = UncheckedSendable(operation) + if turn.wasCurrentWhenReserved { + // The task's turn begins without waiting, so start the task on the main actor rather than hop there. + self.init(name: name, priority: taskPriority) { @MainActor in + await turn.begin() + return try await executeOnMainActor(operation, endingTurn: turn) } - }, in: delivery, name: name, priority: priority).value - } - fifoQueue.taskStreamContinuation.yield(task) - self.init(name: name) { - try await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return try await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + } else { + // A task that waits for its turn resumes on the global concurrent executor whichever executor it waits on, + // so wait there rather than take an extra turn on the main actor. + self.init(name: name, priority: taskPriority) { + await turn.begin() + return try await executeOnMainActor(operation, endingTurn: turn) + } + } + } else { + // A task can switch from the global concurrent executor to an idle actor, and back, without enqueuing a job, + // so a task whose operation is isolated to any other actor gains nothing from starting or ending there. + self.init(name: name, priority: taskPriority) { + await turn.begin() + defer { turn.end() } + return try await operation() + } } + turn.register(self) } /// Runs the given nonthrowing operation asynchronously - /// as part of a new top-level task isolated to the given actor. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. + /// as part of a new unstructured task isolated to the given actor. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - fifoQueue: The queue on which to enqueue the task. /// - isolatedActor: The actor to which the operation is isolated. /// - operation: The operation to perform. @@ -206,51 +277,44 @@ extension Task { isolatedTo isolatedActor: ActorType, operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { - let delivery = Delivery() - let semaphore = Semaphore() - let task = FIFOQueue.FIFOTask { - await semaphore.wait() - await delivery.execute({ @Sendable isolatedActor in - await delivery.sendValue(operation(isolatedActor)) - }, in: isolatedActor, name: name, priority: priority).value - } - fifoQueue.taskStreamContinuation.yield(task) - self.init(name: name) { - await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let turn = fifoQueue.turns.reserve() + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { + await turn.begin() + defer { turn.end() } + return await operation(isolatedActor) } + turn.register(self) } /// Runs the given throwing operation asynchronously - /// as part of a new top-level task isolated to the given actor. - /// The operation will not execute until all prior tasks – including - /// suspended tasks – have completed. + /// as part of a new unstructured task isolated to the given actor. + /// The operation doesn't run until every task enqueued before it has finished. + /// A task that is suspended at an `await` hasn't finished. /// - /// Use this function when creating asynchronous work - /// that operates on behalf of the synchronous function that calls it. - /// Like `Task.detached(priority:operation:)`, - /// this function creates a separate, top-level task. - /// Unlike `Task.detached(priority:operation:)`, - /// the task created by `Task.init(priority:operation:)` - /// inherits the priority and actor context of the caller, - /// so the operation is treated more like an asynchronous extension - /// to the synchronous operation. + /// Like a task created with `Task.init(name:priority:operation:)`, the task inherits the task-local values + /// and, unless you pass a `priority`, the priority of the code that enqueues it. + /// When a higher-priority task awaits the task's value, Swift escalates the task's priority. + /// On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, + /// a task that waits on the queue also escalates the tasks ahead of it to its own priority. + /// On earlier releases, the tasks ahead keep their own priority. + /// An escalated task keeps that priority until it finishes. + /// + /// Cancelling the task doesn't remove it from the queue: the operation still runs, + /// after every task enqueued before it has finished. + /// Check `Task.isCancelled` or call `Task.checkCancellation()` within the operation to stop early. /// /// You need to keep a reference to the task /// if you want to cancel it by calling the `Task.cancel()` method. - /// Discarding your reference to a detached task + /// Discarding your reference to a task /// doesn't implicitly cancel that task, /// it only makes it impossible for you to explicitly cancel the task. /// /// - Parameters: /// - name: Human readable name of the task. /// - priority: The priority of the task. - /// Pass `nil` to use the priority from `Task.currentPriority`. + /// Pass `nil` to inherit the priority of the code that enqueues the task, + /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - fifoQueue: The queue on which to enqueue the task. /// - isolatedActor: The actor to which the operation is isolated. /// - operation: The operation to perform. @@ -262,43 +326,60 @@ extension Task { isolatedTo isolatedActor: ActorType, operation: @Sendable @escaping (isolated ActorType) async throws -> Success, ) where Failure == any Error { - let delivery = Delivery() - let semaphore = Semaphore() - let task = FIFOQueue.FIFOTask { - await semaphore.wait() - await delivery.execute({ @Sendable isolatedActor in - do { - try await delivery.sendValue(operation(isolatedActor)) - } catch { - await delivery.sendFailure(error) - } - }, in: isolatedActor, name: name, priority: priority).value - } - fifoQueue.taskStreamContinuation.yield(task) - self.init(name: name, priority: priority) { - try await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return try await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let turn = fifoQueue.turns.reserve() + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { + await turn.begin() + defer { turn.end() } + return try await operation(isolatedActor) } + turn.register(self) } } -private struct UnsafeClosureHolder: @unchecked Sendable { - init(operation: sending @escaping @isolated(any) () async -> Success) { - self.operation = operation - } +// MARK: - Execution + +/// The isolation of `operation`. +/// +/// Reading `isolation` directly from a `sending` parameter of an initializer in an extension of `Task` crashes the +/// Swift 6.4 compiler, so the initializers read it through this function. +func isolation(of operation: @isolated(any) () async throws -> some Any) -> (any Actor)? { + operation.isolation +} + +/// Executes `operation`, which is isolated to the main actor, and ends `turn` on the main actor once `operation` returns. +/// +/// Ending the turn on the main actor keeps the task from hopping off of the main actor before it ends its turn. +@MainActor +private func executeOnMainActor( + _ operation: UncheckedSendable<@isolated(any) () async -> Success>, + endingTurn turn: Turn, +) async -> Success { + defer { turn.end() } + return await operation.value() +} - let operation: @isolated(any) () async -> Success +/// Executes `operation`, which is isolated to the main actor, and ends `turn` on the main actor once `operation` returns +/// or throws. +/// +/// Ending the turn on the main actor keeps the task from hopping off of the main actor before it ends its turn. +@MainActor +private func executeOnMainActor( + _ operation: UncheckedSendable<@isolated(any) () async throws -> Success>, + endingTurn turn: Turn, +) async throws -> Success { + defer { turn.end() } + return try await operation.value() } -private struct UnsafeThrowingClosureHolder: @unchecked Sendable { - init(operation: sending @escaping @isolated(any) () async throws -> Success) { - self.operation = operation +/// Carries the operation that was sent to a queue's task into that task, and from there to the main actor. +/// +/// A `sending` operation belongs to its own isolation region, which the task's operation takes over. The compiler cannot +/// see that a task's operation, which runs only once, gives the operation up when it passes it to the main actor, +/// so this box asserts it. +struct UncheckedSendable: @unchecked Sendable { + init(_ value: consuming Value) { + self.value = value } - let operation: @isolated(any) () async throws -> Success + let value: Value } diff --git a/Sources/AsyncQueue/Utilities/Delivery.swift b/Sources/AsyncQueue/Utilities/Delivery.swift deleted file mode 100644 index 23e050e..0000000 --- a/Sources/AsyncQueue/Utilities/Delivery.swift +++ /dev/null @@ -1,149 +0,0 @@ -// MIT License -// -// Copyright (c) 2025 Dan Federman -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -import Dispatch - -actor Delivery { - func sendValue(_ value: Success) { - self.value = value - } - - func sendFailure(_ failure: Failure) { - self.failure = failure - } - - nonisolated func cancel() { - let task = taskContainer.withLock { - $0.isCancelled = true - return $0.task - } - // Cancelling a task synchronously runs its cancellation handlers, which may cancel other tasks. - // Cancel only after releasing the lock so that those handlers can never re-enter it. - task?.cancel() - } - - @discardableResult - func execute( - _ operation: sending @escaping (isolated ActorType) async -> Void, - in context: isolated ActorType, - name: String?, - priority: TaskPriority?, - ) -> Task { - // In Swift 6, a `Task` enqueued from an actor begins executing immediately on that actor. - // Since we're running on our actor's context already, we can just dispatch a Task to get first-enqueued-first-start task execution. - let task = Task(name: name, priority: priority) { - await operation(context) - } - let isCancelled = taskContainer.withLock { - $0.task = task - return $0.isCancelled - } - if isCancelled { - // Cancel only after releasing the lock. See `cancel()`. - task.cancel() - } - return task - } - - private var value: Success? { - didSet { - if let value { - valueContinuations.forEach { $0.resume(returning: value) } - valueContinuations.removeAll() - } - } - } - - private var failure: Failure? { - didSet { - if let failure { - valueContinuations.forEach { $0.resume(throwing: failure) } - valueContinuations.removeAll() - } - } - } - - private var valueContinuations: [UnsafeContinuation] = [] - private let taskContainer = Locked(value: TaskContainer()) - - struct TaskContainer { - var task: Task? - var isCancelled = false - } -} - -extension Delivery where Failure == Never { - func getValue() async -> Success { - if let value { - value - } else { - await withUnsafeContinuation { continuation in - valueContinuations.append(continuation) - } - } - } -} - -extension Delivery where Failure == any Error { - func getValue() async throws -> Success { - if let value { - value - } else if let failure { - throw failure - } else { - try await withUnsafeThrowingContinuation { continuation in - valueContinuations.append(continuation) - } - } - } -} - -// MARK: - Locked - -// We'd use `OSAllocatedUnfairLock` or `Mutex` but the minimum supported version is much higher than what we support. -private struct Locked: @unchecked Sendable { - init(value: State) { - container = .init(value: value) - } - - /// Executes `body` while holding the lock. - /// - Warning: `body` must not cancel a task, resume a continuation, or otherwise call out to code that may re-enter this lock. - func withLock(_ body: @Sendable (inout State) throws -> R) rethrows -> R where R: Sendable { - try container.lockQueue.sync { - var value = container.unsafeValue - let returnValue = try body(&value) - container.unsafeValue = value - return returnValue - } - } - - private let container: UnsafeContainer - - private final class UnsafeContainer: @unchecked Sendable { - init(value: State) { - unsafeValue = value - } - - var unsafeValue: State - let lockQueue = DispatchQueue(label: "Locked.lockQueue", target: DispatchQueue.global()) - } -} diff --git a/Sources/AsyncQueue/Utilities/MinimumPriority.swift b/Sources/AsyncQueue/Utilities/MinimumPriority.swift new file mode 100644 index 0000000..f192ff3 --- /dev/null +++ b/Sources/AsyncQueue/Utilities/MinimumPriority.swift @@ -0,0 +1,64 @@ +// MIT License +// +// Copyright (c) 2026 Dan Federman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +/// The priority that a queue gives each of its tasks at least. +struct MinimumPriority: Sendable { + // MARK: Initialization + + /// - Parameter priority: The lowest priority at which the queue's tasks run. + /// Pass `nil` to run each task at the priority with which it was enqueued. + init(_ priority: TaskPriority?) { + self.priority = priority + } + + // MARK: Internal + + /// Returns the priority with which to create a task that was enqueued with the given priority. + /// - Parameter taskPriority: The priority with which the task was enqueued. `nil` means the priority of the enqueuing context. + func priority(forTaskEnqueuedWith taskPriority: TaskPriority?) -> TaskPriority? { + if let priority, Self.priorityOfNewTask(enqueuedWith: taskPriority) < priority { + priority + } else { + // Keep the enqueued priority when it suffices, so that `Task` determines the task's priority itself. + taskPriority + } + } + + // MARK: Private + + private let priority: TaskPriority? + + /// Returns the priority that `Task.init(priority:)` gives a task created in the current context with the given priority. + private static func priorityOfNewTask(enqueuedWith taskPriority: TaskPriority?) -> TaskPriority { + // `Task` treats a priority with a raw value of zero as no priority. + if let taskPriority, taskPriority.rawValue != 0 { + return taskPriority + } else { + // Within a task, a new task inherits the task's base priority, not its escalated priority. + // Outside of a task, a new task takes the current thread's priority, or `.medium` if the thread has none. + let inheritedPriority = Task.basePriority ?? Task.currentPriority + guard inheritedPriority.rawValue != 0 else { return .medium } + // `Task` lowers an inherited user-interactive priority to user-initiated, which is `.high`. + return min(inheritedPriority, .high) + } + } +} diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift new file mode 100644 index 0000000..3c5d439 --- /dev/null +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -0,0 +1,319 @@ +// MIT License +// +// Copyright (c) 2026 Dan Federman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import Synchronization + +/// Hands out turns in the order in which they are reserved. +/// +/// Each turn begins once every turn reserved before it has ended. +/// +/// Where the runtime supports priority escalation, a task waiting for its turn escalates the task holding the current turn +/// to the waiting task's priority, so that a high-priority task does not wait on a low-priority task indefinitely. +/// The current turn is held by the earliest turn that has not ended, whether or not its task has started running. +/// When a turn ends, the next turn's task is escalated to the highest priority of the tasks still waiting before it is resumed. +/// Escalation therefore never walks the queue, however many tasks are waiting. +final class Turns: Sendable { + // MARK: Initialization + + /// - Parameter escalatesPriority: Whether waiting tasks escalate the task holding the current turn. + /// Tests pass `false` to exercise the behavior of runtimes that cannot escalate another task. + init(escalatesPriority: Bool = true) { + self.escalatesPriority = escalatesPriority + #if DEBUG + didEndTurn = nil + #endif + } + + #if DEBUG + /// Creates turns that call `didEndTurn` each time a turn ends, from the code that ends it. + /// + /// Tests use this to check where a queue's task ends its turn. This initializer exists only in debug builds, + /// so release builds pay nothing for it. + /// - Parameter didEndTurn: Called each time a turn ends, after the turn has ended. + init(didEndTurn: @escaping @Sendable () -> Void) { + escalatesPriority = true + self.didEndTurn = didEndTurn + } + #endif + + // MARK: Internal + + /// Reserves the next turn. + func reserve() -> Turn { + let ticket = Ticket() + let (previousTicket, isCurrent) = state.withLock { state -> (Ticket?, Bool) in + defer { state.lastTicket = ticket } + if let lastTicket = state.lastTicket, !lastTicket.hasEnded { + lastTicket.next = ticket + return (lastTicket, false) + } else { + // Every earlier turn has ended, so this turn is the current turn. + state.holder = ticket + state.holderPriority = nil + return (state.lastTicket, true) + } + } + return Turn(turns: self, previousTicket: previousTicket, ticket: ticket, wasCurrentWhenReserved: isCurrent) + } + + /// Whether every turn reserved so far has ended. + /// + /// A turn ends only after every turn reserved before it has ended, so every turn has ended once the most recently reserved turn has. + var isIdle: Bool { + state.withLock { $0.lastTicket?.hasEnded ?? true } + } + + /// The number of tasks waiting for their turn whose priority is recorded. Used by tests. + var waitingTaskCount: Int { + state.withLock { $0.waitingTaskCounts.values.reduce(0, +) } + } + + /// The highest priority of the tasks waiting for their turn whose priority is recorded. Used by tests. + var highestWaitingPriority: TaskPriority? { + state.withLock(\.highestWaitingPriority) + } + + /// Records that the task waiting for `ticket`'s turn was escalated to `priority`, and escalates the task holding the + /// current turn to match from a new task, so the task holding the turn may be escalated after this method returns. + /// Called by the waiting task's escalation handler. Tests call it directly to deliver escalations in orders that the + /// runtime allows but cannot be made to produce on demand. + func waitingTicket(_ ticket: Ticket, wasEscalatedTo priority: TaskPriority) { + let escalateHolder = state.withLock { state -> (@Sendable () -> Void)? in + // Ignore the escalation if the ticket is not waiting yet, is no longer waiting, or already waits at this + // priority or higher. + guard let waitingPriority = ticket.waitingPriority, waitingPriority < priority else { return nil } + state.removeWaitingTask(at: waitingPriority) + state.addWaitingTask(at: priority) + ticket.waitingPriority = priority + return state.escalateHolder(to: priority) + } + if let escalateHolder { + // The runtime holds the waiting task's status lock while it runs the task's escalation handler, and + // escalating the task holding the turn takes that task's status lock. A cancellation handler of the task + // holding the turn runs under that task's status lock and may cancel the waiting task, which takes the + // locks in the opposite order. Escalate from a new task so that this handler never waits for another + // task's status lock. Escalation only raises a task's priority, so escalations that run late or out of + // order still leave the task at the highest priority requested. + Task.detached(priority: priority) { + escalateHolder() + } + } + } + + // MARK: Fileprivate + + fileprivate let escalatesPriority: Bool + + #if DEBUG + private let didEndTurn: (@Sendable () -> Void)? + #endif + + fileprivate func register( + escalation escalate: @escaping @Sendable (TaskPriority) -> Void, + for ticket: Ticket, + ) { + let priority = state.withLock { state -> TaskPriority? in + guard !ticket.hasEnded else { + // Do not retain a task that has already ended its turn. + return nil + } + ticket.escalate = escalate + // Waiting tasks may have asked to escalate this ticket's task before it was registered. + return state.holder === ticket ? state.holderPriority : nil + } + if let priority { + escalate(priority) + } + } + + nonisolated(nonsending) fileprivate func begin(_ ticket: Ticket, after previousTicket: Ticket?) async { + if let previousTicket { + if escalatesPriority, #available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) { + await withTaskPriorityEscalationHandler { + await wait(for: previousTicket, as: ticket, recordingPriority: true) + } onPriorityEscalated: { [self] _, newPriority in + waitingTicket(ticket, wasEscalatedTo: newPriority) + } + } else { + await wait(for: previousTicket, as: ticket, recordingPriority: false) + } + } + state.withLock { state in + if let waitingPriority = ticket.waitingPriority { + state.removeWaitingTask(at: waitingPriority) + ticket.waitingPriority = nil + } + } + } + + fileprivate func end(_ ticket: Ticket) { + let (successor, escalateNextHolder) = state.withLock { state -> (UnsafeContinuation?, (@Sendable () -> Void)?) in + ticket.hasEnded = true + // Release the task now that waiting tasks no longer need to escalate it. + ticket.escalate = nil + var escalateNextHolder: (@Sendable () -> Void)? + if state.holder === ticket { + // Turns end in order, so the next ticket, if one has been reserved, holds the current turn now. + state.holder = ticket.next + state.holderPriority = nil + if let highestWaitingPriority = state.highestWaitingPriority { + escalateNextHolder = state.escalateHolder(to: highestWaitingPriority) + } + } + ticket.next = nil + defer { ticket.successor = nil } + return (ticket.successor, escalateNextHolder) + } + // Escalate and resume only after releasing the lock: either may synchronously run other code. + // Escalating before resuming means the next task is scheduled at its escalated priority. + escalateNextHolder?() + successor?.resume() + #if DEBUG + didEndTurn?() + #endif + } + + // MARK: Private + + private struct State { + /// The most recently reserved ticket. + var lastTicket: Ticket? + /// The earliest ticket whose turn has not ended, if any. + var holder: Ticket? + /// The priority to which the holder's task has been escalated on behalf of waiting tasks. + var holderPriority: TaskPriority? + /// The number of tasks waiting for their turn, by the raw value of their priority. + var waitingTaskCounts = [UInt8: Int]() + + var highestWaitingPriority: TaskPriority? { + waitingTaskCounts.keys.max().map(TaskPriority.init(rawValue:)) + } + + mutating func addWaitingTask(at priority: TaskPriority) { + waitingTaskCounts[priority.rawValue, default: 0] += 1 + } + + mutating func removeWaitingTask(at priority: TaskPriority) { + let count = waitingTaskCounts[priority.rawValue, default: 0] - 1 + waitingTaskCounts[priority.rawValue] = count > 0 ? count : nil + } + + /// Records that the holder's task should execute at `priority` or higher. + /// - Returns: A closure that escalates the holder's task, to be called after releasing the lock. + mutating func escalateHolder(to priority: TaskPriority) -> (@Sendable () -> Void)? { + guard let holder, holderPriority.map({ $0 < priority }) ?? true else { return nil } + holderPriority = priority + // If the holder's task is not yet registered, registering it applies `holderPriority`. + guard let escalate = holder.escalate else { return nil } + return { escalate(priority) } + } + } + + private let state = Mutex(State()) + + nonisolated(nonsending) private func wait(for previousTicket: Ticket, as ticket: Ticket, recordingPriority: Bool) async { + await withUnsafeContinuation { (continuation: UnsafeContinuation) in + let (hasPreviousTicketEnded, escalateHolder) = state.withLock { state -> (Bool, (@Sendable () -> Void)?) in + guard !previousTicket.hasEnded else { return (true, nil) } + previousTicket.successor = continuation + guard recordingPriority else { return (false, nil) } + // Read the priority under the lock so that an escalation of this task is either reflected here + // or delivered to `waitingTicket(_:wasEscalatedTo:)` after this ticket is recorded as waiting. + let priority = Task.currentPriority + ticket.waitingPriority = priority + state.addWaitingTask(at: priority) + return (false, state.escalateHolder(to: priority)) + } + // Escalate and resume only after releasing the lock: either may synchronously run other code. + // A continuation resumed before its task suspends does not suspend the task. + escalateHolder?() + if hasPreviousTicketEnded { + continuation.resume() + } + } + } +} + +/// A turn reserved from a `Turns` instance. +struct Turn: Sendable { + // MARK: Initialization + + fileprivate init(turns: Turns, previousTicket: Ticket?, ticket: Ticket, wasCurrentWhenReserved: Bool) { + self.turns = turns + self.previousTicket = previousTicket + self.ticket = ticket + self.wasCurrentWhenReserved = wasCurrentWhenReserved + } + + // MARK: Internal + + /// Whether every earlier turn had ended when this turn was reserved, so that `begin()` returns without suspending. + /// + /// A queue starts a task on the main actor only if the task's turn was current when it was reserved. A task that waits + /// for its turn resumes on the global concurrent executor whichever executor it waited on, so waiting on the main actor + /// would only make the task take an extra turn there. + let wasCurrentWhenReserved: Bool + + /// The state of this turn. Used by tests. + let ticket: Ticket + + /// Registers the task that takes this turn, so that tasks waiting for later turns can escalate its priority. + func register(_ task: Task) { + guard turns.escalatesPriority, #available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) else { return } + turns.register(escalation: { task.escalatePriority(to: $0) }, for: ticket) + } + + /// Suspends until every earlier turn has ended. + /// + /// Runs on the caller's executor, so a task on the main actor whose turn is current begins it without hopping off of the main actor. + /// - Warning: Must be called at most once, from the task that takes this turn. + nonisolated(nonsending) func begin() async { + await turns.begin(ticket, after: previousTicket) + } + + /// Ends this turn, allowing the next turn to begin. + /// - Warning: Must be called exactly once, after `begin()` returns. + func end() { + turns.end(ticket) + } + + // MARK: Private + + private let turns: Turns + private let previousTicket: Ticket? +} + +// MARK: - Ticket + +/// The state of one turn. Every property is guarded by the lock of the `Turns` instance that reserved the ticket. +final class Ticket: @unchecked Sendable { + /// Whether the turn has ended. + var hasEnded = false + /// The ticket reserved after this one, while this ticket's turn has not ended. + var next: Ticket? + /// The continuation of the task waiting for this turn to end. + var successor: UnsafeContinuation? + /// The priority of this ticket's task while it waits for its turn, or `nil` if it is not waiting. + var waitingPriority: TaskPriority? + /// Escalates this ticket's task. Set once the task is registered, and cleared when its turn ends. + var escalate: (@Sendable (TaskPriority) -> Void)? +} diff --git a/Tests/AsyncQueueTests/ActorQueueTests.swift b/Tests/AsyncQueueTests/ActorQueueTests.swift index 292e212..54c397a 100644 --- a/Tests/AsyncQueueTests/ActorQueueTests.swift +++ b/Tests/AsyncQueueTests/ActorQueueTests.swift @@ -21,6 +21,7 @@ // SOFTWARE. import Foundation +import Synchronization import Testing @testable import AsyncQueue @@ -131,9 +132,13 @@ struct ActorQueueTests { @Test func mainTask_sendsEventsInOrder() async throws { + // Use a queue of our own rather than `MainActor.queue`: higher-priority tasks that tests running in parallel enqueue + // on the shared queue escalate the tasks ahead of them, which reorders what those tasks do after they suspend. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) var lastTask: Task? for iteration in 1...1_000 { - lastTask = Task(on: MainActor.queue) { + lastTask = Task(on: mainActorQueue) { await counter.incrementAndExpectCount(equals: iteration) } } @@ -143,9 +148,12 @@ struct ActorQueueTests { @Test func mainThrowingTask_sendsEventsInOrder() async throws { + // Use a queue of our own rather than `MainActor.queue`. See `mainTask_sendsEventsInOrder`. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) var lastTask: Task? for iteration in 1...1_000 { - lastTask = Task(on: MainActor.queue) { + lastTask = Task(on: mainActorQueue) { await counter.incrementAndExpectCount(equals: iteration) try doWork() } @@ -156,8 +164,8 @@ struct ActorQueueTests { @Test func task_startsExecutionOfNextTaskAfterSuspension() async { - let systemUnderTest = ActorQueue() - let semaphore = AsyncQueue.Semaphore() + let systemUnderTest = ActorQueue() + let semaphore = Semaphore() systemUnderTest.adoptExecutionContext(of: semaphore) let firstTask = Task(on: systemUnderTest) { semaphore in @@ -174,8 +182,8 @@ struct ActorQueueTests { @Test func throwingTask_startsExecutionOfNextTaskAfterSuspension() async throws { - let systemUnderTest = ActorQueue() - let semaphore = AsyncQueue.Semaphore() + let systemUnderTest = ActorQueue() + let semaphore = Semaphore() systemUnderTest.adoptExecutionContext(of: semaphore) let firstTask = Task(on: systemUnderTest) { semaphore in @@ -243,7 +251,7 @@ struct ActorQueueTests { var systemUnderTest: ActorQueue? = ActorQueue() systemUnderTest?.adoptExecutionContext(of: counter) - let semaphore = AsyncQueue.Semaphore() + let semaphore = Semaphore() let task = try Task(on: #require(systemUnderTest)) { counter in // Make the task wait. await semaphore.wait() @@ -265,7 +273,7 @@ struct ActorQueueTests { var systemUnderTest: ActorQueue? = ActorQueue() systemUnderTest?.adoptExecutionContext(of: counter) - let semaphore = AsyncQueue.Semaphore() + let semaphore = Semaphore() let task = try Task(on: #require(systemUnderTest)) { counter in try doWork() @@ -334,20 +342,6 @@ struct ActorQueueTests { try? await task.value } - @MainActor - @Test - func mainTask_cancelledWhileMainActorIsBusy_executesOperationCancelled() async { - let task = Task(on: MainActor.queue) { - Task.isCancelled - } - - // The task's operation cannot begin until this test suspends and frees the main actor, - // so this cancels the task before its operation begins. - task.cancel() - - #expect(await task.value) - } - @Test func task_canBeCancelledFromCancellationHandlerOfAnotherQueuedTask() async { let taskStarted = Semaphore() @@ -435,6 +429,697 @@ struct ActorQueueTests { }.value } + @Test + func task_holdsTurnUntilItIsIsolatedToActor() async { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + let task = Task(on: actor.queue) { _ in } + // Wait for the task to hop to the actor, whose executor holds the task's job until the test runs it. + _ = await enqueuedJobs.next() + // The task holds its turn until it is isolated to the actor, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: actor.queue.turns) + let didNextTurnBeginBeforeTaskWasIsolatedToActor = hasNextTurnBegun() + // Running the task's job isolates the task to the actor, which ends its turn. + actor.executor.runUntilIdle() + await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeTaskWasIsolatedToActor) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func throwingTask_holdsTurnUntilItIsIsolatedToActor() async throws { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + let task = Task(on: actor.queue) { _ in try doWork() } + // Wait for the task to hop to the actor, whose executor holds the task's job until the test runs it. + _ = await enqueuedJobs.next() + // The task holds its turn until it is isolated to the actor, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: actor.queue.turns) + let didNextTurnBeginBeforeTaskWasIsolatedToActor = hasNextTurnBegun() + // Running the task's job isolates the task to the actor, which ends its turn. + actor.executor.runUntilIdle() + try await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeTaskWasIsolatedToActor) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func mainTask_holdsTurnUntilItIsIsolatedToMainActor() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executor = ManualTaskExecutor() + // While this closure holds the main actor, the task cannot be isolated to it, so its turn cannot end. + let task = await MainActor.run { + let task = Task(on: mainActorQueue) {} + let nextTurn = mainActorQueue.turns.reserve() + Task(executorPreference: executor) { + await nextTurn.begin() + nextTurn.end() + } + // Run the probe until it waits for its turn. + executor.runUntilIdle() + return task + } + await task.value + executor.runUntilIdle() + // The probe is enqueued when it is created, here on the main actor, and again by whoever ends the task's turn. + // `false` for the second job means that the task's turn ended before the task was isolated to the main actor. + #expect(executor.wasEachJobEnqueuedOnMainQueue == [true, true]) + } + + @Test + func mainThrowingTask_holdsTurnUntilItIsIsolatedToMainActor() async throws { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executor = ManualTaskExecutor() + // While this closure holds the main actor, the task cannot be isolated to it, so its turn cannot end. + let task = await MainActor.run { + let task = Task(on: mainActorQueue) { try doWork() } + let nextTurn = mainActorQueue.turns.reserve() + Task(executorPreference: executor) { + await nextTurn.begin() + nextTurn.end() + } + // Run the probe until it waits for its turn. + executor.runUntilIdle() + return task + } + try await task.value + executor.runUntilIdle() + // The probe is enqueued when it is created, here on the main actor, and again by whoever ends the task's turn. + // `false` for the second job means that the task's turn ended before the task was isolated to the main actor. + #expect(executor.wasEachJobEnqueuedOnMainQueue == [true, true]) + } + + @Test + func hasStartedAllWork_onNewQueue_isTrue() { + #expect(systemUnderTest.hasStartedAllWork) + } + + @Test + func hasStartedAllWork_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor() async { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + let task = Task(on: actor.queue) { actor in + actor.queue.hasStartedAllWork + } + // `Task(on:)` takes the task's place on the queue before it returns, and the task cannot be isolated to the actor + // until the test runs the actor's executor. + let hadStartedAllWorkAfterTaskWasEnqueued = actor.queue.hasStartedAllWork + // Wait for the task to hop to the actor. It has begun executing, but it is not isolated to the actor yet. + _ = await enqueuedJobs.next() + let hadStartedAllWorkAfterTaskHoppedToActor = actor.queue.hasStartedAllWork + actor.executor.runUntilIdle() + let hadStartedAllWorkWhileOperationExecuted = await task.value + #expect(!hadStartedAllWorkAfterTaskWasEnqueued) + #expect(!hadStartedAllWorkAfterTaskHoppedToActor) + #expect(hadStartedAllWorkWhileOperationExecuted) + } + + @Test + func hasStartedAllWork_whileLastOperationIsSuspended_isTrue() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { _ in + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task gave up its place on the queue once it was isolated to the actor, before its operation began. + let hadStartedAllWorkWhileOperationWasSuspended = systemUnderTest.hasStartedAllWork + await operationAllowedToReturn.signal() + await task.value + #expect(hadStartedAllWorkWhileOperationWasSuspended) + } + + @Test + func hasStartedAllWork_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActor() async { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + // Each operation reads the property before it can suspend. The actor executes one job at a time, so the last task + // cannot be isolated to the actor while the first task's operation executes. + let firstTask = Task(on: actor.queue) { actor in + actor.queue.hasStartedAllWork + } + let lastTask = Task(on: actor.queue) { actor in + actor.queue.hasStartedAllWork + } + // Wait for the first task to hop to the actor, then run it. Its operation cannot execute before both tasks are enqueued. + _ = await enqueuedJobs.next() + actor.executor.runUntilIdle() + // Wait for the last task to hop to the actor, then run it if the previous call did not already. + _ = await enqueuedJobs.next() + actor.executor.runUntilIdle() + let hadStartedAllWorkWhileFirstOperationExecuted = await firstTask.value + let hadStartedAllWorkWhileLastOperationExecuted = await lastTask.value + #expect(!hadStartedAllWorkWhileFirstOperationExecuted) + #expect(hadStartedAllWorkWhileLastOperationExecuted) + } + + @Test + func hasStartedAllWork_onMainActorQueue_afterTaskIsEnqueuedWhileCallerHoldsMainActor_isFalseUntilOperationRuns() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + // While this closure holds the main actor, the task cannot be isolated to it. The test cannot wait here for the task + // to hop to the main actor, so `mainTask_holdsTurnUntilItIsIsolatedToMainActor` covers when the task's turn ends. + let (task, hadStartedAllWorkAfterTaskWasEnqueued) = await MainActor.run { + let task = Task(on: mainActorQueue) { + mainActorQueue.hasStartedAllWork + } + return (task, mainActorQueue.hasStartedAllWork) + } + let hadStartedAllWorkWhileOperationExecuted = await task.value + #expect(!hadStartedAllWorkAfterTaskWasEnqueued) + #expect(hadStartedAllWorkWhileOperationExecuted) + } + + @Test + func hasStartedAllWork_onMainActorQueue_whileLastOperationIsSuspended_isTrue() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: mainActorQueue) { + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task gave up its place on the queue once it was isolated to the main actor, before its operation began. + let hadStartedAllWorkWhileOperationWasSuspended = mainActorQueue.hasStartedAllWork + await operationAllowedToReturn.signal() + await task.value + #expect(hadStartedAllWorkWhileOperationWasSuspended) + } + + @Test + func task_seesCallersTaskLocalValues() async throws { + // Create the queue while a task-local value is bound: enqueued tasks must see their caller's values instead. + let systemUnderTest = TestTaskLocal.$value.withValue("queue creator") { + ActorQueue() + } + systemUnderTest.adoptExecutionContext(of: counter) + let (value, throwingValue) = try await TestTaskLocal.$value.withValue("caller") { + try await ( + Task(on: systemUnderTest) { _ in TestTaskLocal.value }.value, + Task(on: systemUnderTest) { _ in try doWork(); return TestTaskLocal.value }.value, + ) + } + #expect(value == "caller") + #expect(throwingValue == "caller") + #expect(await Task(on: systemUnderTest) { _ in TestTaskLocal.value }.value == "default") + } + + @Test + func mainTask_seesCallersTaskLocalValues() async throws { + let (value, throwingValue) = try await TestTaskLocal.$value.withValue("caller") { + try await ( + Task(on: MainActor.queue) { TestTaskLocal.value }.value, + Task(on: MainActor.queue) { try doWork(); return TestTaskLocal.value }.value, + ) + } + #expect(value == "caller") + #expect(throwingValue == "caller") + #expect(await Task(on: MainActor.queue) { TestTaskLocal.value }.value == "default") + } + + @Test + func task_withNilPriority_inheritsCallersPriority() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + for priority in [TaskPriority.background, .low, .medium, .high] { + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: priority) { [systemUnderTest] report in + Task(on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { [systemUnderTest] report in + Task(on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == Array(repeating: priority, count: 4)) + } + } + + @Test + func task_withPriority_executesAtThatPriority() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + for priority in [TaskPriority.background, .low, .medium, .high] { + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: priority, on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: priority, on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == Array(repeating: priority, count: 4)) + } + } + + @Test + func task_onQueueWithPriority_withLowerPriority_executesAtQueuePriority() async { + let systemUnderTest = ActorQueue(priority: .medium) + systemUnderTest.adoptExecutionContext(of: counter) + let mainActorQueue = ActorQueue(priority: .medium) + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.medium, .medium, .medium, .medium]) + } + + @Test + func task_onQueueWithPriority_withHigherPriority_executesAtThatPriority() async { + let systemUnderTest = ActorQueue(priority: .medium) + systemUnderTest.adoptExecutionContext(of: counter) + let mainActorQueue = ActorQueue(priority: .medium) + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.high, .high, .high, .high]) + } + + @Test + func task_onQueueWithPriority_withNilPriority_executesAtHigherOfCallersAndQueuePriority() async { + let systemUnderTest = ActorQueue(priority: .medium) + systemUnderTest.adoptExecutionContext(of: counter) + let mainActorQueue = ActorQueue(priority: .medium) + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.medium, .high, .medium, .high, .medium, .high, .medium, .high]) + } + + @Test + func task_onQueueWithPriority_enqueuedFromEscalatedTaskWithLowerBasePriority_executesAtQueuePriority() async { + let systemUnderTest = ActorQueue(priority: .medium) + systemUnderTest.adoptExecutionContext(of: counter) + let enqueuingTaskAllowedToEnqueue = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + let enqueuingTask = Task.detached(priority: .background) { + // Wait for a higher-priority task to escalate this task above the queue's priority. + await enqueuingTaskAllowedToEnqueue.wait() + // Do not await the enqueued task: awaiting it would escalate it. + Task(on: systemUnderTest) { _ in + prioritiesContinuation.yield(Task.currentPriority) + } + } + await value(of: enqueuingTask, awaitedFromTaskWithPriority: .high) { + await enqueuingTaskAllowedToEnqueue.signal() + } + var prioritiesIterator = priorities.makeAsyncIterator() + let executionPriority = await prioritiesIterator.next() + #expect(executionPriority == .medium) + } + + @Test + func task_onQueueWithPriority_enqueuedOutsideOfAnyTask_executesAtHigherOfNewTaskAndQueuePriority() async { + // Threads without a quality of service take the default branch; threads with one, on platforms that support it, do not. + for qualityOfService in [QualityOfService.default, .userInitiated, .utility] { + for queuePriority in [TaskPriority.background, .low, .medium, .high] { + let systemUnderTest = ActorQueue(priority: queuePriority) + systemUnderTest.adoptExecutionContext(of: counter) + let (priorities, prioritiesContinuation) = AsyncStream<(isEnqueued: Bool, priority: TaskPriority)>.makeStream() + // Enqueue from a thread that is not running a task, and create a plain task there for comparison. + let thread = Thread { + Task { + prioritiesContinuation.yield((isEnqueued: false, priority: Task.currentPriority)) + } + Task(on: systemUnderTest) { _ in + prioritiesContinuation.yield((isEnqueued: true, priority: Task.currentPriority)) + } + } + thread.qualityOfService = qualityOfService + thread.start() + var plainTaskPriority: TaskPriority? + var executionPriority: TaskPriority? + // The thread reports exactly two priorities: one from each task. + for await (isEnqueued, priority) in priorities.prefix(2) { + if isEnqueued { + executionPriority = priority + } else { + plainTaskPriority = priority + } + } + #expect(plainTaskPriority.map { executionPriority == max($0, queuePriority) } == true) + } + } + } + + @Test + func task_onQueueWithPriority_withUnspecifiedPriority_executesAtHigherOfCallersAndQueuePriority() async { + let systemUnderTest = ActorQueue(priority: .low) + systemUnderTest.adoptExecutionContext(of: counter) + // `Task` treats a priority with a raw value of zero as no priority, so the task inherits the caller's priority. + let executionPriority = await priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: TaskPriority(rawValue: 0), on: systemUnderTest) { _ in report(Task.currentPriority) } + } + #expect(executionPriority == .high) + } + + @Test + func task_onQueueWithUserInteractivePriority_enqueuedFromUserInteractiveTask_executesAtQueuePriority() async { + let userInteractivePriority = TaskPriority(rawValue: 0x21) + let systemUnderTest = ActorQueue(priority: userInteractivePriority) + systemUnderTest.adoptExecutionContext(of: counter) + // `Task` lowers an inherited user-interactive priority, so only the queue's priority keeps the task user-interactive. + let executionPriority = await priorityOfTask(enqueuedFromTaskWithPriority: userInteractivePriority) { report in + Task(on: systemUnderTest) { _ in report(Task.currentPriority) } + } + #expect(executionPriority == userInteractivePriority) + } + + @Test + func task_onQueueWithPriority_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + let systemUnderTest = ActorQueue(priority: .low) + systemUnderTest.adoptExecutionContext(of: counter) + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .background, on: systemUnderTest) { _ in + let startingPriority = Task.currentPriority + await taskStarted.signal() + await taskAllowedToReturn.wait() + return [startingPriority, Task.currentPriority] + } + await taskStarted.wait() + let priorities = await value(of: task, awaitedFromTaskWithPriority: .high) { + await taskAllowedToReturn.signal() + } + #expect(priorities[0] == .low) + #expect(priorities[1] >= .high) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func throwingTask_onQueueWithPriority_isEscalatedWhenItsTurnBeginsWhileHigherPriorityTaskWaits() async { + let systemUnderTest = ActorQueue(priority: .low) + systemUnderTest.adoptExecutionContext(of: counter) + // Hold the turn before the task enqueued at `.background`, so that the task cannot begin its turn yet. + let heldTurn = systemUnderTest.turns.reserve() + let taskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the queue's help. + let task = Task(priority: .background, on: systemUnderTest) { _ in + await taskAllowedToReport.wait() + try doWork() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for that task's turn to end, and so escalates that task once its turn begins. + let finishWaiting = runTaskWaitingForNextTurn(of: systemUnderTest.turns, withPriority: .high) + await heldTurn.begin() + // Ending the held turn escalates that task on behalf of the waiting task before `end()` returns. + heldTurn.end() + // That task may begin its turn before `end()` escalates it, so let it report only once `end()` has returned. + await taskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) + } + + @Test + func task_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .low, on: systemUnderTest) { _ in + await taskStarted.signal() + await taskAllowedToReturn.wait() + return Task.currentPriority + } + await taskStarted.wait() + let priority = await value(of: task, awaitedFromTaskWithPriority: .high) { + await taskAllowedToReturn.signal() + } + #expect(priority >= .high) + } + + @Test + func mainTask_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + // Use a queue of our own rather than `MainActor.queue`: a higher-priority task that a test running in parallel + // enqueues on the shared queue may escalate this task, which would hide whether awaiting this task escalates it. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .low, on: mainActorQueue) { + await taskStarted.signal() + await taskAllowedToReturn.wait() + return Task.currentPriority + } + await taskStarted.wait() + let priority = await value(of: task, awaitedFromTaskWithPriority: .high) { + await taskAllowedToReturn.signal() + } + #expect(priority >= .high) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func task_waitingForActor_isEscalatedByHigherPriorityTaskWaitingForItsTurn() async { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task: awaiting it would escalate it without the queue's help. + Task(priority: .background, on: actor.queue) { _ in + prioritiesContinuation.yield(Task.currentPriority) + } + // Wait for the task to hop to the actor, whose executor holds the task's job until the test runs it. + await enqueuedJobs.next() + let executor = ManualTaskExecutor() + let nextTurn = actor.queue.turns.reserve() + let waitingTask = Task(executorPreference: executor, priority: .high) { + await nextTurn.begin() + nextTurn.end() + } + nextTurn.register(waitingTask) + // Run the waiting task until it waits for its turn, which escalates the task holding the turn before returning. + executor.runUntilIdle() + actor.executor.runUntilIdle() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + executor.runUntilIdle() + await waitingTask.value + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func throwingTask_isEscalatedWhenItsTurnBeginsWhileHigherPriorityTaskWaits() async { + // Hold the turn before the background task's, so that the background task cannot begin its turn yet. + let heldTurn = systemUnderTest.turns.reserve() + let taskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the queue's help. + let task = Task(priority: .background, on: systemUnderTest) { _ in + await taskAllowedToReport.wait() + try doWork() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for the background task's turn to end, and so escalates the background task once its turn begins. + let finishWaiting = runTaskWaitingForNextTurn(of: systemUnderTest.turns, withPriority: .high) + await heldTurn.begin() + // Ending the held turn escalates the background task on behalf of the waiting task before `end()` returns. + heldTurn.end() + // The background task may begin its turn before `end()` escalates it, so let it report only once `end()` has returned. + await taskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func mainTask_isEscalatedWhenItsTurnBeginsWhileHigherPriorityTaskWaits() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + // Hold the turn before the background task's, so that the background task cannot begin its turn yet. + let heldTurn = mainActorQueue.turns.reserve() + let taskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the queue's help. + let task = Task(priority: .background, on: mainActorQueue) { + await taskAllowedToReport.wait() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for the background task's turn to end, and so escalates the background task once its turn begins. + let finishWaiting = runTaskWaitingForNextTurn(of: mainActorQueue.turns, withPriority: .high) + await heldTurn.begin() + // Ending the held turn escalates the background task on behalf of the waiting task before `end()` returns. + heldTurn.end() + // The background task may begin its turn before `end()` escalates it, so let it report only once `end()` has returned. + await taskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func mainThrowingTask_isEscalatedWhenItsTurnBeginsWhileHigherPriorityTaskWaits() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + // Hold the turn before the background task's, so that the background task cannot begin its turn yet. + let heldTurn = mainActorQueue.turns.reserve() + let taskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the queue's help. + let task = Task(priority: .background, on: mainActorQueue) { + await taskAllowedToReport.wait() + try doWork() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for the background task's turn to end, and so escalates the background task once its turn begins. + let finishWaiting = runTaskWaitingForNextTurn(of: mainActorQueue.turns, withPriority: .high) + await heldTurn.begin() + // Ending the held turn escalates the background task on behalf of the waiting task before `end()` returns. + heldTurn.end() + // The background task may begin its turn before `end()` escalates it, so let it report only once `end()` has returned. + await taskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) + } + + @MainActor + @Test + func mainTask_whenTurnBeginsWithoutWaiting_startsOnMainActorWithoutHoppingThere() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: mainActorQueue) { + executionOrder.withLock { $0.append("queued") } + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @MainActor + @Test + func mainThrowingTask_whenTurnBeginsWithoutWaiting_startsOnMainActorWithoutHoppingThere() async throws { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: mainActorQueue) { + executionOrder.withLock { $0.append("queued") } + try doWork() + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + try await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @Test + func mainTask_whenTurnCannotBeginYet_beginsInOrderOnceTurnBegins() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + // Hold the turn before the tasks' turns, so that every task waits for its turn off of the main actor. + let heldTurn = mainActorQueue.turns.reserve() + await heldTurn.begin() + let executionOrder = Mutex([Int]()) + let tasks = (0..<100).map { index in + Task(on: mainActorQueue) { + executionOrder.withLock { $0.append(index) } + } + } + heldTurn.end() + for task in tasks { + await task.value + } + #expect(executionOrder.withLock(\.self) == Array(0..<100)) + } + // MARK: Private private let systemUnderTest: ActorQueue @@ -443,3 +1128,19 @@ struct ActorQueueTests { @Sendable private func doWork() throws {} } + +// MARK: - ManuallyExecutedActor + +/// An actor whose jobs run only when a test calls `executor.runUntilIdle()`. +private actor ManuallyExecutedActor { + init() { + queue.adoptExecutionContext(of: self) + } + + nonisolated let queue = ActorQueue() + nonisolated let executor = ManualSerialExecutor() + + nonisolated var unownedExecutor: UnownedSerialExecutor { + executor.asUnownedSerialExecutor() + } +} diff --git a/Tests/AsyncQueueTests/CancellableQueueTests.swift b/Tests/AsyncQueueTests/CancellableQueueTests.swift index 61991ac..bbedea2 100644 --- a/Tests/AsyncQueueTests/CancellableQueueTests.swift +++ b/Tests/AsyncQueueTests/CancellableQueueTests.swift @@ -20,6 +20,9 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. +import Dispatch +import Foundation +import Synchronization import Testing @testable import AsyncQueue @@ -61,7 +64,7 @@ struct CancellableQueueTests { } @Test - func cancelTasks_cancelsTaskThatRegisteredCancellationAfterEarlierCancelTasks() { + func cancelTasks_cancelsTaskThatRegistersCancellationAfterward() { let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) let task = Task {} @@ -70,8 +73,61 @@ struct CancellableQueueTests { systemUnderTest.cancelTasks() systemUnderTest.registerCancellation(forTaskWithIdentifier: identifier, task.cancel) + #expect(task.isCancelled) + } + + @Test + func cancelTasks_cancelsTaskThatRegistersCancellationAfterRepeatedCancelTasks() { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let task = Task {} + + let identifier = systemUnderTest.reserveTaskIdentifier() + systemUnderTest.cancelTasks() + systemUnderTest.cancelTasks() + systemUnderTest.registerCancellation(forTaskWithIdentifier: identifier, task.cancel) + + #expect(task.isCancelled) + } + + @Test + func cancelTasks_doesNotCancelTaskThatFinishedBeforeRegisteringCancellationAfterCancelTasks() { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let task = Task {} + + let identifier = systemUnderTest.reserveTaskIdentifier() + systemUnderTest.cancelTasks() + systemUnderTest.taskDidFinish(withIdentifier: identifier) + systemUnderTest.registerCancellation(forTaskWithIdentifier: identifier, task.cancel) + + #expect(!task.isCancelled) + } + + @Test + func cancelTasks_doesNotCancelTrackedTaskThatFinishedWhileBeingCreated() { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + + // Finish the task while it is being created, as a task that runs to completion on another thread can before + // `trackTask` registers its cancellation. + let task = systemUnderTest.trackTask(performing: ()) { identifier, _ in + systemUnderTest.taskDidFinish(withIdentifier: identifier) + return Task {} + } systemUnderTest.cancelTasks() + #expect(!task.isCancelled) + } + + @Test + func cancelTasks_calledWhileTrackedTaskIsBeingCreated_cancelsTask() { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + + // Cancel tasks while the task is being created, as another thread, or the task's own operation, can before + // `trackTask` registers the task's cancellation. + let task = systemUnderTest.trackTask(performing: ()) { _, _ in + systemUnderTest.cancelTasks() + return Task {} + } + #expect(task.isCancelled) } @@ -147,9 +203,6 @@ struct CancellableQueueTests { // Wait for the task to end, so that its operation has run. try await task.value - // `cancelTasks()` returns only once the queue has processed every earlier registration, including the task's. - // The task has ended, so this call cancels nothing, and the task is cancelled only if registering it cancelled it. - systemUnderTest.cancelTasks() #expect(!task.isCancelled) } @@ -269,9 +322,6 @@ struct CancellableQueueTests { // Wait for the task to end, so that its operation has run. try await task.value - // `cancelTasks()` returns only once the queue has processed every earlier registration, including the task's. - // The task has ended, so this call cancels nothing, and the task is cancelled only if registering it cancelled it. - systemUnderTest.cancelTasks() #expect(!task.isCancelled) } @@ -381,9 +431,6 @@ struct CancellableQueueTests { // Wait for the task to end, so that its operation has run. try await task.value - // `cancelTasks()` returns only once the queue has processed every earlier registration, including the task's. - // The task has ended, so this call cancels nothing, and the task is cancelled only if registering it cancelled it. - systemUnderTest.cancelTasks() #expect(!task.isCancelled) } @@ -432,6 +479,32 @@ struct CancellableQueueTests { await task.value } + @Test + func cancelTasks_canBeCalledFromCancellationHandlerOfTaskThatRegistersCancellationAfterward() async { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let handlerInstalled = Semaphore() + let taskAllowedToEnd = Semaphore() + let identifier = systemUnderTest.reserveTaskIdentifier() + let task = Task { + await withTaskCancellationHandler { + await handlerInstalled.signal() + await taskAllowedToEnd.wait() + } onCancel: { + systemUnderTest.cancelTasks() + } + } + await handlerInstalled.wait() + + // Cancel tasks after the task reserved its identifier but before it registered its cancellation, + // so that registering its cancellation cancels the task and runs its cancellation handler. + systemUnderTest.cancelTasks() + systemUnderTest.registerCancellation(forTaskWithIdentifier: identifier, task.cancel) + + await taskAllowedToEnd.signal() + await task.value + #expect(task.isCancelled) + } + @Test func cancelTasks_actorQueue_doesNotCancelCompletedNonthrowingTask() async { let actorQueue = ActorQueue() @@ -506,8 +579,7 @@ struct CancellableQueueTests { try doWork() } - // The task submits its cancellation's registration before `Task(on:)` returns, `cancelTasks()` processes every - // earlier submission before it cancels, and the task cannot end until it is allowed to. + // The task registers its cancellation before `Task(on:)` returns, and cannot end until it is allowed to. await taskStarted.wait() systemUnderTest.cancelTasks() await taskAllowedToEnd.signal() @@ -527,8 +599,7 @@ struct CancellableQueueTests { try doWork() } - // The task submits its cancellation's registration before `Task(on:)` returns, `cancelTasks()` processes every - // earlier submission before it cancels, and the task cannot end until it is allowed to. + // The task registers its cancellation before `Task(on:)` returns, and cannot end until it is allowed to. await taskStarted.wait() systemUnderTest.cancelTasks() await taskAllowedToEnd.signal() @@ -551,8 +622,7 @@ struct CancellableQueueTests { try doWork() } - // The task submits its cancellation's registration before `Task(on:)` returns, `cancelTasks()` processes every - // earlier submission before it cancels, and the task cannot end until it is allowed to. + // The task registers its cancellation before `Task(on:)` returns, and cannot end until it is allowed to. await taskStarted.wait() systemUnderTest.cancelTasks() await taskAllowedToEnd.signal() @@ -572,8 +642,7 @@ struct CancellableQueueTests { try doWork() } - // The task submits its cancellation's registration before `Task(on:)` returns, `cancelTasks()` processes every - // earlier submission before it cancels, and the task cannot end until it is allowed to. + // The task registers its cancellation before `Task(on:)` returns, and cannot end until it is allowed to. await taskStarted.wait() systemUnderTest.cancelTasks() await taskAllowedToEnd.signal() @@ -633,6 +702,188 @@ struct CancellableQueueTests { #expect(!task.isCancelled) } + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func cancelTasks_fifoQueue_whileTaskWaitingForItsTurnIsEscalated_escalatesTaskHoldingTurnWithoutWaitingForCancellationHandler() async { + let fifoQueue = FIFOQueue() + let systemUnderTest = CancellableQueue(underlyingQueue: fifoQueue) + let executor = ManualTaskExecutor() + var enqueuedJobs = executor.enqueuedJobs.makeAsyncIterator() + let handlerRunning = DispatchSemaphore(value: 0) + let waitingTaskEscalated = DispatchSemaphore(value: 0) + let firstTaskAllowedToContinue = Semaphore() + let reportedPriority = Mutex(nil) + let hasWaitingTaskFinished = Mutex(false) + // Never await this task: awaiting it would escalate it without the queue's help. + Task(priority: .low, on: systemUnderTest) { + // Wait on the executor, so that the test runs this task until it waits and knows that it is not running. + _ = await withTaskExecutorPreference(executor) { + await withTaskCancellationHandler { + // Wait for the test rather than for cancellation, so that cancelling this task does not resume it while + // its cancellation handler holds its status lock. + await firstTaskAllowedToContinue.wait() + } onCancel: { + // The runtime holds this task's status lock while it runs this handler, and escalating this task takes + // that lock. Hold the lock until escalating the waiting task has returned. + handlerRunning.signal() + waitingTaskEscalated.wait() + } + } + await suspendUntilEscalated(to: .high) + let priority = Task.currentPriority + reportedPriority.withLock { $0 = priority } + } + // Run the first task, once it moves to the executor, until it waits for the test. The test is done with this iterator + // before `runUntil(_:)` makes its own. The stream keeps each job enqueued in between for that iterator, which at most + // makes `runUntil(_:)` run the executor when no job is pending. + await enqueuedJobs.next() + executor.runUntilIdle() + // Reserve the next turn for a task that runs only when this test runs it, and run it until it waits for its turn. + let turn = fifoQueue.turns.reserve() + let waitingTask = Task(executorPreference: executor, priority: .low) { + await turn.begin() + turn.end() + hasWaitingTaskFinished.withLock { $0 = true } + } + turn.register(waitingTask) + // Neither task is running once this call returns, so cancelling the first task never makes it wait for its own + // status lock. + executor.runUntilIdle() + await withUnsafeContinuation { continuation in + // Escalate the waiting task on a thread of its own, and only then cancel the queue's tasks, so that nothing waits + // for a thread from the cooperative thread pool while the first task's cancellation handler holds the first + // task's status lock. A thread from the pool may wait for that lock for a moment, but the thread that holds it + // never needs the pool. + DispatchQueue(label: "escalateWaitingTask").async { + handlerRunning.wait() + // Only the waiting task's escalation handler can deliver this escalation. If the handler escalated the first + // task before returning, it would wait for the first task's status lock, which the first task's cancellation + // handler holds until this call returns, and this test would never finish. + waitingTask.escalatePriority(to: .high) + waitingTaskEscalated.signal() + continuation.resume() + } + // Cancel the queue's tasks on a thread of their own, since the first task's cancellation handler blocks that + // thread. + DispatchQueue(label: "cancelTasks").async { + systemUnderTest.cancelTasks() + } + } + await firstTaskAllowedToContinue.signal() + // Run the first task until it leaves the executor, and the waiting task once the first task's turn ends. The first + // task reports its priority before its turn ends. + await executor.runUntil { hasWaitingTaskFinished.withLock(\.self) } + let priority = reportedPriority.withLock(\.self) + #expect(priority.map { $0 >= .high } == true) + } + + @Test + func task_fifoQueue_withPriority_executesAtThatPriority() async { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.low, .low]) + } + + @Test + func task_seesCallersTaskLocalValues() async throws { + let fifoQueue = CancellableQueue(underlyingQueue: FIFOQueue()) + let actorQueue = ActorQueue() + let counter = Counter() + actorQueue.adoptExecutionContext(of: counter) + let cancellableActorQueue = CancellableQueue(underlyingQueue: actorQueue) + let cancellableMainActorQueue = CancellableQueue(underlyingQueue: MainActor.queue) + let values = try await TestTaskLocal.$value.withValue("caller") { + try await [ + Task(on: fifoQueue) { TestTaskLocal.value }.value, + Task(on: fifoQueue) { try doWork(); return TestTaskLocal.value }.value, + Task(on: fifoQueue, isolatedTo: counter) { _ in TestTaskLocal.value }.value, + Task(on: fifoQueue, isolatedTo: counter) { _ in try doWork(); return TestTaskLocal.value }.value, + Task(on: cancellableActorQueue) { _ in TestTaskLocal.value }.value, + Task(on: cancellableActorQueue) { _ in try doWork(); return TestTaskLocal.value }.value, + Task(on: cancellableMainActorQueue) { TestTaskLocal.value }.value, + Task(on: cancellableMainActorQueue) { try doWork(); return TestTaskLocal.value }.value, + ] + } + #expect(values == Array(repeating: "caller", count: 8)) + } + + @MainActor + @Test + func task_fifoQueue_withMainActorOperation_startsOnMainActorWithoutHoppingThere() async { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: systemUnderTest) { + executionOrder.withLock { $0.append("queued") } + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @MainActor + @Test + func throwingTask_fifoQueue_withMainActorOperation_startsOnMainActorWithoutHoppingThere() async throws { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: systemUnderTest) { + executionOrder.withLock { $0.append("queued") } + try doWork() + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + try await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + #if DEBUG + @Test + func task_fifoQueue_withMainActorOperation_endsItsTurnOnMainActor() async { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + let task = Task(on: CancellableQueue(underlyingQueue: FIFOQueue(turns: turns))) { @MainActor in + MainActor.assertIsolated() + } + await task.value + // A task that hopped off of the main actor before ending its turn would end it on another thread. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [true]) + } + + @Test + func throwingTask_fifoQueue_withMainActorOperation_endsItsTurnOnMainActor() async throws { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + let task = Task(on: CancellableQueue(underlyingQueue: FIFOQueue(turns: turns))) { @MainActor in + MainActor.assertIsolated() + try doWork() + } + try await task.value + // A task that hopped off of the main actor before ending its turn would end it on another thread. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [true]) + } + #endif + // MARK: Private private struct TestError: Error {} diff --git a/Tests/AsyncQueueTests/DeliveryTests.swift b/Tests/AsyncQueueTests/DeliveryTests.swift deleted file mode 100644 index 0a451d1..0000000 --- a/Tests/AsyncQueueTests/DeliveryTests.swift +++ /dev/null @@ -1,87 +0,0 @@ -// MIT License -// -// Copyright (c) 2025 Dan Federman -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -import Foundation -import Testing - -@testable import AsyncQueue - -struct DeliveryTests { - // MARK: Behavior Tests - - @Test - func getValue_whenValueExists() async { - let systemUnderTest = Delivery() - await systemUnderTest.sendValue(true) - await #expect(systemUnderTest.getValue() == true) - } - - @Test - func getValueThrowing_whenValueExists() async throws { - let systemUnderTest = Delivery() - await systemUnderTest.sendValue(true) - try await #expect(systemUnderTest.getValue() == true) - } - - @Test - func getValueThrowing_whenFailureExists() async throws { - let systemUnderTest = Delivery() - await systemUnderTest.sendFailure(CancellationError()) - await #expect(throws: CancellationError.self, performing: { - try await systemUnderTest.getValue() - }) - } - - @Test - func getValue_whenValueIsSentAfterGetValueSuspends() async { - let systemUnderTest = Delivery() - await #expect(valueOnceGetValueSuspends(on: systemUnderTest) == true) - } - - @Test - func getValueThrowing_whenFailureIsSentAfterGetValueSuspends() async throws { - let systemUnderTest = Delivery() - await #expect(throws: CancellationError.self, performing: { - try await valueOnceGetValueSuspends(on: systemUnderTest) - }) - } - - // MARK: Private - - /// Sends `true` to the delivery once `getValue()` suspends, and returns the value that `getValue()` returns. - private func valueOnceGetValueSuspends(on delivery: isolated Delivery) async -> Bool { - // This task is isolated to the delivery, which this function occupies until `getValue()` suspends. - Task { - delivery.sendValue(true) - } - return await delivery.getValue() - } - - /// Sends a `CancellationError` to the delivery once `getValue()` suspends, and returns the value that `getValue()` returns. - private func valueOnceGetValueSuspends(on delivery: isolated Delivery) async throws -> Bool { - // This task is isolated to the delivery, which this function occupies until `getValue()` suspends. - Task { - delivery.sendFailure(CancellationError()) - } - return try await delivery.getValue() - } -} diff --git a/Tests/AsyncQueueTests/FIFOQueueTests.swift b/Tests/AsyncQueueTests/FIFOQueueTests.swift index b506139..570681a 100644 --- a/Tests/AsyncQueueTests/FIFOQueueTests.swift +++ b/Tests/AsyncQueueTests/FIFOQueueTests.swift @@ -21,6 +21,7 @@ // SOFTWARE. import Foundation +import Synchronization import Testing @testable import AsyncQueue @@ -212,21 +213,6 @@ struct FIFOQueueTests { await Task(on: systemUnderTest) { /* Drain the queue */ }.value } - @Test - func taskIsolatedTo_isNotReentrant() async { - let counter = Counter() - Task(on: systemUnderTest, isolatedTo: counter) { [systemUnderTest] counter in - Task(on: systemUnderTest, isolatedTo: counter) { counter in - counter.incrementAndExpectCount(equals: 2) - } - counter.incrementAndExpectCount(equals: 1) - Task(on: systemUnderTest, isolatedTo: counter) { counter in - counter.incrementAndExpectCount(equals: 3) - } - } - await Task(on: systemUnderTest) { /* Drain the queue */ }.value - } - @Test func throwingTask_isNotReentrant() async { let counter = Counter() @@ -244,23 +230,6 @@ struct FIFOQueueTests { await Task(on: systemUnderTest) { /* Drain the queue */ }.value } - @Test - func throwingTaskIsolatedTo_isNotReentrant() async throws { - let counter = Counter() - Task(on: systemUnderTest, isolatedTo: counter) { [systemUnderTest] counter in - Task(on: systemUnderTest, isolatedTo: counter) { counter in - counter.incrementAndExpectCount(equals: 2) - try doWork() - } - counter.incrementAndExpectCount(equals: 1) - Task(on: systemUnderTest, isolatedTo: counter) { counter in - counter.incrementAndExpectCount(equals: 3) - try doWork() - } - } - await Task(on: systemUnderTest) { /* Drain the queue */ }.value - } - @Test func task_executesAfterQueueIsDeallocated() async throws { var systemUnderTest: FIFOQueue? = FIFOQueue() @@ -415,23 +384,6 @@ struct FIFOQueueTests { try? await task.value } - @Test - func task_cancelledWhileWaitingForPriorTask_executesOperationCancelled() async { - let priorTaskAllowedToEnd = Semaphore() - Task(on: systemUnderTest) { - await priorTaskAllowedToEnd.wait() - } - let task = Task(on: systemUnderTest) { - Task.isCancelled - } - - // The task's operation cannot begin until the prior task ends, so this cancels the task before its operation begins. - task.cancel() - await priorTaskAllowedToEnd.signal() - - #expect(await task.value) - } - @Test func task_canBeCancelledFromCancellationHandlerOfAnotherQueuedTask() async { let otherQueue = FIFOQueue() @@ -519,6 +471,717 @@ struct FIFOQueueTests { } } + @Test + func throwingTask_whenOperationThrows_allowsNextTaskToBegin() async { + struct TestError: Error {} + let task = Task(on: systemUnderTest) { throw TestError() } + // Reserve the turn after the task's turn, as the next task enqueued on the queue would. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + await #expect(throws: TestError.self) { try await task.value } + // The task ended its turn when its operation threw, so the next turn begins without waiting. + #expect(hasNextTurnBegun()) + } + + @Test + func throwingTaskIsolatedTo_whenOperationThrows_allowsNextTaskToBegin() async { + struct TestError: Error {} + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in throw TestError() } + // Reserve the turn after the task's turn, as the next task enqueued on the queue would. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + await #expect(throws: TestError.self) { try await task.value } + // The task ended its turn when its operation threw, so the next turn begins without waiting. + #expect(hasNextTurnBegun()) + } + + @Test + func task_holdsTurnUntilItsOperationReturns() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task holds its turn until its operation returns, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + let didNextTurnBeginBeforeOperationReturned = hasNextTurnBegun() + await operationAllowedToReturn.signal() + await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeOperationReturned) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func throwingTask_holdsTurnUntilItsOperationReturns() async throws { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { + await operationStarted.signal() + await operationAllowedToReturn.wait() + try doWork() + } + await operationStarted.wait() + // The task holds its turn until its operation returns, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + let didNextTurnBeginBeforeOperationReturned = hasNextTurnBegun() + await operationAllowedToReturn.signal() + try await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeOperationReturned) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func taskIsolatedTo_holdsTurnUntilItsOperationReturns() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task holds its turn until its operation returns, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + let didNextTurnBeginBeforeOperationReturned = hasNextTurnBegun() + await operationAllowedToReturn.signal() + await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeOperationReturned) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func throwingTaskIsolatedTo_holdsTurnUntilItsOperationReturns() async throws { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in + await operationStarted.signal() + await operationAllowedToReturn.wait() + try doWork() + } + await operationStarted.wait() + // The task holds its turn until its operation returns, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + let didNextTurnBeginBeforeOperationReturned = hasNextTurnBegun() + await operationAllowedToReturn.signal() + try await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeOperationReturned) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func isIdle_onNewQueue_isTrue() { + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTaskIsEnqueuedWhileOperationCannotReturn_isFalse() async { + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { + await operationAllowedToReturn.wait() + } + // `Task(on:)` takes the task's place on the queue before it returns, and the operation cannot return yet. + let isIdleAfterTaskWasEnqueued = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + _ = await task.value + #expect(!isIdleAfterTaskWasEnqueued) + } + + @Test + func isIdle_whileOperationIsSuspended_isFalseUntilOperationReturns() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation returns. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_whileThrowingOperationIsSuspended_isFalseUntilOperationThrows() async { + struct TestError: Error {} + let operationStarted = Semaphore() + let operationAllowedToThrow = Semaphore() + let task = Task(on: systemUnderTest) { + await operationStarted.signal() + await operationAllowedToThrow.wait() + throw TestError() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation throws. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToThrow.signal() + await #expect(throws: TestError.self) { try await task.value } + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_whileOperationIsolatedToActorIsSuspended_isFalseUntilOperationReturns() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation returns. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_whileThrowingOperationIsolatedToActorIsSuspended_isFalseUntilOperationThrows() async { + struct TestError: Error {} + let operationStarted = Semaphore() + let operationAllowedToThrow = Semaphore() + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in + await operationStarted.signal() + await operationAllowedToThrow.wait() + throw TestError() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation throws. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToThrow.signal() + await #expect(throws: TestError.self) { try await task.value } + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_withCancelledTask_isFalseUntilItsOperationReturns() async { + let firstOperationAllowedToReturn = Semaphore() + let cancelledOperationStarted = Semaphore() + let cancelledOperationAllowedToReturn = Semaphore() + let firstTask = Task(on: systemUnderTest) { + await firstOperationAllowedToReturn.wait() + } + let cancelledTask = Task(on: systemUnderTest) { + await cancelledOperationStarted.signal() + await cancelledOperationAllowedToReturn.wait() + return Task.isCancelled + } + // The first operation cannot return yet, so this cancels the task while it waits on the queue. + cancelledTask.cancel() + await firstOperationAllowedToReturn.signal() + _ = await firstTask.value + // The cancelled task keeps its place on the queue, and its operation still runs. + let isIdleAfterFirstTaskCompleted = systemUnderTest.isIdle + await cancelledOperationStarted.wait() + let isIdleWhileCancelledOperationWasSuspended = systemUnderTest.isIdle + await cancelledOperationAllowedToReturn.signal() + let wasCancelledWhileOperationRan = await cancelledTask.value + #expect(!isIdleAfterFirstTaskCompleted) + #expect(!isIdleWhileCancelledOperationWasSuspended) + #expect(wasCancelledWhileOperationRan) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_withSeveralTasks_isFalseUntilLastOperationReturns() async { + let firstOperationAllowedToReturn = Semaphore() + let lastOperationAllowedToReturn = Semaphore() + let firstTask = Task(on: systemUnderTest) { + await firstOperationAllowedToReturn.wait() + } + let lastTask = Task(on: systemUnderTest) { + await lastOperationAllowedToReturn.wait() + } + await firstOperationAllowedToReturn.signal() + _ = await firstTask.value + // The last operation cannot return yet, so the last task still holds its place on the queue. + let isIdleAfterFirstTaskCompleted = systemUnderTest.isIdle + await lastOperationAllowedToReturn.signal() + _ = await lastTask.value + #expect(!isIdleAfterFirstTaskCompleted) + #expect(systemUnderTest.isIdle) + } + + @Test + func task_seesCallersTaskLocalValues() async throws { + let systemUnderTest = TestTaskLocal.$value.withValue("queue creator") { + FIFOQueue() + } + let values = try await TestTaskLocal.$value.withValue("caller") { + try await [ + Task(on: systemUnderTest) { TestTaskLocal.value }.value, + Task(on: systemUnderTest) { try doWork(); return TestTaskLocal.value }.value, + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in TestTaskLocal.value }.value, + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in try doWork(); return TestTaskLocal.value }.value, + ] + } + #expect(values == Array(repeating: "caller", count: 4)) + #expect(await Task(on: systemUnderTest) { TestTaskLocal.value }.value == "default") + } + + @Test + func task_withNilPriority_inheritsCallersPriority() async { + let systemUnderTest = await Task.detached(priority: .background) { FIFOQueue() }.value + for priority in [TaskPriority.background, .low, .medium, .high] { + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: systemUnderTest) { try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == Array(repeating: priority, count: 4)) + } + } + + @Test + func task_withPriority_executesAtThatPriority() async { + for priority in [TaskPriority.background, .low, .medium, .high] { + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest) { try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest, isolatedTo: Counter()) { _ in try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == Array(repeating: priority, count: 4)) + } + } + + @Test + func task_onQueueWithPriority_withLowerPriority_executesAtQueuePriority() async { + let systemUnderTest = FIFOQueue(priority: .medium) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.medium, .medium]) + } + + @Test + func task_onQueueWithPriority_withHigherPriority_executesAtThatPriority() async { + let systemUnderTest = FIFOQueue(priority: .medium) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.high, .high]) + } + + @Test + func task_onQueueWithPriority_withNilPriority_executesAtHigherOfCallersAndQueuePriority() async { + let systemUnderTest = FIFOQueue(priority: .medium) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.medium, .high, .medium, .high]) + } + + @Test + func task_onQueueWithPriority_enqueuedFromEscalatedTaskWithLowerBasePriority_executesAtQueuePriority() async { + let systemUnderTest = FIFOQueue(priority: .medium) + let enqueuingTaskAllowedToEnqueue = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + let enqueuingTask = Task.detached(priority: .background) { + // Wait for a higher-priority task to escalate this task above the queue's priority. + await enqueuingTaskAllowedToEnqueue.wait() + // Do not await the enqueued task: awaiting it would escalate it. + Task(on: systemUnderTest) { + prioritiesContinuation.yield(Task.currentPriority) + } + } + await value(of: enqueuingTask, awaitedFromTaskWithPriority: .high) { + await enqueuingTaskAllowedToEnqueue.signal() + } + var prioritiesIterator = priorities.makeAsyncIterator() + let executionPriority = await prioritiesIterator.next() + #expect(executionPriority == .medium) + } + + @Test + func task_onQueueWithPriority_enqueuedOutsideOfAnyTask_executesAtHigherOfNewTaskAndQueuePriority() async { + // Threads without a quality of service take the default branch; threads with one, on platforms that support it, do not. + for qualityOfService in [QualityOfService.default, .userInitiated, .utility] { + for queuePriority in [TaskPriority.background, .low, .medium, .high] { + let systemUnderTest = FIFOQueue(priority: queuePriority) + let (priorities, prioritiesContinuation) = AsyncStream<(isEnqueued: Bool, priority: TaskPriority)>.makeStream() + // Enqueue from a thread that is not running a task, and create a plain task there for comparison. + let thread = Thread { + Task { + prioritiesContinuation.yield((isEnqueued: false, priority: Task.currentPriority)) + } + Task(on: systemUnderTest) { + prioritiesContinuation.yield((isEnqueued: true, priority: Task.currentPriority)) + } + } + thread.qualityOfService = qualityOfService + thread.start() + var plainTaskPriority: TaskPriority? + var executionPriority: TaskPriority? + // The thread reports exactly two priorities: one from each task. + for await (isEnqueued, priority) in priorities.prefix(2) { + if isEnqueued { + executionPriority = priority + } else { + plainTaskPriority = priority + } + } + #expect(plainTaskPriority.map { executionPriority == max($0, queuePriority) } == true) + } + } + } + + @Test + func task_onQueueWithPriority_withUnspecifiedPriority_executesAtHigherOfCallersAndQueuePriority() async { + let systemUnderTest = FIFOQueue(priority: .low) + // `Task` treats a priority with a raw value of zero as no priority, so the task inherits the caller's priority. + let executionPriority = await priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: TaskPriority(rawValue: 0), on: systemUnderTest) { report(Task.currentPriority) } + } + #expect(executionPriority == .high) + } + + @Test + func task_onQueueWithUserInteractivePriority_enqueuedFromUserInteractiveTask_executesAtQueuePriority() async { + let userInteractivePriority = TaskPriority(rawValue: 0x21) + let systemUnderTest = FIFOQueue(priority: userInteractivePriority) + // `Task` lowers an inherited user-interactive priority, so only the queue's priority keeps the task user-interactive. + let executionPriority = await priorityOfTask(enqueuedFromTaskWithPriority: userInteractivePriority) { report in + Task(on: systemUnderTest) { report(Task.currentPriority) } + } + #expect(executionPriority.map { $0 >= userInteractivePriority } == true) + } + + @Test + func task_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .low, on: systemUnderTest) { + await taskStarted.signal() + await taskAllowedToReturn.wait() + return Task.currentPriority + } + await taskStarted.wait() + let priority = await value(of: task, awaitedFromTaskWithPriority: .high) { + await taskAllowedToReturn.signal() + } + #expect(priority >= .high) + } + + @Test + func taskIsolatedTo_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .low, on: systemUnderTest, isolatedTo: Counter()) { _ in + await taskStarted.signal() + await taskAllowedToReturn.wait() + return Task.currentPriority + } + await taskStarted.wait() + let priority = await value(of: task, awaitedFromTaskWithPriority: .high) { + await taskAllowedToReturn.signal() + } + #expect(priority >= .high) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func task_isEscalatedByHigherPriorityTaskWaitingForItsTurn() async { + let taskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the queue's help. + let task = Task(priority: .background, on: systemUnderTest) { + await taskAllowedToReport.wait() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for the task's turn to end, and so escalates the task before this call returns. + let finishWaiting = runTaskWaitingForNextTurn(of: systemUnderTest.turns, withPriority: .high) + await taskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func taskIsolatedTo_isEscalatedByHigherPriorityTaskWaitingForItsTurn() async { + let taskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the queue's help. + let task = Task(priority: .background, on: systemUnderTest, isolatedTo: Counter()) { _ in + await taskAllowedToReport.wait() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for the task's turn to end, and so escalates the task before this call returns. + let finishWaiting = runTaskWaitingForNextTurn(of: systemUnderTest.turns, withPriority: .high) + await taskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func throwingTask_isEscalatedByHigherPriorityTaskWaitingForItsTurn() async { + let taskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the queue's help. + let task = Task(priority: .background, on: systemUnderTest) { + await taskAllowedToReport.wait() + try doWork() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for the task's turn to end, and so escalates the task before this call returns. + let finishWaiting = runTaskWaitingForNextTurn(of: systemUnderTest.turns, withPriority: .high) + await taskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func throwingTaskIsolatedTo_isEscalatedByHigherPriorityTaskWaitingForItsTurn() async { + let taskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the queue's help. + let task = Task(priority: .background, on: systemUnderTest, isolatedTo: Counter()) { _ in + await taskAllowedToReport.wait() + try doWork() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for the task's turn to end, and so escalates the task before this call returns. + let finishWaiting = runTaskWaitingForNextTurn(of: systemUnderTest.turns, withPriority: .high) + await taskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func task_isEscalatedWhenItsTurnBeginsWhileHigherPriorityTaskWaits() async { + let firstTaskStarted = Semaphore() + let firstTaskAllowedToEnd = Semaphore() + let firstTask = Task(priority: .background, on: systemUnderTest) { + await firstTaskStarted.signal() + await firstTaskAllowedToEnd.wait() + } + await firstTaskStarted.wait() + let secondTaskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task: awaiting it would escalate it without the queue's help. + Task(priority: .background, on: systemUnderTest) { + await secondTaskAllowedToReport.wait() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for the second task's turn to end, and so escalates the second task when its turn begins. + // It is recorded as waiting before this call returns. + let finishWaiting = runTaskWaitingForNextTurn(of: systemUnderTest.turns, withPriority: .high) + await firstTaskAllowedToEnd.signal() + // The first task completes only once ending its turn has returned, and ending its turn escalates the second task. + await firstTask.value + // The second task may begin its turn before ending the first task's turn escalates it, so let it report only now. + await secondTaskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await finishWaiting() + #expect(priority.map { $0 >= .high } == true) + } + + @MainActor + @Test + func task_withMainActorOperation_whenTurnBeginsWithoutWaiting_startsOnMainActorWithoutHoppingThere() async { + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: systemUnderTest) { + executionOrder.withLock { $0.append("queued") } + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @MainActor + @Test + func throwingTask_withMainActorOperation_whenTurnBeginsWithoutWaiting_startsOnMainActorWithoutHoppingThere() async throws { + let executionOrder = Mutex([String]()) + // The test holds the main actor, so neither task runs until the test suspends. + // A task that starts on the main actor runs before a main actor task created after it. + // A task that started elsewhere and then hopped to the main actor would run after that task. + let queuedTask = Task(on: systemUnderTest) { + executionOrder.withLock { $0.append("queued") } + try doWork() + } + let laterTask = Task { @MainActor in + executionOrder.withLock { $0.append("later") } + } + try await queuedTask.value + await laterTask.value + #expect(executionOrder.withLock(\.self) == ["queued", "later"]) + } + + @Test + func task_withMainActorOperation_whenTurnCannotBeginYet_beginsInOrderOnceTurnBegins() async { + // Hold the turn before the tasks' turns, so that every task waits for its turn off of the main actor. + let heldTurn = systemUnderTest.turns.reserve() + await heldTurn.begin() + let executionOrder = Mutex([Int]()) + let tasks = (0..<100).map { index in + Task(on: systemUnderTest) { @MainActor in + executionOrder.withLock { $0.append(index) } + } + } + heldTurn.end() + for task in tasks { + await task.value + } + #expect(executionOrder.withLock(\.self) == Array(0..<100)) + } + + @Test + func throwingTask_withMainActorOperation_whenTurnCannotBeginYet_beginsInOrderOnceTurnBegins() async throws { + // Hold the turn before the tasks' turns, so that every task waits for its turn off of the main actor. + let heldTurn = systemUnderTest.turns.reserve() + await heldTurn.begin() + let executionOrder = Mutex([Int]()) + let tasks = (0..<100).map { index in + Task(on: systemUnderTest) { @MainActor in + executionOrder.withLock { $0.append(index) } + try doWork() + } + } + heldTurn.end() + for task in tasks { + try await task.value + } + #expect(executionOrder.withLock(\.self) == Array(0..<100)) + } + + #if DEBUG + @Test + func task_withMainActorOperation_whenTurnBeginsWithoutWaiting_endsItsTurnOnMainActor() async { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + let task = Task(on: FIFOQueue(turns: turns)) { @MainActor in + MainActor.assertIsolated() + } + await task.value + // A task that hopped off of the main actor before ending its turn would end it on another thread. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [true]) + } + + @Test + func throwingTask_withMainActorOperation_whenTurnBeginsWithoutWaiting_endsItsTurnOnMainActor() async throws { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + let task = Task(on: FIFOQueue(turns: turns)) { @MainActor in + MainActor.assertIsolated() + try doWork() + } + try await task.value + // A task that hopped off of the main actor before ending its turn would end it on another thread. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [true]) + } + + @Test + func task_withMainActorOperation_whenTurnCannotBeginYet_endsItsTurnOnMainActor() async { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + // Hold the turn before the task's turn, so that the task waits for its turn off of the main actor. + let heldTurn = turns.reserve() + await heldTurn.begin() + let task = Task(on: FIFOQueue(turns: turns)) { @MainActor in + MainActor.assertIsolated() + } + heldTurn.end() + await task.value + // The test ends the held turn off of the main actor. A task that hopped off of the main actor before ending its turn + // would end it on another thread too. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [false, true]) + } + + @Test + func throwingTask_withMainActorOperation_whenTurnCannotBeginYet_endsItsTurnOnMainActor() async throws { + let wasEachTurnEndedOnMainThread = Mutex([Bool]()) + let turns = Turns(didEndTurn: { + wasEachTurnEndedOnMainThread.withLock { $0.append(Thread.isMainThread) } + }) + // Hold the turn before the task's turn, so that the task waits for its turn off of the main actor. + let heldTurn = turns.reserve() + await heldTurn.begin() + let task = Task(on: FIFOQueue(turns: turns)) { @MainActor in + MainActor.assertIsolated() + try doWork() + } + heldTurn.end() + try await task.value + // The test ends the held turn off of the main actor. A task that hopped off of the main actor before ending its turn + // would end it on another thread too. + #expect(wasEachTurnEndedOnMainThread.withLock(\.self) == [false, true]) + } + #endif + // MARK: Private private let systemUnderTest = FIFOQueue() diff --git a/Tests/AsyncQueueTests/SemaphoreTests.swift b/Tests/AsyncQueueTests/SemaphoreTests.swift index c5940db..8300041 100644 --- a/Tests/AsyncQueueTests/SemaphoreTests.swift +++ b/Tests/AsyncQueueTests/SemaphoreTests.swift @@ -20,122 +20,157 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. +import Synchronization import Testing @testable import AsyncQueue -final class SemaphoreTests { - // MARK: Initialization +struct SemaphoreTests { + // MARK: Behavior Tests - deinit { - Task { [systemUnderTest] in - let isWaiting = await systemUnderTest.isWaiting - #expect(!isWaiting) - } - } + @Test + func signal_whenSignalCallsReachSuspendedWaitCalls_resumesEveryWaiterAtOnce() async { + let waiters = (1...3).map { _ in Waiter(on: systemUnderTest, executor: executor) } + executor.runUntilIdle() + // No `signal()` call matches any of the three `wait()` calls, so every waiter suspends. + #expect(waiters.map(\.result) == [nil, nil, nil]) - // MARK: Behavior Tests + await systemUnderTest.signal() + executor.runUntilIdle() + // Two `wait()` calls are still unmatched, so every waiter is still suspended. + #expect(waiters.map(\.result) == [nil, nil, nil]) + let isWaitingAfterFirstSignal = await systemUnderTest.isWaiting + #expect(isWaitingAfterFirstSignal) + + await systemUnderTest.signal() + executor.runUntilIdle() + // One `wait()` call is still unmatched, so every waiter is still suspended. + #expect(waiters.map(\.result) == [nil, nil, nil]) + let isWaitingAfterSecondSignal = await systemUnderTest.isWaiting + #expect(isWaitingAfterSecondSignal) + + await systemUnderTest.signal() + executor.runUntilIdle() + // Every `wait()` call is matched, so every waiter has resumed. + #expect(waiters.map(\.result) == [true, true, true]) + let isWaitingAfterThirdSignal = await systemUnderTest.isWaiting + #expect(!isWaitingAfterThirdSignal) + } @Test - func wait_suspendsUntilEqualNumberOfSignalCalls() async { - /* - This test is tricky to pull off! - Our requirements: - 1. We need to call `wait()` before `signal()` - 2. We need to ensure that the `wait()` call suspends _before_ we call `signal()` - 3. We can't `await` the `wait()` call on the test's queue before calling `signal()` since that would deadlock the test. - 4. We must utilize a single actor's isolated context to avoid accidental interleaving when suspending to communicate across actor contexts. - - In order to ensure that we are executing the `wait()` calls before we call `signal()` _without awaiting a `wait()` call_, - we utilize the AsyncQueue.Semaphore's ordered execution context to enqueue ordered `Task`s similar to how an ActorQueue works. - */ - - let iterationCount = 1_000 - /// A counter that will only be accessed from within the `systemUnderTest`'s context - let unsafeCounter = UnsafeCounter() - - for _ in 1...iterationCount { - await systemUnderTest.enqueueAndCount(using: unsafeCounter) { systemUnderTest in - let didSuspend = await systemUnderTest.wait() - #expect(didSuspend) - - return { systemUnderTest in - // Signal that the suspended wait call above has resumed. - // This signal allows us to `wait()` for all of these enqueued `wait()` tasks to have completed later in this test. - systemUnderTest.signal() - } - } + func signal_whenSignalCallsReachAThousandSuspendedWaitCalls_resumesEveryWaiterAtOnce() async { + let waiterCount = 1_000 + let waiters = (1...waiterCount).map { _ in Waiter(on: systemUnderTest, executor: executor) } + executor.runUntilIdle() + // No `signal()` call matches any of the `wait()` calls, so every waiter suspends. + #expect(waiters.allSatisfy { $0.result == nil }) + + for _ in 1.. (@Sendable (isolated AsyncQueue.Semaphore) -> Void)?) async { - // Await the start of the soon-to-be-enqueued `Task` with a continuation. - await withCheckedContinuation { continuation in - // Re-enter the semaphore's ordered context but don't wait for the result. - Task { - // Now that we're back in the semaphore's ordered context, allow the calling code to resume. - continuation.resume() - let executeAfterIncrement = await task(self) - counter.countedTasksCompleted += 1 - executeAfterIncrement?(self) - } +// MARK: - Waiter + +/// A task that calls `wait()` on a semaphore, and that runs only when a test runs its executor. +/// +/// Calls into the semaphore, a default actor, run on the executor that the calling task prefers. So once a test runs +/// the executor until it is idle, every waiter has either returned from `wait()` or is suspended in it. +private final class Waiter: Sendable { + // MARK: Initialization + + init(on semaphore: Semaphore, executor: ManualTaskExecutor) { + Task(executorPreference: executor) { + let didSuspend = await semaphore.wait() + self.waitResult.withLock { $0 = didSuspend } } } - fileprivate func execute(_ task: @Sendable (isolated AsyncQueue.Semaphore) async throws -> Void) async rethrows { - try await task(self) + // MARK: Internal + + /// What `wait()` returned, which is whether it suspended, or `nil` while `wait()` has not returned. + var result: Bool? { + waitResult.withLock(\.self) } -} -// MARK: - UnsafeCounter + // MARK: Private -private final class UnsafeCounter: @unchecked Sendable { - var countedTasksCompleted = 0 + private let waitResult = Mutex(nil) } diff --git a/Tests/AsyncQueueTests/TestHelpersTests.swift b/Tests/AsyncQueueTests/TestHelpersTests.swift new file mode 100644 index 0000000..e589592 --- /dev/null +++ b/Tests/AsyncQueueTests/TestHelpersTests.swift @@ -0,0 +1,86 @@ +// MIT License +// +// Copyright (c) 2026 Dan Federman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import Synchronization +import Testing + +struct TestHelpersTests { + // MARK: Behavior Tests + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func suspendUntilEscalated_whenTaskAlreadyRunsAtPriority_returnsWithoutSuspending() async { + let reportedPriority = Mutex(nil) + Task(executorPreference: executor, priority: .high) { + await suspendUntilEscalated(to: .high) + reportedPriority.withLock { $0 = Task.currentPriority } + } + // Nothing escalates or signals the task, so it returns only if it never waits for an escalation. + executor.runUntilIdle() + let priority = reportedPriority.withLock(\.self) + #expect(priority == .high) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func suspendUntilEscalated_whenTaskIsEscalatedToPriority_returnsAtThatPriority() async { + let reportedPriority = Mutex(nil) + let task = Task(executorPreference: executor, priority: .low) { + await suspendUntilEscalated(to: .high) + reportedPriority.withLock { $0 = Task.currentPriority } + } + // Run the task until it waits for the escalation, by which point its escalation handler is installed. + executor.runUntilIdle() + + task.escalatePriority(to: .high) + await executor.runUntil { reportedPriority.withLock(\.self) != nil } + let priority = reportedPriority.withLock(\.self) + #expect(priority == .high) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func suspendUntilEscalated_whenTaskIsEscalatedBelowPriority_keepsWaiting() async { + let reportedPriority = Mutex(nil) + let task = Task(executorPreference: executor, priority: .low) { + await suspendUntilEscalated(to: .high) + reportedPriority.withLock { $0 = Task.currentPriority } + } + // Run the task until it waits for the escalation, by which point its escalation handler is installed. + executor.runUntilIdle() + + task.escalatePriority(to: .medium) + executor.runUntilIdle() + let priorityAfterEscalationBelowPriority = reportedPriority.withLock(\.self) + #expect(priorityAfterEscalationBelowPriority == nil) + + // Escalate the task to the priority it waits for, so that it returns and the test can end. + task.escalatePriority(to: .high) + await executor.runUntil { reportedPriority.withLock(\.self) != nil } + let priority = reportedPriority.withLock(\.self) + #expect(priority == .high) + } + + // MARK: Private + + private let executor = ManualTaskExecutor() +} diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift new file mode 100644 index 0000000..f40f1b5 --- /dev/null +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -0,0 +1,867 @@ +// MIT License +// +// Copyright (c) 2026 Dan Federman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import Dispatch +import Synchronization +import Testing + +@testable import AsyncQueue + +struct TurnsTests { + // MARK: Behavior Tests + + @Test + func begin_withoutEscalation_waitsForEarlierTurnToEnd() async { + // Runtimes that cannot escalate another task take this path. + let systemUnderTest = Turns(escalatesPriority: false) + let firstTurn = systemUnderTest.reserve() + let hasSecondTurnBegun = probeNextTurn(of: systemUnderTest) + await firstTurn.begin() + let didSecondTurnBeginBeforeFirstTurnEnded = hasSecondTurnBegun() + firstTurn.end() + let didSecondTurnBeginAfterFirstTurnEnded = hasSecondTurnBegun() + #expect(!didSecondTurnBeginBeforeFirstTurnEnded) + #expect(didSecondTurnBeginAfterFirstTurnEnded) + } + + @Test + func begin_withoutEscalation_beginsTurnsInOrderOfReservation() async { + // Runtimes that cannot escalate another task take this path. + let systemUnderTest = Turns(escalatesPriority: false) + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let laterTurns = (1...3).map { _ in systemUnderTest.reserve() } + let begunTurns = Mutex([Int]()) + // Start the tasks in the reverse order of their turns, so that only the turns can make them begin in order. + let tasks = laterTurns.indices.reversed().map { index in + Task(executorPreference: executor) { + await laterTurns[index].begin() + begunTurns.withLock { $0.append(index) } + laterTurns[index].end() + } + } + // Run every task until it waits for its turn. + executor.runUntilIdle() + let turnsBegunBeforeFirstTurnEnded = begunTurns.withLock(\.self) + await firstTurn.begin() + // Ending the first turn lets the later turns begin, one after another, on the executor. + firstTurn.end() + executor.runUntilIdle() + for task in tasks { + await task.value + } + #expect(turnsBegunBeforeFirstTurnEnded.isEmpty) + #expect(begunTurns.withLock(\.self) == Array(laterTurns.indices)) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func begin_withEscalation_waitsForEarlierTurnToEndAndRecordsTaskAsWaitingUntilThen() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + let hasSecondTurnBegun = probeNextTurn(of: systemUnderTest) + await firstTurn.begin() + let didSecondTurnBeginBeforeFirstTurnEnded = hasSecondTurnBegun() + let waitingTaskCountBeforeFirstTurnEnded = systemUnderTest.waitingTaskCount + firstTurn.end() + let didSecondTurnBeginAfterFirstTurnEnded = hasSecondTurnBegun() + #expect(!didSecondTurnBeginBeforeFirstTurnEnded) + #expect(waitingTaskCountBeforeFirstTurnEnded == 1) + #expect(didSecondTurnBeginAfterFirstTurnEnded) + #expect(systemUnderTest.waitingTaskCount == 0) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func reserve_afterEveryEarlierTurnEnds_makesReservedTurnCurrent() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let escalations = Mutex([TaskPriority]()) + // Take two turns, reserving the second only once the first has ended, as on a queue that is idle between tasks. + // A higher-priority task waits behind each turn, so the second turn also shows that the first turn's escalation + // does not carry over to it. + for _ in 1...2 { + let currentTurn = systemUnderTest.reserve() + let (allowedToEnd, allowedToEndContinuation) = AsyncStream.makeStream() + let currentTask = Task(executorPreference: executor, priority: .low) { + await currentTurn.begin() + await withTaskPriorityEscalationHandler { + var allowedToEndIterator = allowedToEnd.makeAsyncIterator() + await allowedToEndIterator.next() + } onPriorityEscalated: { _, newPriority in + escalations.withLock { $0.append(newPriority) } + } + currentTurn.end() + } + currentTurn.register(currentTask) + let nextTurn = systemUnderTest.reserve() + let waitingTask = Task(executorPreference: executor, priority: .high) { + await nextTurn.begin() + nextTurn.end() + } + nextTurn.register(waitingTask) + // Run the current task until it waits to be allowed to end, then the waiting task until it waits for its turn. + // Beginning to wait escalates the task holding the current turn, which runs that task's handler. + executor.runUntilIdle() + allowedToEndContinuation.finish() + // Ending the current turn lets the waiting task take its turn, on the executor. + executor.runUntilIdle() + await currentTask.value + await waitingTask.value + } + // The waiting task escalated each turn's task once, including the task of the turn reserved once every earlier + // turn had ended. + #expect(escalations.withLock(\.self) == [.high, .high]) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func waitingTaskBehindDeepBacklog_escalatedWhileWaiting_escalatesTaskHoldingTurn() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task: awaiting it would escalate it without the turns' help. + let holder = Task(priority: .low) { + await firstTurn.begin() + await suspendUntilEscalated(to: .high) + let priority = Task.currentPriority + // End the turn before reporting, so that the waiting tasks can take their turns once the priority arrives. + firstTurn.end() + prioritiesContinuation.yield(priority) + } + firstTurn.register(holder) + let waitingTasks = (1...10_000).map { _ in + let turn = systemUnderTest.reserve() + let task = Task(executorPreference: executor, priority: .low) { + await turn.begin() + turn.end() + } + turn.register(task) + return task + } + // Run every waiting task until it waits for its turn, at its own priority. + executor.runUntilIdle() + // Escalating the last waiting task escalates the task holding the current turn, from a new task. + waitingTasks[waitingTasks.count - 1].escalatePriority(to: .high) + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + // Ending the holder's turn lets the waiting tasks take their turns, one after another, on the executor. + executor.runUntilIdle() + for task in waitingTasks { + await task.value + } + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func register_afterHigherPriorityTaskBeginsWaiting_escalatesRegisteredTask() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let waitingTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(waitingTask) + // Run the waiting task until it waits for its turn. It asks to escalate the task holding the first turn, + // which is not registered yet. + executor.runUntilIdle() + let firstTaskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task: awaiting it would escalate it without the turns' help. + let firstTask = Task(priority: .low) { + await firstTurn.begin() + await firstTaskAllowedToReport.wait() + let priority = Task.currentPriority + // End the turn before reporting, so that the waiting task can take its turn once the priority arrives. + firstTurn.end() + prioritiesContinuation.yield(priority) + } + // Registering the task applies the escalation that the waiting task asked for, before this call returns. + firstTurn.register(firstTask) + await firstTaskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + executor.runUntilIdle() + await waitingTask.value + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func register_afterHigherPriorityTaskBeginsWaiting_doesNotEscalateTaskForLaterTurn() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let thirdTurn = systemUnderTest.reserve() + let waitingTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(waitingTask) + // Run the waiting task until it waits for its turn. It asks to escalate the task holding the first turn, + // which is not registered yet. + executor.runUntilIdle() + let secondTurnEnded = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it. + let lowerPriorityTask = Task(priority: .low) { + await thirdTurn.begin() + // Report the priority only once ending the second turn has returned, after any escalation it applies. + await secondTurnEnded.wait() + prioritiesContinuation.yield(Task.currentPriority) + thirdTurn.end() + } + // The escalation the waiting task asked for belongs to the task holding the first turn, not to this task. + thirdTurn.register(lowerPriorityTask) + await firstTurn.begin() + // Ending the first turn resumes the waiting task on the executor, and ending its turn lets the third turn begin. + firstTurn.end() + executor.runUntilIdle() + await secondTurnEnded.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await waitingTask.value + await lowerPriorityTask.value + #expect(priority == .low) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func register_afterHigherThenLowerPriorityTasksBeginWaiting_escalatesRegisteredTaskToHigherPriority() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let thirdTurn = systemUnderTest.reserve() + let higherPriorityTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(higherPriorityTask) + // Run the higher-priority task until it waits for its turn. It asks to escalate the task holding the first turn, + // which is not registered yet. + executor.runUntilIdle() + let lowerPriorityTask = Task(executorPreference: executor, priority: .medium) { + await thirdTurn.begin() + thirdTurn.end() + } + thirdTurn.register(lowerPriorityTask) + // Run the lower-priority task until it waits for its turn. It asks to escalate the same task to a lower priority. + executor.runUntilIdle() + let firstTaskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task: awaiting it would escalate it without the turns' help. + let firstTask = Task(priority: .low) { + await firstTurn.begin() + await firstTaskAllowedToReport.wait() + let priority = Task.currentPriority + // End the turn before reporting, so that the waiting tasks can take their turns once the priority arrives. + firstTurn.end() + prioritiesContinuation.yield(priority) + } + // Registering the task applies the escalation that the waiting tasks asked for, before this call returns. + firstTurn.register(firstTask) + await firstTaskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + executor.runUntilIdle() + await higherPriorityTask.value + await lowerPriorityTask.value + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func register_whenTaskHasEscalationHandlerThatUsesTurns_escalatesTask() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let higherPriorityTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(higherPriorityTask) + // Run the waiting task until it waits for its turn. It asks to escalate the task holding the first turn, + // which is not registered yet. + executor.runUntilIdle() + let (handlerInstalled, handlerInstalledContinuation) = AsyncStream.makeStream() + let firstTaskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + let firstTask = taskWithEscalationHandler( + using: systemUnderTest, + taking: firstTurn, + handlerInstalled: handlerInstalledContinuation, + allowedToReport: firstTaskAllowedToReport, + priorities: prioritiesContinuation, + ) + var handlerInstalledIterator = handlerInstalled.makeAsyncIterator() + await handlerInstalledIterator.next() + // Registering the task applies the escalation that the waiting task asked for, which runs the task's handler + // before this call returns. + firstTurn.register(firstTask) + await firstTaskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + executor.runUntilIdle() + await higherPriorityTask.value + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func register_afterTurnEnds_doesNotRetainTask() async { + let systemUnderTest = Turns() + let turn = systemUnderTest.reserve() + await turn.begin() + turn.end() + weak let result = await valueOfTask(registeredAfterItsTurnEnded: turn) + // The ended turn is still the last one reserved, so retaining the task would keep its result alive. + #expect(result == nil) + // Keep the turn, and with it the turns, alive until after the check. + withExtendedLifetime(turn) {} + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func begin_whenWaitingTaskIsEscalated_recordsEscalationAndEscalatesTaskHoldingTurn() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let waitingTaskInspected = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task: awaiting it would escalate it without the turns' help. + let firstTask = Task(priority: .low) { + await firstTurn.begin() + // Hold the turn until the test has inspected the waiting task's record. + await waitingTaskInspected.wait() + await suspendUntilEscalated(to: .high) + let priority = Task.currentPriority + // End the turn before reporting, so that the waiting task can take its turn once the priority arrives. + firstTurn.end() + prioritiesContinuation.yield(priority) + } + firstTurn.register(firstTask) + let waitingTask = Task(executorPreference: executor, priority: .medium) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(waitingTask) + // Run the waiting task until it waits for its turn, recorded at its own priority. + executor.runUntilIdle() + // The task is already recorded as waiting, so only its escalation handler can deliver this escalation. + // The handler records the escalation on this thread before `escalatePriority(to:)` returns, and escalates the + // task holding the current turn from a new task. + waitingTask.escalatePriority(to: .high) + #expect(systemUnderTest.waitingTaskCount == 1) + #expect(systemUnderTest.highestWaitingPriority == .high) + await waitingTaskInspected.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + executor.runUntilIdle() + await waitingTask.value + #expect(priority.map { $0 >= .high } == true) + #expect(systemUnderTest.waitingTaskCount == 0) + #expect(systemUnderTest.highestWaitingPriority == nil) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func waitingTicket_beforeTaskIsRecordedAsWaiting_doesNotRecordTask() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let waitingTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + // An escalation can reach the waiting task's escalation handler after the handler is installed but before the + // task is recorded as waiting. The task's priority already reflects the escalation, so recording the task reads it. + systemUnderTest.waitingTicket(secondTurn.ticket, wasEscalatedTo: .high) + let waitingTaskCountBeforeTaskWaits = systemUnderTest.waitingTaskCount + // Run the waiting task until it waits for its turn. + executor.runUntilIdle() + let waitingTaskCountWhileTaskWaits = systemUnderTest.waitingTaskCount + await firstTurn.begin() + // Ending the first turn lets the waiting task take its turn, on the executor. + firstTurn.end() + executor.runUntilIdle() + await waitingTask.value + #expect(waitingTaskCountBeforeTaskWaits == 0) + #expect(waitingTaskCountWhileTaskWaits == 1) + #expect(systemUnderTest.waitingTaskCount == 0) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func waitingTicket_afterEscalationToHigherPriority_ignoresEscalationToLowerPriority() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let waitingTask = Task(executorPreference: executor, priority: .low) { + await secondTurn.begin() + secondTurn.end() + } + // Run the waiting task until it waits for its turn, recorded at its own priority. + executor.runUntilIdle() + // The runtime raises a task's priority before it runs the task's escalation handler, so escalations that race + // can reach the handler out of order. Deliver an escalation to `.high`, and then a late escalation to `.medium`. + systemUnderTest.waitingTicket(secondTurn.ticket, wasEscalatedTo: .high) + systemUnderTest.waitingTicket(secondTurn.ticket, wasEscalatedTo: .medium) + #expect(systemUnderTest.highestWaitingPriority == .high) + await firstTurn.begin() + // Ending the first turn lets the waiting task take its turn, on the executor. + firstTurn.end() + executor.runUntilIdle() + await waitingTask.value + #expect(systemUnderTest.waitingTaskCount == 0) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func begin_whenTaskHoldingTurnHasEscalationHandlerThatUsesTurns_escalatesTaskHoldingTurn() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let (handlerInstalled, handlerInstalledContinuation) = AsyncStream.makeStream() + let firstTaskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + let firstTask = taskWithEscalationHandler( + using: systemUnderTest, + taking: firstTurn, + handlerInstalled: handlerInstalledContinuation, + allowedToReport: firstTaskAllowedToReport, + priorities: prioritiesContinuation, + ) + firstTurn.register(firstTask) + var handlerInstalledIterator = handlerInstalled.makeAsyncIterator() + await handlerInstalledIterator.next() + let waitingTask = Task(executorPreference: executor, priority: .medium) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(waitingTask) + // Run the waiting task until it waits for its turn. Beginning to wait escalates the first task, + // which runs the first task's handler. + executor.runUntilIdle() + // Escalating the waiting task escalates the first task again, from a new task, which runs the first task's + // handler again. + waitingTask.escalatePriority(to: .high) + await firstTaskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + executor.runUntilIdle() + await waitingTask.value + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func begin_whenWaitingTaskIsEscalatedWhileTaskHoldingTurnRunsCancellationHandler_escalatesTaskHoldingTurnWithoutWaitingForHandler() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let handlerRunning = DispatchSemaphore(value: 0) + let waitingTaskEscalated = DispatchSemaphore(value: 0) + let firstTaskAllowedToContinue = Semaphore() + let reportedPriority = Mutex(nil) + let hasWaitingTaskFinished = Mutex(false) + // Never await this task: awaiting it would escalate it without the turns' help. + let firstTask = Task(executorPreference: executor, priority: .low) { + await firstTurn.begin() + _ = await withTaskCancellationHandler { + // Wait for the test rather than for cancellation, so that cancelling this task does not resume it while its + // cancellation handler holds its status lock. + await firstTaskAllowedToContinue.wait() + } onCancel: { + // The runtime holds this task's status lock while it runs this handler, and escalating this task takes + // that lock. Hold the lock until escalating the waiting task has returned. + handlerRunning.signal() + waitingTaskEscalated.wait() + } + await suspendUntilEscalated(to: .high) + let priority = Task.currentPriority + // End the turn before reporting, so that the waiting task can take its turn once the priority arrives. + firstTurn.end() + reportedPriority.withLock { $0 = priority } + } + firstTurn.register(firstTask) + let waitingTask = Task(executorPreference: executor, priority: .low) { + await secondTurn.begin() + secondTurn.end() + hasWaitingTaskFinished.withLock { $0 = true } + } + secondTurn.register(waitingTask) + // Run the first task until it waits for the test, and the waiting task until it waits for its turn, recorded at its + // own priority. Neither task is running once this call returns, so cancelling the first task never makes it wait + // for its own status lock. + executor.runUntilIdle() + await withUnsafeContinuation { continuation in + // Escalate the waiting task on a thread of its own, and only then cancel the first task, so that nothing waits + // for a thread from the cooperative thread pool while the first task's cancellation handler holds the first + // task's status lock. A thread from the pool may wait for that lock for a moment, but the thread that holds it + // never needs the pool. + DispatchQueue(label: "escalateWaitingTask").async { + handlerRunning.wait() + // Only the waiting task's escalation handler can deliver this escalation. If the handler escalated the first + // task before returning, it would wait for the first task's status lock, which the first task's cancellation + // handler holds until this call returns, and this test would never finish. + waitingTask.escalatePriority(to: .high) + waitingTaskEscalated.signal() + continuation.resume() + } + // Cancel the first task on a thread of its own, since its cancellation handler blocks that thread. + DispatchQueue(label: "cancelFirstTask").async { + firstTask.cancel() + } + } + await firstTaskAllowedToContinue.signal() + // Run the first task until it ends its turn and reports, and then the waiting task until it takes its turn. + await executor.runUntil { hasWaitingTaskFinished.withLock(\.self) } + let priority = reportedPriority.withLock(\.self) + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func end_afterTaskIsRegistered_releasesTask() async { + let systemUnderTest = Turns() + let turn = systemUnderTest.reserve() + weak let result = await valueOfTask(takingTurnAfterItIsRegistered: turn) + // The ended turn is still the last one reserved, so retaining the task would keep its result alive. + #expect(result == nil) + // Keep the turn, and with it the turns, alive until after the check. + withExtendedLifetime(turn) {} + } + + @Test + func end_whileEarlierTurnIsRetained_releasesLaterTurns() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + weak let laterTicket = await ticketOfTurn(reservedAndTakenAfter: firstTurn, from: systemUnderTest) + // Reserve another turn, so that the turns no longer reference the later turn as the last one reserved. + _ = systemUnderTest.reserve() + // A queued task keeps its turn until the task completes, so a turn must not keep later turns alive. + #expect(laterTicket == nil) + withExtendedLifetime(firstTurn) {} + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func end_whileHigherPriorityTaskWaits_resumesNextTaskAtEscalatedPriority() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let thirdTurn = systemUnderTest.reserve() + let nextTask = Task(executorPreference: executor, priority: .medium) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(nextTask) + let higherPriorityTask = Task(executorPreference: executor, priority: .high) { + await thirdTurn.begin() + thirdTurn.end() + } + thirdTurn.register(higherPriorityTask) + // Run both tasks until they wait for their turns. + executor.runUntilIdle() + let enqueuedJobCount = executor.enqueuedJobPriorities.count + await firstTurn.begin() + // Ending the turn resumes the next task, which enqueues the task's next job before `end()` returns. + firstTurn.end() + let resumedJobPriority = executor.enqueuedJobPriorities.dropFirst(enqueuedJobCount).first + executor.runUntilIdle() + await nextTask.value + await higherPriorityTask.value + #expect(resumedJobPriority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func end_afterHigherPriorityTaskStopsWaiting_doesNotEscalateNextTask() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let higherPriorityTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(higherPriorityTask) + // Run the higher-priority task until it waits for its turn. + executor.runUntilIdle() + await firstTurn.begin() + // Ending the first turn resumes the higher-priority task, which stops waiting when its turn begins. + firstTurn.end() + executor.runUntilIdle() + await higherPriorityTask.value + // No task waits any longer, so ending the next turn has no priority to escalate the task after it to. + let thirdTurn = systemUnderTest.reserve() + let fourthTurn = systemUnderTest.reserve() + let thirdTurnEnded = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it. + let lowerPriorityTask = Task(priority: .low) { + await fourthTurn.begin() + // Report the priority only once `end()` returns, after any escalation it applies. + await thirdTurnEnded.wait() + prioritiesContinuation.yield(Task.currentPriority) + fourthTurn.end() + } + fourthTurn.register(lowerPriorityTask) + await thirdTurn.begin() + thirdTurn.end() + await thirdTurnEnded.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await lowerPriorityTask.value + #expect(priority == .low) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func end_afterOneOfTwoHigherPriorityTasksStopsWaiting_escalatesNextTask() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let thirdTurn = systemUnderTest.reserve() + let fourthTurn = systemUnderTest.reserve() + let firstHigherPriorityTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(firstHigherPriorityTask) + let secondHigherPriorityTask = Task(executorPreference: executor, priority: .high) { + await fourthTurn.begin() + fourthTurn.end() + } + fourthTurn.register(secondHigherPriorityTask) + // Run both higher-priority tasks until they wait for their turns. + executor.runUntilIdle() + let lowerPriorityTaskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it. + let lowerPriorityTask = Task(priority: .low) { + await thirdTurn.begin() + await lowerPriorityTaskAllowedToReport.wait() + let priority = Task.currentPriority + // End the turn before reporting, so that the second higher-priority task can take its turn once the priority arrives. + thirdTurn.end() + prioritiesContinuation.yield(priority) + } + thirdTurn.register(lowerPriorityTask) + await firstTurn.begin() + // Ending the first turn resumes the first higher-priority task, which stops waiting when its turn begins. + // Ending its turn escalates the lower-priority task, on behalf of the second higher-priority task, + // before the executor runs out of jobs. + firstTurn.end() + executor.runUntilIdle() + await lowerPriorityTaskAllowedToReport.signal() + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + executor.runUntilIdle() + await firstHigherPriorityTask.value + await secondHigherPriorityTask.value + await lowerPriorityTask.value + #expect(priority.map { $0 >= .high } == true) + } + + @Test + func isIdle_beforeAnyTurnIsReserved_isTrue() { + let systemUnderTest = Turns() + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTurnIsReserved_isFalseUntilTurnEnds() async { + let systemUnderTest = Turns() + let turn = systemUnderTest.reserve() + let isIdleAfterTurnWasReserved = systemUnderTest.isIdle + await turn.begin() + let isIdleAfterTurnBegan = systemUnderTest.isIdle + turn.end() + #expect(!isIdleAfterTurnWasReserved) + #expect(!isIdleAfterTurnBegan) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_withSeveralTurns_isFalseUntilLastTurnEnds() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let lastTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + let isIdleAfterFirstTurnEnded = systemUnderTest.isIdle + await secondTurn.begin() + secondTurn.end() + let isIdleAfterSecondTurnEnded = systemUnderTest.isIdle + await lastTurn.begin() + lastTurn.end() + #expect(!isIdleAfterFirstTurnEnded) + #expect(!isIdleAfterSecondTurnEnded) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTurnIsReservedOnceEveryEarlierTurnEnded_isFalseUntilThatTurnEnds() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + // The value is a snapshot: reserving another turn makes the turns busy again. + let laterTurn = systemUnderTest.reserve() + let isIdleAfterLaterTurnWasReserved = systemUnderTest.isIdle + await laterTurn.begin() + laterTurn.end() + #expect(!isIdleAfterLaterTurnWasReserved) + #expect(systemUnderTest.isIdle) + } + + @Test + func reserve_whenEveryEarlierTurnHasEnded_reservesTurnThatWasCurrentWhenReserved() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + let secondTurn = systemUnderTest.reserve() + #expect(firstTurn.wasCurrentWhenReserved) + #expect(secondTurn.wasCurrentWhenReserved) + } + + @Test + func reserve_whileEarlierTurnHasNotEnded_reservesTurnThatWasNotCurrentWhenReserved() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + await secondTurn.begin() + secondTurn.end() + #expect(!secondTurn.wasCurrentWhenReserved) + } + + @MainActor + @Test + func begin_onMainActor_whenTurnWasCurrentWhenReserved_doesNotSuspend() async { + let systemUnderTest = Turns() + let turn = systemUnderTest.reserve() + let didOtherMainActorTaskRun = Mutex(false) + // This task can run only once the test suspends or returns, since the test holds the main actor. + let otherMainActorTask = Task { @MainActor in + didOtherMainActorTaskRun.withLock { $0 = true } + } + // Beginning a current turn runs on the caller's actor and returns without suspending, + // so it neither hops off of the main actor nor lets another main actor task run. + await turn.begin() + let didOtherMainActorTaskRunDuringBegin = didOtherMainActorTaskRun.withLock(\.self) + turn.end() + await otherMainActorTask.value + #expect(!didOtherMainActorTaskRunDuringBegin) + } + + // MARK: Private + + /// Creates a task that takes `turn` and, once its turn begins, installs an escalation handler that uses `turns`, + /// as an operation's own escalation handler may. + /// - Parameters: + /// - turns: The turns from which `turn` was reserved. + /// - turn: The turn that the task takes. + /// - handlerInstalled: Receives a value once the task's escalation handler is installed. + /// - allowedToReport: Signaled by the test once it has escalated the task. + /// - priorities: Receives the task's priority once `allowedToReport` is signaled, the task has been escalated to + /// `.high` or higher, and the task has ended its turn. + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + private func taskWithEscalationHandler( + using turns: Turns, + taking turn: Turn, + handlerInstalled: AsyncStream.Continuation, + allowedToReport: Semaphore, + priorities: AsyncStream.Continuation, + ) -> Task { + // Never await this task: awaiting it would escalate it without the turns' help. + Task(priority: .low) { + await turn.begin() + let priority = await withTaskPriorityEscalationHandler { + handlerInstalled.yield() + await allowedToReport.wait() + await suspendUntilEscalated(to: .high) + return Task.currentPriority + } onPriorityEscalated: { _, _ in + // The turns must not hold their lock while escalating a task, or this deadlocks. + _ = turns.waitingTaskCount + } + // End the turn before reporting, so that the waiting task can take its turn once the priority arrives. + turn.end() + priorities.yield(priority) + } + } + + /// Returns the value of a task that is registered for `turn` after the turn ended, once nothing else references the task. + private func valueOfTask(registeredAfterItsTurnEnded turn: Turn) async -> Counter { + let executor = ManualTaskExecutor() + let task = Task(executorPreference: executor) { Counter() } + // Run the task to completion, so that the executor no longer runs it once this function returns. + executor.runUntilIdle() + let value = await task.value + turn.register(task) + return value + } + + /// Returns the value of a task that takes `turn` after it is registered for the turn, once nothing else references the task. + private func valueOfTask(takingTurnAfterItIsRegistered turn: Turn) async -> Counter { + let executor = ManualTaskExecutor() + let task = Task(executorPreference: executor) { + await turn.begin() + turn.end() + return Counter() + } + turn.register(task) + // Run the task only once it is registered, and to completion, so that the executor no longer runs it + // once this function returns. + executor.runUntilIdle() + return await task.value + } + + /// Reserves a turn after `earlierTurn`, takes both turns in order, and returns the ticket of the turn it reserved. + private func ticketOfTurn(reservedAndTakenAfter earlierTurn: Turn, from turns: Turns) async -> Ticket { + let turn = turns.reserve() + await earlierTurn.begin() + earlierTurn.end() + await turn.begin() + turn.end() + return turn.ticket + } +} diff --git a/Tests/AsyncQueueTests/Utilities/ManualExecutors.swift b/Tests/AsyncQueueTests/Utilities/ManualExecutors.swift new file mode 100644 index 0000000..82bddae --- /dev/null +++ b/Tests/AsyncQueueTests/Utilities/ManualExecutors.swift @@ -0,0 +1,236 @@ +// MIT License +// +// Copyright (c) 2026 Dan Federman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import Dispatch +import Synchronization + +@testable import AsyncQueue + +/// A task executor that runs its jobs only when a test calls `runUntilIdle()`. +/// +/// A task that prefers this executor makes progress only while the test runs it, +/// so the test decides exactly when the task runs, and knows when it has suspended. +final class ManualTaskExecutor: TaskExecutor { + // MARK: Initialization + + init() { + (enqueuedJobs, enqueuedJobsContinuation) = AsyncStream.makeStream() + } + + // MARK: Internal + + /// Yields once each time a job is enqueued. + let enqueuedJobs: AsyncStream + + /// The priority of each job enqueued so far, in the order in which the jobs were enqueued. + var enqueuedJobPriorities: [TaskPriority] { + state.withLock { $0.enqueuedJobs.map(\.priority) } + } + + /// Whether each job enqueued so far was enqueued from the main dispatch queue, in the order in which the jobs were enqueued. + var wasEachJobEnqueuedOnMainQueue: [Bool] { + state.withLock { $0.enqueuedJobs.map(\.wasEnqueuedOnMainQueue) } + } + + func enqueue(_ job: consuming ExecutorJob) { + // The caller doesn't keep this executor alive. Once `yield()` resumes the test, the test may run the job to the end + // and release its last reference to this executor before `yield()` returns, so keep the executor alive until this + // method returns. + let retainedSelf = Unmanaged.passRetained(self) + defer { retainedSelf.release() } + let job = UnownedJob(job) + let enqueuedJob = EnqueuedJob( + priority: TaskPriority(rawValue: job.priority.rawValue), + wasEnqueuedOnMainQueue: Self.mainQueueKey.withLock { DispatchQueue.getSpecific(key: $0) } == true, + ) + state.withLock { state in + state.pendingJobs.append(job) + state.enqueuedJobs.append(enqueuedJob) + } + enqueuedJobsContinuation.yield() + } + + /// Runs every pending job, and every job those jobs enqueue on this executor, until none is pending. + /// + /// The jobs run synchronously on the calling thread, so a job run from a test's task runs nested inside that task, + /// which the runtime makes current again once the job returns. Call this function from one task at a time, and never + /// from a job that this executor runs. + func runUntilIdle() { + while let job = state.withLock({ $0.pendingJobs.isEmpty ? nil : $0.pendingJobs.removeFirst() }) { + job.runSynchronously(on: asUnownedTaskExecutor()) + } + } + + /// Runs the pending jobs each time a job is enqueued, until `isDone` returns `true`. + /// + /// Another thread may enqueue a job for a task that prefers this executor at any time, and the task may need more than + /// one job to reach the point that the test waits for. Running the executor after each job is enqueued keeps the test + /// from missing any of them. `isDone` is checked after the executor runs, so it should become `true` while a job on this + /// executor runs. If it never does, this method suspends forever, so a regression hangs the test. + func runUntil(_ isDone: () -> Bool) async { + var enqueuedJobs = enqueuedJobs.makeAsyncIterator() + while !isDone() { + await enqueuedJobs.next() + runUntilIdle() + } + } + + // MARK: Private + + private struct EnqueuedJob { + let priority: TaskPriority + let wasEnqueuedOnMainQueue: Bool + } + + private struct State { + var pendingJobs = [UnownedJob]() + var enqueuedJobs = [EnqueuedJob]() + } + + /// A key whose value is `true` on the main dispatch queue, and `nil` on every other queue. + /// A `Mutex` holds the key because it is `Sendable` whether or not `DispatchSpecificKey` is on a given platform. + private static let mainQueueKey = { + let key = DispatchSpecificKey() + DispatchQueue.main.setSpecific(key: key, value: true) + return Mutex(key) + }() + + private let enqueuedJobsContinuation: AsyncStream.Continuation + private let state = Mutex(State()) +} + +/// A serial executor that runs its jobs only when a test calls `runUntilIdle()`. +/// +/// An actor that uses this executor runs nothing until the test runs it, +/// so the test can hold a task that has hopped to the actor before the task executes there. +final class ManualSerialExecutor: SerialExecutor { + // MARK: Initialization + + init() { + (enqueuedJobs, enqueuedJobsContinuation) = AsyncStream.makeStream() + } + + // MARK: Internal + + /// Yields once each time a job is enqueued. + let enqueuedJobs: AsyncStream + + func enqueue(_ job: consuming ExecutorJob) { + // The caller doesn't keep this executor alive. Once `yield()` resumes the test, the test may run the job to the end + // and release its last reference to this executor before `yield()` returns, so keep the executor alive until this + // method returns. + let retainedSelf = Unmanaged.passRetained(self) + defer { retainedSelf.release() } + let job = UnownedJob(job) + pendingJobs.withLock { $0.append(job) } + enqueuedJobsContinuation.yield() + } + + /// Runs every pending job, and every job those jobs enqueue on this executor, until none is pending. + /// + /// The jobs run synchronously on the calling thread, so a job run from a test's task runs nested inside that task, + /// which the runtime makes current again once the job returns. Call this function from one task at a time, and never + /// from a job that this executor runs. + func runUntilIdle() { + while let job = pendingJobs.withLock({ $0.isEmpty ? nil : $0.removeFirst() }) { + job.runSynchronously(on: asUnownedSerialExecutor()) + } + } + + // MARK: Private + + private let enqueuedJobsContinuation: AsyncStream.Continuation + private let pendingJobs = Mutex<[UnownedJob]>([]) +} + +/// Reserves the next turn of `turns` for a probe task that runs only when a test runs it. +/// +/// A test calls the returned closure to find out whether the turn can begin at a point of the test's choosing: +/// the closure runs the probe until it suspends or completes, so the answer never depends on how the probe is scheduled. +/// - Returns: A closure that runs the probe until it suspends or completes, and returns whether the probe's turn has begun. +func probeNextTurn(of turns: Turns) -> @Sendable () -> Bool { + let executor = ManualTaskExecutor() + let turn = turns.reserve() + let hasTurnBegun = Mutex(false) + Task(executorPreference: executor) { + await turn.begin() + hasTurnBegun.withLock { $0 = true } + turn.end() + } + return { + executor.runUntilIdle() + return hasTurnBegun.withLock(\.self) + } +} + +/// Reserves the next turn of `turns` for a task with the given priority, and runs the task until it waits for its turn. +/// +/// A task that begins waiting for its turn escalates the task holding the current turn before it suspends, +/// so that escalation has happened once this function returns. The task runs only when a test runs it. +/// - Returns: A closure that waits for the turn before the task's turn to end, and then runs the task until it completes. +func runTaskWaitingForNextTurn(of turns: Turns, withPriority priority: TaskPriority) -> () async -> Void { + let executor = ManualTaskExecutor() + let turn = turns.reserve() + let task = Task(executorPreference: executor, priority: priority) { + await turn.begin() + turn.end() + } + turn.register(task) + executor.runUntilIdle() + return { + var enqueuedJobs = executor.enqueuedJobs.makeAsyncIterator() + // Skip the job that started the task, and wait for the job that resumes it once the turn before its turn ends. + await enqueuedJobs.next() + await enqueuedJobs.next() + executor.runUntilIdle() + await task.value + } +} + +/// Awaits the value of `task` from a new task with the given priority, as a higher-priority caller may. +/// +/// The awaiting task runs only when this function runs it, so `afterEscalating` runs once the awaiting task +/// awaits `task`. Awaiting a task escalates it to the awaiting task's priority before the awaiting task suspends. +/// - Parameters: +/// - task: The task whose value to await. +/// - priority: The priority of the awaiting task. +/// - afterEscalating: Runs once the awaiting task awaits `task`, and so once `task` has been escalated. +/// - Returns: The value of `task`, as the awaiting task received it. +func value( + of task: Task, + awaitedFromTaskWithPriority priority: TaskPriority, + afterEscalating: () async -> Void, +) async -> Success { + let executor = ManualTaskExecutor() + var enqueuedJobs = executor.enqueuedJobs.makeAsyncIterator() + let awaitingTask = Task(executorPreference: executor, priority: priority) { + await task.value + } + // Run the awaiting task until it awaits `task`. + await enqueuedJobs.next() + executor.runUntilIdle() + await afterEscalating() + // Completing `task` resumes the awaiting task on the executor. + await enqueuedJobs.next() + executor.runUntilIdle() + return await awaitingTask.value +} diff --git a/Sources/AsyncQueue/Utilities/Semaphore.swift b/Tests/AsyncQueueTests/Utilities/Semaphore.swift similarity index 93% rename from Sources/AsyncQueue/Utilities/Semaphore.swift rename to Tests/AsyncQueueTests/Utilities/Semaphore.swift index 7b3034b..f8d45c1 100644 --- a/Sources/AsyncQueue/Utilities/Semaphore.swift +++ b/Tests/AsyncQueueTests/Utilities/Semaphore.swift @@ -44,7 +44,7 @@ actor Semaphore { return true } - /// Increment the counting semaphore. If the previous value was less than zero, this function resumes a waiting thread before returning. + /// Increment the counting semaphore. If the resulting value is greater than or equal to zero, this function resumes every waiting task before returning. func signal() { count += 1 guard !isWaiting else { diff --git a/Tests/AsyncQueueTests/Utilities/TestHelpers.swift b/Tests/AsyncQueueTests/Utilities/TestHelpers.swift index 506a9f1..b437947 100644 --- a/Tests/AsyncQueueTests/Utilities/TestHelpers.swift +++ b/Tests/AsyncQueueTests/Utilities/TestHelpers.swift @@ -22,6 +22,30 @@ import Dispatch +/// A task-local value that tests use to check which task-local values an enqueued operation sees. +enum TestTaskLocal { + @TaskLocal static var value = "default" +} + +/// Returns the priority at which a task executes when `enqueue` creates it from a task with the given priority. +/// +/// The task is never awaited, since awaiting it would escalate its priority. +/// - Parameters: +/// - enqueuingPriority: The priority of the task that calls `enqueue`. +/// - enqueue: Creates a task that passes its `Task.currentPriority` to `report`. +func priorityOfTask( + enqueuedFromTaskWithPriority enqueuingPriority: TaskPriority, + _ enqueue: @escaping @Sendable (_ report: @escaping @Sendable (TaskPriority) -> Void) -> Void, +) async -> TaskPriority? { + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Do not await this task either: awaiting it would escalate the priority it enqueues from. + Task.detached(priority: enqueuingPriority) { + enqueue { prioritiesContinuation.yield($0) } + } + var prioritiesIterator = priorities.makeAsyncIterator() + return await prioritiesIterator.next() +} + /// Suspends the calling task until it is cancelled. /// /// Returns once the calling task is cancelled. If the task is never cancelled, this function suspends forever, so a @@ -35,6 +59,28 @@ func suspendUntilCancelled() async { withExtendedLifetime(untilCancelledContinuation) {} } +/// Suspends the calling task until its priority is `priority` or higher. +/// +/// Returns once the calling task is escalated to `priority` or higher, or right away if it already runs at that priority. +/// Cancelling the task does not end the wait. If the task is never escalated, this function suspends forever, so a +/// regression that keeps an escalation from reaching the task hangs the test until the CI job times out. +@available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) +func suspendUntilEscalated(to priority: TaskPriority) async { + let escalated = Semaphore() + await withTaskPriorityEscalationHandler { + // An escalation that arrives before the handler is installed is reflected in the task's priority. + guard Task.currentPriority < priority else { return } + await escalated.wait() + } onPriorityEscalated: { _, newPriority in + guard newPriority >= priority else { return } + // The runtime runs this handler while it holds this task's status lock. Signaling the semaphore may resume this + // task, so signal it from another task, after the handler returns. + Task.detached { + await escalated.signal() + } + } +} + /// A serial executor that runs its jobs on a dispatch queue of its own, in the order in which they are enqueued. final class DispatchQueueExecutor: SerialExecutor { func enqueue(_ job: consuming ExecutorJob) {