From 44534d054c97e0646c3ac14e9d69bd7e500c6759 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 22:48:57 +0000 Subject: [PATCH 1/8] Test that registering a task does not run its escalation handler under the caller's lock Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLo2UsTkDdhDM9Keiv --- Tests/AsyncQueueTests/TurnsTests.swift | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index f40f1b5..e109b18 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -332,6 +332,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() + 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() + // 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() + // 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 { From 16b42a4197cb9e8240f5e3f5638966560f60f373 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 22:48:57 +0000 Subject: [PATCH 2/8] Escalate a task from a new task when registering it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLo2UsTkDdhDM9Keiv --- Sources/AsyncQueue/Utilities/Turns.swift | 7 ++++++- Tests/AsyncQueueTests/TurnsTests.swift | 8 ++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index 3c5d439..f2a4c17 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -141,7 +141,12 @@ final class Turns: Sendable { return state.holder === ticket ? state.holderPriority : nil } if let priority { - escalate(priority) + // 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 task'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. + Task.detached(priority: priority) { + escalate(priority) + } } } diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index e109b18..d294ddf 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -199,7 +199,7 @@ struct TurnsTests { firstTurn.end() prioritiesContinuation.yield(priority) } - // Registering the task applies the escalation that the waiting task asked for, before this call returns. + // Registering the task applies the escalation that the waiting task asked for, from a new task. firstTurn.register(firstTask) await firstTaskAllowedToReport.signal() var prioritiesIterator = priorities.makeAsyncIterator() @@ -283,7 +283,7 @@ struct TurnsTests { firstTurn.end() prioritiesContinuation.yield(priority) } - // Registering the task applies the escalation that the waiting tasks asked for, before this call returns. + // Registering the task applies the escalation that the waiting tasks asked for, from a new task. firstTurn.register(firstTask) await firstTaskAllowedToReport.signal() var prioritiesIterator = priorities.makeAsyncIterator() @@ -321,8 +321,8 @@ 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. + // 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() From f7b975830b1249122fdef65cb325dc6f468cf7fe Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 22:52:26 +0000 Subject: [PATCH 3/8] Wait for the escalation in register tests, now that it arrives from a new task Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLo2UsTkDdhDM9Keiv --- Tests/AsyncQueueTests/TurnsTests.swift | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index d294ddf..0406198 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -188,12 +188,11 @@ 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. let firstTask = Task(priority: .low) { await firstTurn.begin() - await firstTaskAllowedToReport.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() @@ -201,7 +200,6 @@ struct TurnsTests { } // Registering the task 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() @@ -272,12 +270,11 @@ 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) { await firstTurn.begin() - await firstTaskAllowedToReport.wait() + 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() @@ -285,7 +282,6 @@ struct TurnsTests { } // Registering the task applies the escalation that the waiting tasks asked for, from a new task. firstTurn.register(firstTask) - await firstTaskAllowedToReport.signal() var prioritiesIterator = priorities.makeAsyncIterator() let priority = await prioritiesIterator.next() executor.runUntilIdle() From add211378f2dae153e439c90436bc4669c7a7218 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:06:14 +0000 Subject: [PATCH 4/8] Escalate a task from itself as its turn begins, and from a new task only once its operation may run Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLo2UsTkDdhDM9Keiv --- Sources/AsyncQueue/Utilities/Turns.swift | 30 +++++++++--- Tests/AsyncQueueTests/TurnsTests.swift | 62 ++++++++++++++++++------ 2 files changed, 71 insertions(+), 21 deletions(-) diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index f2a4c17..dda60e4 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -137,13 +137,17 @@ final class Turns: Sendable { 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 + // Waiting tasks may have asked to escalate this ticket's task before it was registered. A task that has not + // begun its turn applies those escalations itself as its turn begins. + // A task that has begun its turn and not ended it holds the current turn. + guard ticket.hasBegun else { return nil } + return state.holderPriority } if let priority { - // 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 task'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. + // The task began its turn before it was registered, so its operation may be running. 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. Task.detached(priority: priority) { escalate(priority) } @@ -162,11 +166,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 } + ticket.hasBegun = true + // 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 `register(escalation:for:)` leaves those + // escalations to the task until its turn begins. + return state.holderPriority + } + // 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) + } } } @@ -311,6 +327,8 @@ struct Turn: Sendable { /// 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 begun. + var hasBegun = false /// Whether the turn has ended. var hasEnded = false /// The ticket reserved after this one, while this ticket's turn has not ended. diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index 0406198..88dafc3 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -175,7 +175,7 @@ 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() @@ -188,17 +188,53 @@ 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 priorityAfterTurnBegan = Mutex(nil) + let firstTask = Task(executorPreference: executor, priority: .low) { + await firstTurn.begin() + priorityAfterTurnBegan.withLock { $0 = Task.currentPriority } + firstTurn.end() + } + // The task has not begun its turn, so registering it leaves the escalation to the task. + firstTurn.register(firstTask) + // Run the first task, which escalates itself as its turn begins, 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_afterTurnBegins_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 (turnBegan, turnBeganContinuation) = AsyncStream.makeStream() let (priorities, prioritiesContinuation) = AsyncStream.makeStream() - // Never await this task: awaiting it would escalate it without the turns' help. + // 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() + 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, from a new task. + var turnBeganIterator = turnBegan.makeAsyncIterator() + await turnBeganIterator.next() + // 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) var prioritiesIterator = priorities.makeAsyncIterator() let priority = await prioritiesIterator.next() @@ -249,7 +285,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() @@ -270,24 +306,20 @@ 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 (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 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. + priorityAfterTurnBegan.withLock { $0 = Task.currentPriority } firstTurn.end() - prioritiesContinuation.yield(priority) } - // Registering the task applies the escalation that the waiting tasks asked for, from a new task. + // The task has not begun its turn, so registering it leaves the escalations to the task. firstTurn.register(firstTask) - var prioritiesIterator = priorities.makeAsyncIterator() - let priority = await prioritiesIterator.next() + // Run the first task, which escalates itself as its turn begins, 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, *) From a919146a19a0294bfcb0e5007b815f63ba715537 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:14:20 +0000 Subject: [PATCH 5/8] Escalate the task holding the turn only after it begins, in tests of escalating from a new task Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLo2UsTkDdhDM9Keiv --- Tests/AsyncQueueTests/TurnsTests.swift | 48 +++++++++++++------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index 88dafc3..6dff747 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -211,14 +211,6 @@ struct TurnsTests { 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 (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. @@ -233,6 +225,14 @@ struct TurnsTests { } 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) @@ -329,14 +329,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() @@ -349,6 +341,14 @@ struct TurnsTests { ) 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() // 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) @@ -367,14 +367,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() // 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() @@ -395,6 +387,14 @@ struct TurnsTests { } 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. From bb4cb42b85fd5f451252d17b57f4731c1f4d4069 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:30:37 +0000 Subject: [PATCH 6/8] Describe how a task that is not yet registered gets its escalation Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLo2UsTkDdhDM9Keiv --- Sources/AsyncQueue/Utilities/Turns.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index dda60e4..7d56a5e 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -243,7 +243,8 @@ 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, the task applies `holderPriority` as its turn begins, or registering + // it does if its turn has already begun. guard let escalate = holder.escalate else { return nil } return { escalate(priority) } } From 731505ec921193acd4e0c3269d078c6866628061 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:32:36 +0000 Subject: [PATCH 7/8] Say when a holder that is not yet registered is escalated to holderPriority Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLo2UsTkDdhDM9Keiv --- Sources/AsyncQueue/Utilities/Turns.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index 7d56a5e..98cbd1c 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -220,7 +220,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 not escalated to this priority until its turn begins, + /// or, if its turn has already begun, until it is registered. var holderPriority: TaskPriority? /// The number of tasks waiting for their turn, by the raw value of their priority. var waitingTaskCounts = [UInt8: Int]() @@ -243,8 +246,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, the task applies `holderPriority` as its turn begins, or registering - // it does if its turn has already begun. + // 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) } } From 521fde0b12ef309e8579621e7204090f96783965 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:38:07 +0000 Subject: [PATCH 8/8] Escalate a registered task as soon as it holds the turn, from a new task The task still escalates itself as its turn begins, in case that new task has not run yet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLo2UsTkDdhDM9Keiv --- Sources/AsyncQueue/Utilities/Turns.swift | 28 +++++++-------- Tests/AsyncQueueTests/TurnsTests.swift | 45 +++++++++++++++++++++--- 2 files changed, 52 insertions(+), 21 deletions(-) diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index 98cbd1c..8d2b0b4 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -137,17 +137,15 @@ final class Turns: Sendable { return nil } ticket.escalate = escalate - // Waiting tasks may have asked to escalate this ticket's task before it was registered. A task that has not - // begun its turn applies those escalations itself as its turn begins. - // A task that has begun its turn and not ended it holds the current turn. - guard ticket.hasBegun else { return nil } - return state.holderPriority + // 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 { - // The task began its turn before it was registered, so its operation may be running. 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. + // 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) } @@ -171,12 +169,12 @@ final class Turns: Sendable { state.removeWaitingTask(at: waitingPriority) ticket.waitingPriority = nil } - ticket.hasBegun = true // 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 `register(escalation:for:)` leaves those - // escalations to the task until its turn begins. + // 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, *) { @@ -222,8 +220,8 @@ final class Turns: Sendable { var holder: Ticket? /// The priority to which waiting tasks have asked to escalate the holder's task. /// - /// A holder's task that is not yet registered is not escalated to this priority until its turn begins, - /// or, if its turn has already begun, until it is registered. + /// 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]() @@ -330,8 +328,6 @@ struct Turn: Sendable { /// 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 begun. - var hasBegun = false /// Whether the turn has ended. var hasEnded = false /// The ticket reserved after this one, while this ticket's turn has not ended. diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index 6dff747..00c4bc4 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -194,16 +194,50 @@ struct TurnsTests { priorityAfterTurnBegan.withLock { $0 = Task.currentPriority } firstTurn.end() } - // The task has not begun its turn, so registering it leaves the escalation to the task. + // 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, and then the waiting task, which takes its turn - // once the first turn ends. + // 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() + 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 (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // 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 { @@ -312,9 +346,10 @@ struct TurnsTests { priorityAfterTurnBegan.withLock { $0 = Task.currentPriority } firstTurn.end() } - // The task has not begun its turn, so registering it leaves the escalations to the task. + // 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, and then the waiting tasks. + // 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