diff --git a/README.md b/README.md index 8411362..431e259 100644 --- a/README.md +++ b/README.md @@ -313,7 +313,7 @@ Your operation sees the [task-local values](https://developer.apple.com/document ### 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:)` gives 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. +- `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. - When a higher-priority task awaits a task's value, Swift raises, or *escalates*, that task's priority, as it does for any task. - On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, a task that waits in a queue also raises the priority of the tasks ahead of it to its own priority. That way, the tasks ahead of a high-priority task don't run at a lower priority while it waits. On earlier releases, the tasks ahead keep their own priority. - A task keeps a raised priority until it finishes. diff --git a/Sources/AsyncQueue/ActorQueue.swift b/Sources/AsyncQueue/ActorQueue.swift index a947a8e..0ef21bf 100644 --- a/Sources/AsyncQueue/ActorQueue.swift +++ b/Sources/AsyncQueue/ActorQueue.swift @@ -55,7 +55,13 @@ public final class ActorQueue: @unchecked Sendable { // MARK: Initialization /// Creates an actor queue. - public init() {} + /// - 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 @@ -90,6 +96,9 @@ public final class ActorQueue: @unchecked Sendable { /// 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. @@ -140,6 +149,7 @@ extension 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 @@ -151,7 +161,7 @@ extension Task { ) where Failure == Never { let executionContext = actorQueue.executionContext let turn = actorQueue.turns.reserve() - self.init(name: name, priority: priority) { + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() return await execute(operation, on: executionContext, endingTurn: turn) } @@ -185,6 +195,7 @@ extension 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 @@ -196,7 +207,7 @@ extension Task { ) where Failure == any Error { let executionContext = actorQueue.executionContext let turn = actorQueue.turns.reserve() - self.init(name: name, priority: priority) { + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() return try await execute(operation, on: executionContext, endingTurn: turn) } @@ -230,6 +241,7 @@ extension 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 @@ -240,7 +252,7 @@ extension Task { operation: @MainActor @escaping () async -> Success, ) where Failure == Never { let turn = actorQueue.turns.reserve() - self.init(name: name, priority: priority) { + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() return await executeOnMainActor(operation, endingTurn: turn) } @@ -274,6 +286,7 @@ extension 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 @@ -284,7 +297,7 @@ extension Task { operation: @escaping @MainActor () async throws -> Success, ) where Failure == any Error { let turn = actorQueue.turns.reserve() - self.init(name: name, priority: priority) { + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() return try await executeOnMainActor(operation, endingTurn: turn) } @@ -322,6 +335,10 @@ private func executeOnMainActor( 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 7b9d0a2..b34f8d4 100644 --- a/Sources/AsyncQueue/CancellableQueue.swift +++ b/Sources/AsyncQueue/CancellableQueue.swift @@ -172,6 +172,7 @@ extension 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 @@ -219,6 +220,7 @@ extension 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 @@ -266,6 +268,7 @@ extension 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 @@ -313,6 +316,7 @@ extension 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 diff --git a/Sources/AsyncQueue/FIFOQueue.swift b/Sources/AsyncQueue/FIFOQueue.swift index 702b6f9..96acd4c 100644 --- a/Sources/AsyncQueue/FIFOQueue.swift +++ b/Sources/AsyncQueue/FIFOQueue.swift @@ -35,7 +35,7 @@ public final class FIFOQueue: Sendable { /// 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) { - self.priority = priority + minimumPriority = MinimumPriority(priority) } // MARK: Public @@ -87,37 +87,8 @@ public final class FIFOQueue: Sendable { /// Hands out turns to execute, in the order in which tasks are enqueued. let turns = Turns() - // MARK: Fileprivate - - /// 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. - fileprivate 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 - } - } - - /// 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) - } - } - - // MARK: Private - - private let priority: TaskPriority? + /// The priority that the queue gives each of its tasks at least. + let minimumPriority: MinimumPriority } extension Task { @@ -160,7 +131,7 @@ extension Task { @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success, ) where Failure == Never { let turn = fifoQueue.turns.reserve() - self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() defer { turn.end() } return await operation() @@ -207,7 +178,7 @@ extension Task { @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success, ) where Failure == any Error { let turn = fifoQueue.turns.reserve() - self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() defer { turn.end() } return try await operation() @@ -256,7 +227,7 @@ extension Task { operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { let turn = fifoQueue.turns.reserve() - self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() defer { turn.end() } return await operation(isolatedActor) @@ -305,7 +276,7 @@ extension Task { operation: @Sendable @escaping (isolated ActorType) async throws -> Success, ) where Failure == any Error { let turn = fifoQueue.turns.reserve() - self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() defer { turn.end() } return try await operation(isolatedActor) 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/Tests/AsyncQueueTests/ActorQueueTests.swift b/Tests/AsyncQueueTests/ActorQueueTests.swift index 4b37cd8..fc49ca6 100644 --- a/Tests/AsyncQueueTests/ActorQueueTests.swift +++ b/Tests/AsyncQueueTests/ActorQueueTests.swift @@ -673,22 +673,235 @@ struct ActorQueueTests { @Test func task_withPriority_executesAtThatPriority() async { - let (priorities, prioritiesContinuation) = AsyncStream.makeStream() // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. let mainActorQueue = ActorQueue() mainActorQueue.adoptExecutionContext(of: MainActor.shared) - await Task.detached(priority: .high) { [systemUnderTest] in - // Do not await these tasks: awaiting them from this task would escalate them. - Task(priority: .low, on: systemUnderTest) { _ in + 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) } - Task(priority: .low, on: mainActorQueue) { - 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) } - }.value + } + } + + @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() - #expect(await prioritiesIterator.next() == .low) - #expect(await prioritiesIterator.next() == .low) + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) } @Test