diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index 3c5d439..8d2b0b4 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -141,7 +141,14 @@ final class Turns: Sendable { return state.holder === ticket ? state.holderPriority : nil } if let priority { - escalate(priority) + // The task may already be running its operation. The code that registers a task is the code that enqueues it, + // which may hold a lock, or the runtime's lock on another task, that the operation's escalation handlers take. + // Escalating a task runs its escalation handlers on the escalating thread, so escalate from a new task so that + // those handlers never run on this thread. If the task's turn has not begun when the new task runs, the + // escalation also makes the task begin its turn sooner. + Task.detached(priority: priority) { + escalate(priority) + } } } @@ -157,11 +164,23 @@ final class Turns: Sendable { await wait(for: previousTicket, as: ticket, recordingPriority: false) } } - state.withLock { state in + let priority = state.withLock { state -> TaskPriority? in if let waitingPriority = ticket.waitingPriority { state.removeWaitingTask(at: waitingPriority) ticket.waitingPriority = nil } + // Every earlier turn has ended, so this ticket holds the current turn. Waiting tasks may have asked to + // escalate this ticket's task before it was registered, and the new task that registering it creates to + // apply those escalations may not have run yet. + return state.holderPriority + } + // Escalate this task now, so that it takes its turn at that priority even if that new task has not run yet. + // Escalate only after releasing the lock. This task has no escalation handlers of its own yet, so escalating it + // runs only handlers that this code installed, and none of them is active here. + if let priority, #available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) { + withUnsafeCurrentTask { task in + task?.escalatePriority(to: priority) + } } } @@ -199,7 +218,10 @@ final class Turns: Sendable { 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. + /// The priority to which waiting tasks have asked to escalate the holder's task. + /// + /// A holder's task that is not yet registered is escalated to this priority from a new task once it is registered. + /// The task also escalates itself to this priority as its turn begins, in case that new task has not run yet. var holderPriority: TaskPriority? /// The number of tasks waiting for their turn, by the raw value of their priority. var waitingTaskCounts = [UInt8: Int]() @@ -222,7 +244,7 @@ final class Turns: Sendable { 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`. + // If the holder's task is not yet registered, it is escalated to `holderPriority` later. See `holderPriority`. guard let escalate = holder.escalate else { return nil } return { escalate(priority) } } diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index f40f1b5..00c4bc4 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -175,7 +175,38 @@ struct TurnsTests { @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) @Test - func register_afterHigherPriorityTaskBeginsWaiting_escalatesRegisteredTask() async { + func register_beforeTurnBegins_afterHigherPriorityTaskBeginsWaiting_escalatesTaskAsItsTurnBegins() 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 priorityAfterTurnBegan = Mutex(nil) + let firstTask = Task(executorPreference: executor, priority: .low) { + await firstTurn.begin() + priorityAfterTurnBegan.withLock { $0 = Task.currentPriority } + firstTurn.end() + } + // Registering the task escalates it from a new task, which may not run before the task begins its turn. + firstTurn.register(firstTask) + // Run the first task, which escalates itself as its turn begins whether or not that new task has run, and then + // the waiting task, which takes its turn once the first turn ends. + executor.runUntilIdle() + await firstTask.value + await waitingTask.value + #expect(priorityAfterTurnBegan.withLock(\.self).map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func register_beforeTurnBegins_afterHigherPriorityTaskBeginsWaiting_escalatesRegisteredTaskBeforeItsTurnBegins() async { let systemUnderTest = Turns() let executor = ManualTaskExecutor() let firstTurn = systemUnderTest.reserve() @@ -188,20 +219,57 @@ struct TurnsTests { // 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. + // Registered for the first turn in place of the task that takes it, so that only registering can escalate it. + // Never await this task before it reports its priority: awaiting it would escalate it without the turns' help. + let registeredTask = Task(priority: .low) { + await suspendUntilEscalated(to: .high) + prioritiesContinuation.yield(Task.currentPriority) + } + firstTurn.register(registeredTask) + // The registered task reports its priority only once it is escalated, and the first turn has not begun. + var prioritiesIterator = priorities.makeAsyncIterator() + let priority = await prioritiesIterator.next() + await firstTurn.begin() + firstTurn.end() + executor.runUntilIdle() + await registeredTask.value + await waitingTask.value + #expect(priority.map { $0 >= .high } == true) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func register_afterTurnBegins_afterHigherPriorityTaskBeginsWaiting_escalatesRegisteredTask() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let (turnBegan, turnBeganContinuation) = AsyncStream.makeStream() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the turns' help. let firstTask = Task(priority: .low) { await firstTurn.begin() - await firstTaskAllowedToReport.wait() + turnBeganContinuation.yield() + 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) } - // Registering the task applies the escalation that the waiting task asked for, before this call returns. + var turnBeganIterator = turnBegan.makeAsyncIterator() + await turnBeganIterator.next() + let waitingTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(waitingTask) + // Only now run a higher-priority task until it waits for its turn. It asks to escalate the task holding the first + // turn, which has begun its turn but is not registered yet. + executor.runUntilIdle() + // The task began its turn before it was registered, so registering it applies the escalation that the waiting + // task asked for, from a new task. firstTurn.register(firstTask) - await firstTaskAllowedToReport.signal() var prioritiesIterator = priorities.makeAsyncIterator() let priority = await prioritiesIterator.next() executor.runUntilIdle() @@ -251,7 +319,7 @@ struct TurnsTests { @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) @Test - func register_afterHigherThenLowerPriorityTasksBeginWaiting_escalatesRegisteredTaskToHigherPriority() async { + func register_beforeTurnBegins_afterHigherThenLowerPriorityTasksBeginWaiting_escalatesTaskToHigherPriorityAsItsTurnBegins() async { let systemUnderTest = Turns() let executor = ManualTaskExecutor() let firstTurn = systemUnderTest.reserve() @@ -272,26 +340,21 @@ struct TurnsTests { 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) { + let priorityAfterTurnBegan = Mutex(nil) + let firstTask = Task(executorPreference: executor, 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. + priorityAfterTurnBegan.withLock { $0 = Task.currentPriority } firstTurn.end() - prioritiesContinuation.yield(priority) } - // Registering the task applies the escalation that the waiting tasks asked for, before this call returns. + // Registering the task escalates it from a new task, which may not run before the task begins its turn. firstTurn.register(firstTask) - await firstTaskAllowedToReport.signal() - var prioritiesIterator = priorities.makeAsyncIterator() - let priority = await prioritiesIterator.next() + // Run the first task, which escalates itself as its turn begins whether or not that new task has run, and then + // the waiting tasks. executor.runUntilIdle() + await firstTask.value await higherPriorityTask.value await lowerPriorityTask.value - #expect(priority.map { $0 >= .high } == true) + #expect(priorityAfterTurnBegan.withLock(\.self).map { $0 >= .high } == true) } @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) @@ -301,14 +364,6 @@ struct TurnsTests { 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() @@ -321,8 +376,16 @@ struct TurnsTests { ) 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. + let higherPriorityTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(higherPriorityTask) + // Only now run a higher-priority task until it waits for its turn. It asks to escalate the task holding the first + // turn, which has begun its turn but is not registered yet. + executor.runUntilIdle() + // Registering the task applies the escalation that the waiting task asked for, from a new task, which runs the + // task's handler. firstTurn.register(firstTask) await firstTaskAllowedToReport.signal() var prioritiesIterator = priorities.makeAsyncIterator() @@ -332,6 +395,54 @@ struct TurnsTests { #expect(priority.map { $0 >= .high } == true) } + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func register_whileRegisteringCodeHoldsLockThatTaskEscalationHandlerTakes_escalatesTaskWithoutDeadlocking() async { + let systemUnderTest = Turns() + let executor = ManualTaskExecutor() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + // A lock that the code enqueuing a task holds, and that the task's operation takes in its escalation handler. + let lock = Mutex(()) + let (handlerInstalled, handlerInstalledContinuation) = AsyncStream.makeStream() + 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() + let priority = await withTaskPriorityEscalationHandler { + handlerInstalledContinuation.yield() + await suspendUntilEscalated(to: .high) + return Task.currentPriority + } onPriorityEscalated: { _, _ in + lock.withLock { _ in } + } + // End the turn before reporting, so that the waiting task can take its turn once the priority arrives. + firstTurn.end() + prioritiesContinuation.yield(priority) + } + var handlerInstalledIterator = handlerInstalled.makeAsyncIterator() + await handlerInstalledIterator.next() + let higherPriorityTask = Task(executorPreference: executor, priority: .high) { + await secondTurn.begin() + secondTurn.end() + } + secondTurn.register(higherPriorityTask) + // Only now run a higher-priority task until it waits for its turn. It asks to escalate the task holding the first + // turn, which has begun its turn but is not registered yet. + executor.runUntilIdle() + // The task began running before it was registered, as a task enqueued on a queue may. Registering it applies + // the escalation that the waiting task asked for. If registering runs the task's escalation handler on this + // thread, the handler waits for the lock this thread holds, and this deadlocks. + lock.withLock { _ in + firstTurn.register(firstTask) + } + 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 {