diff --git a/README.md b/README.md index bf5cea4..094a103 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,8 @@ Your operation sees the [task-local values](https://developer.apple.com/document - 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. - 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. ### Cancellation diff --git a/Sources/AsyncQueue/ActorQueue.swift b/Sources/AsyncQueue/ActorQueue.swift index 6359975..97a7ceb 100644 --- a/Sources/AsyncQueue/ActorQueue.swift +++ b/Sources/AsyncQueue/ActorQueue.swift @@ -105,6 +105,10 @@ extension Task { /// 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. @@ -136,6 +140,7 @@ extension Task { await turn.begin() return await execute(operation, on: executionContext, endingTurn: turn) } + turn.register(self) } /// Runs the given throwing operation asynchronously @@ -145,6 +150,10 @@ extension Task { /// 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. @@ -176,6 +185,7 @@ extension Task { await turn.begin() return try await execute(operation, on: executionContext, endingTurn: turn) } + turn.register(self) } /// Runs the given nonthrowing operation asynchronously @@ -185,6 +195,10 @@ extension Task { /// 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. @@ -215,6 +229,7 @@ extension Task { await turn.begin() return await executeOnMainActor(operation, endingTurn: turn) } + turn.register(self) } /// Runs the given throwing operation asynchronously @@ -224,6 +239,10 @@ extension Task { /// 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. @@ -254,6 +273,7 @@ extension Task { await turn.begin() return try await executeOnMainActor(operation, endingTurn: turn) } + turn.register(self) } } diff --git a/Sources/AsyncQueue/CancellableQueue.swift b/Sources/AsyncQueue/CancellableQueue.swift index 38b351b..7b9d0a2 100644 --- a/Sources/AsyncQueue/CancellableQueue.swift +++ b/Sources/AsyncQueue/CancellableQueue.swift @@ -151,6 +151,10 @@ extension Task { /// 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. @@ -194,6 +198,10 @@ extension Task { /// 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. @@ -237,6 +245,10 @@ extension Task { /// 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. @@ -280,6 +292,10 @@ extension Task { /// 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. @@ -324,6 +340,10 @@ extension Task { /// 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. @@ -369,6 +389,10 @@ extension Task { /// 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. @@ -414,6 +438,10 @@ extension Task { /// 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. @@ -461,6 +489,10 @@ extension Task { /// 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. diff --git a/Sources/AsyncQueue/FIFOQueue.swift b/Sources/AsyncQueue/FIFOQueue.swift index e8bc480..8de755b 100644 --- a/Sources/AsyncQueue/FIFOQueue.swift +++ b/Sources/AsyncQueue/FIFOQueue.swift @@ -85,6 +85,10 @@ extension Task { /// 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. @@ -117,6 +121,7 @@ extension Task { defer { turn.end() } return await operation() } + turn.register(self) } /// Runs the given throwing operation asynchronously @@ -127,6 +132,10 @@ extension Task { /// 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. @@ -159,6 +168,7 @@ extension Task { defer { turn.end() } return try await operation() } + turn.register(self) } /// Runs the given nonthrowing operation asynchronously @@ -169,6 +179,10 @@ extension Task { /// 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. @@ -203,6 +217,7 @@ extension Task { defer { turn.end() } return await operation(isolatedActor) } + turn.register(self) } /// Runs the given throwing operation asynchronously @@ -213,6 +228,10 @@ extension Task { /// 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. @@ -247,5 +266,6 @@ extension Task { defer { turn.end() } return try await operation(isolatedActor) } + turn.register(self) } } diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index 1c78f82..26f19c9 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -25,102 +25,255 @@ 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 - init() {} + /// - 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 + } // MARK: Internal /// Reserves the next turn. func reserve() -> Turn { - let ended = Signal() - let previousTurnEnded = lastTurnEnded.withLock { lastTurnEnded in - defer { lastTurnEnded = ended } - return lastTurnEnded + let ticket = Ticket() + let previousTicket = state.withLock { state in + defer { state.lastTicket = ticket } + if let lastTicket = state.lastTicket, !lastTicket.hasEnded { + lastTicket.next = ticket + } else { + // Every earlier turn has ended, so this turn is the current turn. + state.holder = ticket + state.holderPriority = nil + } + return state.lastTicket } - return Turn(previousTurnEnded: previousTurnEnded, ended: ended) + return Turn(turns: self, previousTicket: previousTicket, ticket: ticket) } - // MARK: Private - - /// The signal fired when the most recently reserved turn ends. - private let lastTurnEnded = Mutex(nil) -} + /// 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, +) } + } -/// A turn reserved from a `Turns` instance. -struct Turn: Sendable { - // MARK: Initialization + /// The highest priority of the tasks waiting for their turn whose priority is recorded. Used by tests. + var highestWaitingPriority: TaskPriority? { + state.withLock(\.highestWaitingPriority) + } - fileprivate init(previousTurnEnded: Signal?, ended: Signal) { - self.previousTurnEnded = previousTurnEnded - self.ended = ended + /// 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: Internal + // MARK: Fileprivate - /// Suspends until every earlier turn has ended. - /// - Warning: Must be called at most once. - func begin() async { - await previousTurnEnded?.wait() + fileprivate let escalatesPriority: Bool + + 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) + } } - /// Ends this turn, allowing the next turn to begin. - func end() { - ended.fire() + 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 + } + } } - // MARK: Private + 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() + } - private let previousTurnEnded: Signal? - private let ended: Signal -} + // MARK: Private -// MARK: - Signal + 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]() -/// A one-shot latch that a single waiter can await. -private final class Signal: Sendable { - // MARK: Initialization + var highestWaitingPriority: TaskPriority? { + waitingTaskCounts.keys.max().map(TaskPriority.init(rawValue:)) + } - init() {} + mutating func addWaitingTask(at priority: TaskPriority) { + waitingTaskCounts[priority.rawValue, default: 0] += 1 + } - // MARK: Internal + mutating func removeWaitingTask(at priority: TaskPriority) { + let count = waitingTaskCounts[priority.rawValue, default: 0] - 1 + waitingTaskCounts[priority.rawValue] = count > 0 ? count : nil + } - /// Opens the latch, resuming the waiter if there is one. - func fire() { - let waiter = state.withLock { state in - state.isFired = true - defer { state.waiter = nil } - return state.waiter + /// 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) } } - // Resume the waiter only after releasing the lock: never resume a continuation while holding a lock. - waiter?.resume() } - /// Suspends until the latch is open. Returns immediately if it is already open. - /// - Warning: At most one task may wait on a signal. - func wait() async { - // A continuation resumed before its task suspends does not suspend the task, - // so an open latch costs no suspension even without a separate fast path. + private let state = Mutex(State()) + + private func wait(for previousTicket: Ticket, as ticket: Ticket, recordingPriority: Bool) async { await withUnsafeContinuation { (continuation: UnsafeContinuation) in - let isFired = state.withLock { state in - if !state.isFired { - state.waiter = continuation - } - return state.isFired + 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)) } - if isFired { + // 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() } } } +} - // MARK: Private +/// A turn reserved from a `Turns` instance. +struct Turn: Sendable { + // MARK: Initialization - private struct State { - var isFired = false - var waiter: UnsafeContinuation? + fileprivate init(turns: Turns, previousTicket: Ticket?, ticket: Ticket) { + self.turns = turns + self.previousTicket = previousTicket + self.ticket = ticket } - private let state = Mutex(State()) + // MARK: Internal + + /// 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. + /// - Warning: Must be called at most once, from the task that takes this turn. + 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 4305167..fdfeadd 100644 --- a/Tests/AsyncQueueTests/ActorQueueTests.swift +++ b/Tests/AsyncQueueTests/ActorQueueTests.swift @@ -131,9 +131,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 +147,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() } @@ -618,6 +625,121 @@ struct ActorQueueTests { #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) + } + // MARK: Private private let systemUnderTest: ActorQueue diff --git a/Tests/AsyncQueueTests/CancellableQueueTests.swift b/Tests/AsyncQueueTests/CancellableQueueTests.swift index 5fe84da..db12c2a 100644 --- a/Tests/AsyncQueueTests/CancellableQueueTests.swift +++ b/Tests/AsyncQueueTests/CancellableQueueTests.swift @@ -20,6 +20,8 @@ // 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 @@ -699,6 +701,81 @@ 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()) diff --git a/Tests/AsyncQueueTests/FIFOQueueTests.swift b/Tests/AsyncQueueTests/FIFOQueueTests.swift index 1613ddd..b8163cc 100644 --- a/Tests/AsyncQueueTests/FIFOQueueTests.swift +++ b/Tests/AsyncQueueTests/FIFOQueueTests.swift @@ -785,6 +785,119 @@ struct FIFOQueueTests { #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) + } + // MARK: Private private let systemUnderTest = FIFOQueue() 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..8cfb24d --- /dev/null +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -0,0 +1,772 @@ +// 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) + } + + // 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 index eb2a531..637a8c4 100644 --- a/Tests/AsyncQueueTests/Utilities/ManualExecutors.swift +++ b/Tests/AsyncQueueTests/Utilities/ManualExecutors.swift @@ -41,6 +41,11 @@ final class ManualTaskExecutor: TaskExecutor { /// 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) } @@ -54,6 +59,7 @@ final class ManualTaskExecutor: TaskExecutor { 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 @@ -75,9 +81,24 @@ final class ManualTaskExecutor: TaskExecutor { } } + /// 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 } @@ -165,6 +186,30 @@ func probeNextTurn(of turns: Turns) -> @Sendable () -> Bool { } } +/// 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 diff --git a/Tests/AsyncQueueTests/Utilities/TestHelpers.swift b/Tests/AsyncQueueTests/Utilities/TestHelpers.swift index 8d72cfc..b437947 100644 --- a/Tests/AsyncQueueTests/Utilities/TestHelpers.swift +++ b/Tests/AsyncQueueTests/Utilities/TestHelpers.swift @@ -59,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) {