From a442493b6b2144385bae6745e13b4c09355f1ea5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 22:23:33 +0000 Subject: [PATCH] Run FIFOQueue operations in the task returned to the caller Previously each operation ran in a task created by the queue's detached drain loop, and the returned task waited on a continuation for the result. As a result: - Operations never saw the caller's task-local values. - Operations ran at the drain loop's priority rather than the caller's, and three of the four `Task(on:)` initializers dropped `priority` from the returned task. - Awaiting the returned task did not escalate the operation. Now each `Task(on:)` runs its operation in the task it returns, so task-local values, priority, escalation, and cancellation behave as they do for `Task`. Tasks take turns in the order in which they are enqueued: each waits for its predecessor to finish, runs, and then lets its successor begin. A queue's priority is now a floor: a task enqueued with, or from a context with, a lower priority executes at the queue's priority. The comparison uses the priority `Task` would give the new task: the enqueuing task's base priority, ignoring escalation, or outside of a task the thread's priority, which defaults to `.medium`; an inherited user-interactive priority is lowered to user-initiated, and a priority with a raw value of zero counts as no priority. A queue without a priority no longer raises every task to the drain loop's priority. The queue's `name` named the drain task, which no longer exists, so `FIFOQueue(name:priority:)` is removed in favor of `FIFOQueue(priority:)`. Its doc comment is reworded to say plainly which priority each task runs at. `Delivery` is no longer used, so it and its tests are deleted. `Semaphore` is now used only by tests, so it moves to the test target. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM --- Sources/AsyncQueue/FIFOQueue.swift | 170 +++----- Sources/AsyncQueue/Utilities/Delivery.swift | 119 ------ Tests/AsyncQueueTests/ActorQueueTests.swift | 26 +- .../CancellableQueueTests.swift | 23 ++ Tests/AsyncQueueTests/DeliveryTests.swift | 87 ----- Tests/AsyncQueueTests/FIFOQueueTests.swift | 364 +++++++++++++++--- Tests/AsyncQueueTests/SemaphoreTests.swift | 211 +++++----- .../Utilities/Semaphore.swift | 2 +- 8 files changed, 524 insertions(+), 478 deletions(-) delete mode 100644 Sources/AsyncQueue/Utilities/Delivery.swift delete mode 100644 Tests/AsyncQueueTests/DeliveryTests.swift rename {Sources/AsyncQueue => Tests/AsyncQueueTests}/Utilities/Semaphore.swift (93%) diff --git a/Sources/AsyncQueue/FIFOQueue.swift b/Sources/AsyncQueue/FIFOQueue.swift index b22f37a..b8ebc98 100644 --- a/Sources/AsyncQueue/FIFOQueue.swift +++ b/Sources/AsyncQueue/FIFOQueue.swift @@ -26,35 +26,51 @@ public final class FIFOQueue: Sendable { // MARK: Initialization - /// Instantiates a FIFO queue. - /// - Parameter name: Human readable name of the queue. - /// - Parameter priority: The baseline priority of the tasks added to the asynchronous queue. - public init(name: String? = nil, priority: TaskPriority? = nil) { - let (taskStream, taskStreamContinuation) = AsyncStream.makeStream() - self.taskStreamContinuation = taskStreamContinuation - - Task.detached(name: name, priority: priority) { - for await fifoTask in taskStream { - await fifoTask.task() - } - } + /// Creates a FIFO queue. + /// - Parameter priority: The lowest priority at which the queue's tasks run. + /// A task that would run at a lower priority runs at this priority instead. + /// Pass `nil` to run each task at the priority you pass to `Task(on:)`, + /// or, if you pass `nil` there too, at the priority of the code that enqueues it. + public init(priority: TaskPriority? = nil) { + self.priority = priority } - deinit { - taskStreamContinuation.finish() - } + // MARK: Internal + + /// Hands out turns to execute, in the order in which tasks are enqueued. + let turns = Turns() // MARK: Fileprivate - fileprivate struct FIFOTask: Sendable { - init(task: @escaping @Sendable () async -> Void) { - self.task = task + /// Returns the priority with which to create a task that was enqueued with the given priority. + /// - Parameter taskPriority: The priority with which the task was enqueued. `nil` means the priority of the enqueuing context. + fileprivate func priority(forTaskEnqueuedWith taskPriority: TaskPriority?) -> TaskPriority? { + if let priority, Self.priorityOfNewTask(enqueuedWith: taskPriority) < priority { + priority + } else { + // Keep the enqueued priority when it suffices, so that `Task` determines the task's priority itself. + taskPriority } + } - let task: @Sendable () async -> Void + /// Returns the priority that `Task.init(priority:)` gives a task created in the current context with the given priority. + private static func priorityOfNewTask(enqueuedWith taskPriority: TaskPriority?) -> TaskPriority { + // `Task` treats a priority with a raw value of zero as no priority. + if let taskPriority, taskPriority.rawValue != 0 { + return taskPriority + } else { + // Within a task, a new task inherits the task's base priority, not its escalated priority. + // Outside of a task, a new task takes the current thread's priority, or `.medium` if the thread has none. + let inheritedPriority = Task.basePriority ?? Task.currentPriority + guard inheritedPriority.rawValue != 0 else { return .medium } + // `Task` lowers an inherited user-interactive priority to user-initiated, which is `.high`. + return min(inheritedPriority, .high) + } } - fileprivate let taskStreamContinuation: AsyncStream.Continuation + // MARK: Private + + private let priority: TaskPriority? } extension Task { @@ -91,24 +107,11 @@ extension Task { on fifoQueue: FIFOQueue, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success, ) where Failure == Never { - let delivery = Delivery() - let semaphore = Semaphore() - let executeOnce = UnsafeClosureHolder(operation: operation) - let task = FIFOQueue.FIFOTask { - await semaphore.wait() - await delivery.execute({ @Sendable delivery in - await delivery.sendValue(executeOnce.operation()) - }, in: delivery, name: name, priority: priority).value - } - fifoQueue.taskStreamContinuation.yield(task) - self.init(name: name) { - await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let turn = fifoQueue.turns.reserve() + self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + await turn.begin() + defer { turn.end() } + return await operation() } } @@ -145,28 +148,11 @@ extension Task { on fifoQueue: FIFOQueue, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success, ) where Failure == any Error { - let delivery = Delivery() - let semaphore = Semaphore() - let executeOnce = UnsafeThrowingClosureHolder(operation: operation) - let task = FIFOQueue.FIFOTask { - await semaphore.wait() - await delivery.execute({ @Sendable delivery in - do { - try await delivery.sendValue(executeOnce.operation()) - } catch { - delivery.sendFailure(error) - } - }, in: delivery, name: name, priority: priority).value - } - fifoQueue.taskStreamContinuation.yield(task) - self.init(name: name) { - try await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return try await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let turn = fifoQueue.turns.reserve() + self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + await turn.begin() + defer { turn.end() } + return try await operation() } } @@ -206,23 +192,11 @@ extension Task { isolatedTo isolatedActor: ActorType, operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { - let delivery = Delivery() - let semaphore = Semaphore() - let task = FIFOQueue.FIFOTask { - await semaphore.wait() - await delivery.execute({ @Sendable isolatedActor in - await delivery.sendValue(operation(isolatedActor)) - }, in: isolatedActor, name: name, priority: priority).value - } - fifoQueue.taskStreamContinuation.yield(task) - self.init(name: name) { - await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let turn = fifoQueue.turns.reserve() + self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + await turn.begin() + defer { turn.end() } + return await operation(isolatedActor) } } @@ -262,43 +236,11 @@ extension Task { isolatedTo isolatedActor: ActorType, operation: @Sendable @escaping (isolated ActorType) async throws -> Success, ) where Failure == any Error { - let delivery = Delivery() - let semaphore = Semaphore() - let task = FIFOQueue.FIFOTask { - await semaphore.wait() - await delivery.execute({ @Sendable isolatedActor in - do { - try await delivery.sendValue(operation(isolatedActor)) - } catch { - await delivery.sendFailure(error) - } - }, in: isolatedActor, name: name, priority: priority).value - } - fifoQueue.taskStreamContinuation.yield(task) - self.init(name: name, priority: priority) { - try await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return try await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + let turn = fifoQueue.turns.reserve() + self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + await turn.begin() + defer { turn.end() } + return try await operation(isolatedActor) } } } - -private struct UnsafeClosureHolder: @unchecked Sendable { - init(operation: sending @escaping @isolated(any) () async -> Success) { - self.operation = operation - } - - let operation: @isolated(any) () async -> Success -} - -private struct UnsafeThrowingClosureHolder: @unchecked Sendable { - init(operation: sending @escaping @isolated(any) () async throws -> Success) { - self.operation = operation - } - - let operation: @isolated(any) () async throws -> Success -} diff --git a/Sources/AsyncQueue/Utilities/Delivery.swift b/Sources/AsyncQueue/Utilities/Delivery.swift deleted file mode 100644 index 7a658eb..0000000 --- a/Sources/AsyncQueue/Utilities/Delivery.swift +++ /dev/null @@ -1,119 +0,0 @@ -// MIT License -// -// Copyright (c) 2025 Dan Federman -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -import Synchronization - -actor Delivery { - func sendValue(_ value: Success) { - self.value = value - } - - func sendFailure(_ failure: Failure) { - self.failure = failure - } - - nonisolated func cancel() { - let task = taskContainer.withLock { - $0.isCancelled = true - return $0.task - } - // Cancelling a task synchronously runs its cancellation handlers, which may cancel other tasks. - // Cancel only after releasing the lock so that those handlers can never re-enter it. - task?.cancel() - } - - @discardableResult - func execute( - _ operation: sending @escaping (isolated ActorType) async -> Void, - in context: isolated ActorType, - name: String?, - priority: TaskPriority?, - ) -> Task { - // In Swift 6, a `Task` enqueued from an actor begins executing immediately on that actor. - // Since we're running on our actor's context already, we can just dispatch a Task to get first-enqueued-first-start task execution. - let task = Task(name: name, priority: priority) { - await operation(context) - } - let isCancelled = taskContainer.withLock { - $0.task = task - return $0.isCancelled - } - if isCancelled { - // Cancel only after releasing the lock. See `cancel()`. - task.cancel() - } - return task - } - - private var value: Success? { - didSet { - if let value { - valueContinuations.forEach { $0.resume(returning: value) } - valueContinuations.removeAll() - } - } - } - - private var failure: Failure? { - didSet { - if let failure { - valueContinuations.forEach { $0.resume(throwing: failure) } - valueContinuations.removeAll() - } - } - } - - private var valueContinuations: [UnsafeContinuation] = [] - /// Never cancel a task while holding this lock: cancellation handlers run synchronously and may cancel other tasks. - private let taskContainer = Mutex(TaskContainer()) - - struct TaskContainer { - var task: Task? - var isCancelled = false - } -} - -extension Delivery where Failure == Never { - func getValue() async -> Success { - if let value { - value - } else { - await withUnsafeContinuation { continuation in - valueContinuations.append(continuation) - } - } - } -} - -extension Delivery where Failure == any Error { - func getValue() async throws -> Success { - if let value { - value - } else if let failure { - throw failure - } else { - try await withUnsafeThrowingContinuation { continuation in - valueContinuations.append(continuation) - } - } - } -} diff --git a/Tests/AsyncQueueTests/ActorQueueTests.swift b/Tests/AsyncQueueTests/ActorQueueTests.swift index ba6481c..4305167 100644 --- a/Tests/AsyncQueueTests/ActorQueueTests.swift +++ b/Tests/AsyncQueueTests/ActorQueueTests.swift @@ -156,8 +156,8 @@ struct ActorQueueTests { @Test func task_startsExecutionOfNextTaskAfterSuspension() async { - let systemUnderTest = ActorQueue() - let semaphore = AsyncQueue.Semaphore() + let systemUnderTest = ActorQueue() + let semaphore = Semaphore() systemUnderTest.adoptExecutionContext(of: semaphore) let firstTask = Task(on: systemUnderTest) { semaphore in @@ -174,8 +174,8 @@ struct ActorQueueTests { @Test func throwingTask_startsExecutionOfNextTaskAfterSuspension() async throws { - let systemUnderTest = ActorQueue() - let semaphore = AsyncQueue.Semaphore() + let systemUnderTest = ActorQueue() + let semaphore = Semaphore() systemUnderTest.adoptExecutionContext(of: semaphore) let firstTask = Task(on: systemUnderTest) { semaphore in @@ -243,7 +243,7 @@ struct ActorQueueTests { var systemUnderTest: ActorQueue? = ActorQueue() systemUnderTest?.adoptExecutionContext(of: counter) - let semaphore = AsyncQueue.Semaphore() + let semaphore = Semaphore() let task = try Task(on: #require(systemUnderTest)) { counter in // Make the task wait. await semaphore.wait() @@ -265,7 +265,7 @@ struct ActorQueueTests { var systemUnderTest: ActorQueue? = ActorQueue() systemUnderTest?.adoptExecutionContext(of: counter) - let semaphore = AsyncQueue.Semaphore() + let semaphore = Semaphore() let task = try Task(on: #require(systemUnderTest)) { counter in try doWork() @@ -334,20 +334,6 @@ struct ActorQueueTests { try? await task.value } - @MainActor - @Test - func mainTask_cancelledWhileMainActorIsBusy_executesOperationCancelled() async { - let task = Task(on: MainActor.queue) { - Task.isCancelled - } - - // The task's operation cannot begin until this test suspends and frees the main actor, - // so this cancels the task before its operation begins. - task.cancel() - - #expect(await task.value) - } - @Test func task_canBeCancelledFromCancellationHandlerOfAnotherQueuedTask() async { let taskStarted = Semaphore() diff --git a/Tests/AsyncQueueTests/CancellableQueueTests.swift b/Tests/AsyncQueueTests/CancellableQueueTests.swift index 6905a8e..cbf1a29 100644 --- a/Tests/AsyncQueueTests/CancellableQueueTests.swift +++ b/Tests/AsyncQueueTests/CancellableQueueTests.swift @@ -699,6 +699,29 @@ struct CancellableQueueTests { #expect(!task.isCancelled) } + @Test + func task_seesCallersTaskLocalValues() async throws { + let fifoQueue = CancellableQueue(underlyingQueue: FIFOQueue()) + let actorQueue = ActorQueue() + let counter = Counter() + actorQueue.adoptExecutionContext(of: counter) + let cancellableActorQueue = CancellableQueue(underlyingQueue: actorQueue) + let cancellableMainActorQueue = CancellableQueue(underlyingQueue: MainActor.queue) + let values = try await TestTaskLocal.$value.withValue("caller") { + try await [ + Task(on: fifoQueue) { TestTaskLocal.value }.value, + Task(on: fifoQueue) { try doWork(); return TestTaskLocal.value }.value, + Task(on: fifoQueue, isolatedTo: counter) { _ in TestTaskLocal.value }.value, + Task(on: fifoQueue, isolatedTo: counter) { _ in try doWork(); return TestTaskLocal.value }.value, + Task(on: cancellableActorQueue) { _ in TestTaskLocal.value }.value, + Task(on: cancellableActorQueue) { _ in try doWork(); return TestTaskLocal.value }.value, + Task(on: cancellableMainActorQueue) { TestTaskLocal.value }.value, + Task(on: cancellableMainActorQueue) { try doWork(); return TestTaskLocal.value }.value, + ] + } + #expect(values == Array(repeating: "caller", count: 8)) + } + // MARK: Private private struct TestError: Error {} diff --git a/Tests/AsyncQueueTests/DeliveryTests.swift b/Tests/AsyncQueueTests/DeliveryTests.swift deleted file mode 100644 index 0a451d1..0000000 --- a/Tests/AsyncQueueTests/DeliveryTests.swift +++ /dev/null @@ -1,87 +0,0 @@ -// MIT License -// -// Copyright (c) 2025 Dan Federman -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -import Foundation -import Testing - -@testable import AsyncQueue - -struct DeliveryTests { - // MARK: Behavior Tests - - @Test - func getValue_whenValueExists() async { - let systemUnderTest = Delivery() - await systemUnderTest.sendValue(true) - await #expect(systemUnderTest.getValue() == true) - } - - @Test - func getValueThrowing_whenValueExists() async throws { - let systemUnderTest = Delivery() - await systemUnderTest.sendValue(true) - try await #expect(systemUnderTest.getValue() == true) - } - - @Test - func getValueThrowing_whenFailureExists() async throws { - let systemUnderTest = Delivery() - await systemUnderTest.sendFailure(CancellationError()) - await #expect(throws: CancellationError.self, performing: { - try await systemUnderTest.getValue() - }) - } - - @Test - func getValue_whenValueIsSentAfterGetValueSuspends() async { - let systemUnderTest = Delivery() - await #expect(valueOnceGetValueSuspends(on: systemUnderTest) == true) - } - - @Test - func getValueThrowing_whenFailureIsSentAfterGetValueSuspends() async throws { - let systemUnderTest = Delivery() - await #expect(throws: CancellationError.self, performing: { - try await valueOnceGetValueSuspends(on: systemUnderTest) - }) - } - - // MARK: Private - - /// Sends `true` to the delivery once `getValue()` suspends, and returns the value that `getValue()` returns. - private func valueOnceGetValueSuspends(on delivery: isolated Delivery) async -> Bool { - // This task is isolated to the delivery, which this function occupies until `getValue()` suspends. - Task { - delivery.sendValue(true) - } - return await delivery.getValue() - } - - /// Sends a `CancellationError` to the delivery once `getValue()` suspends, and returns the value that `getValue()` returns. - private func valueOnceGetValueSuspends(on delivery: isolated Delivery) async throws -> Bool { - // This task is isolated to the delivery, which this function occupies until `getValue()` suspends. - Task { - delivery.sendFailure(CancellationError()) - } - return try await delivery.getValue() - } -} diff --git a/Tests/AsyncQueueTests/FIFOQueueTests.swift b/Tests/AsyncQueueTests/FIFOQueueTests.swift index b506139..1613ddd 100644 --- a/Tests/AsyncQueueTests/FIFOQueueTests.swift +++ b/Tests/AsyncQueueTests/FIFOQueueTests.swift @@ -212,21 +212,6 @@ struct FIFOQueueTests { await Task(on: systemUnderTest) { /* Drain the queue */ }.value } - @Test - func taskIsolatedTo_isNotReentrant() async { - let counter = Counter() - Task(on: systemUnderTest, isolatedTo: counter) { [systemUnderTest] counter in - Task(on: systemUnderTest, isolatedTo: counter) { counter in - counter.incrementAndExpectCount(equals: 2) - } - counter.incrementAndExpectCount(equals: 1) - Task(on: systemUnderTest, isolatedTo: counter) { counter in - counter.incrementAndExpectCount(equals: 3) - } - } - await Task(on: systemUnderTest) { /* Drain the queue */ }.value - } - @Test func throwingTask_isNotReentrant() async { let counter = Counter() @@ -244,23 +229,6 @@ struct FIFOQueueTests { await Task(on: systemUnderTest) { /* Drain the queue */ }.value } - @Test - func throwingTaskIsolatedTo_isNotReentrant() async throws { - let counter = Counter() - Task(on: systemUnderTest, isolatedTo: counter) { [systemUnderTest] counter in - Task(on: systemUnderTest, isolatedTo: counter) { counter in - counter.incrementAndExpectCount(equals: 2) - try doWork() - } - counter.incrementAndExpectCount(equals: 1) - Task(on: systemUnderTest, isolatedTo: counter) { counter in - counter.incrementAndExpectCount(equals: 3) - try doWork() - } - } - await Task(on: systemUnderTest) { /* Drain the queue */ }.value - } - @Test func task_executesAfterQueueIsDeallocated() async throws { var systemUnderTest: FIFOQueue? = FIFOQueue() @@ -415,23 +383,6 @@ struct FIFOQueueTests { try? await task.value } - @Test - func task_cancelledWhileWaitingForPriorTask_executesOperationCancelled() async { - let priorTaskAllowedToEnd = Semaphore() - Task(on: systemUnderTest) { - await priorTaskAllowedToEnd.wait() - } - let task = Task(on: systemUnderTest) { - Task.isCancelled - } - - // The task's operation cannot begin until the prior task ends, so this cancels the task before its operation begins. - task.cancel() - await priorTaskAllowedToEnd.signal() - - #expect(await task.value) - } - @Test func task_canBeCancelledFromCancellationHandlerOfAnotherQueuedTask() async { let otherQueue = FIFOQueue() @@ -519,6 +470,321 @@ struct FIFOQueueTests { } } + @Test + func throwingTask_whenOperationThrows_allowsNextTaskToBegin() async { + struct TestError: Error {} + let task = Task(on: systemUnderTest) { throw TestError() } + // Reserve the turn after the task's turn, as the next task enqueued on the queue would. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + await #expect(throws: TestError.self) { try await task.value } + // The task ended its turn when its operation threw, so the next turn begins without waiting. + #expect(hasNextTurnBegun()) + } + + @Test + func throwingTaskIsolatedTo_whenOperationThrows_allowsNextTaskToBegin() async { + struct TestError: Error {} + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in throw TestError() } + // Reserve the turn after the task's turn, as the next task enqueued on the queue would. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + await #expect(throws: TestError.self) { try await task.value } + // The task ended its turn when its operation threw, so the next turn begins without waiting. + #expect(hasNextTurnBegun()) + } + + @Test + func task_holdsTurnUntilItsOperationReturns() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task holds its turn until its operation returns, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + let didNextTurnBeginBeforeOperationReturned = hasNextTurnBegun() + await operationAllowedToReturn.signal() + await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeOperationReturned) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func throwingTask_holdsTurnUntilItsOperationReturns() async throws { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { + await operationStarted.signal() + await operationAllowedToReturn.wait() + try doWork() + } + await operationStarted.wait() + // The task holds its turn until its operation returns, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + let didNextTurnBeginBeforeOperationReturned = hasNextTurnBegun() + await operationAllowedToReturn.signal() + try await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeOperationReturned) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func taskIsolatedTo_holdsTurnUntilItsOperationReturns() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task holds its turn until its operation returns, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + let didNextTurnBeginBeforeOperationReturned = hasNextTurnBegun() + await operationAllowedToReturn.signal() + await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeOperationReturned) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func throwingTaskIsolatedTo_holdsTurnUntilItsOperationReturns() async throws { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in + await operationStarted.signal() + await operationAllowedToReturn.wait() + try doWork() + } + await operationStarted.wait() + // The task holds its turn until its operation returns, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: systemUnderTest.turns) + let didNextTurnBeginBeforeOperationReturned = hasNextTurnBegun() + await operationAllowedToReturn.signal() + try await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeOperationReturned) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func task_seesCallersTaskLocalValues() async throws { + let systemUnderTest = TestTaskLocal.$value.withValue("queue creator") { + FIFOQueue() + } + let values = try await TestTaskLocal.$value.withValue("caller") { + try await [ + Task(on: systemUnderTest) { TestTaskLocal.value }.value, + Task(on: systemUnderTest) { try doWork(); return TestTaskLocal.value }.value, + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in TestTaskLocal.value }.value, + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in try doWork(); return TestTaskLocal.value }.value, + ] + } + #expect(values == Array(repeating: "caller", count: 4)) + #expect(await Task(on: systemUnderTest) { TestTaskLocal.value }.value == "default") + } + + @Test + func task_withNilPriority_inheritsCallersPriority() async { + let systemUnderTest = await Task.detached(priority: .background) { FIFOQueue() }.value + for priority in [TaskPriority.background, .low, .medium, .high] { + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: systemUnderTest) { try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == Array(repeating: priority, count: 4)) + } + } + + @Test + func task_withPriority_executesAtThatPriority() async { + for priority in [TaskPriority.background, .low, .medium, .high] { + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest) { try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest, isolatedTo: Counter()) { _ in try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == Array(repeating: priority, count: 4)) + } + } + + @Test + func task_onQueueWithPriority_withLowerPriority_executesAtQueuePriority() async { + let systemUnderTest = FIFOQueue(priority: .medium) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.medium, .medium]) + } + + @Test + func task_onQueueWithPriority_withHigherPriority_executesAtThatPriority() async { + let systemUnderTest = FIFOQueue(priority: .medium) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.high, .high]) + } + + @Test + func task_onQueueWithPriority_withNilPriority_executesAtHigherOfCallersAndQueuePriority() async { + let systemUnderTest = FIFOQueue(priority: .medium) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: systemUnderTest) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: systemUnderTest, isolatedTo: Counter()) { _ in report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.medium, .high, .medium, .high]) + } + + @Test + func task_onQueueWithPriority_enqueuedFromEscalatedTaskWithLowerBasePriority_executesAtQueuePriority() async { + let systemUnderTest = FIFOQueue(priority: .medium) + let enqueuingTaskAllowedToEnqueue = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + let enqueuingTask = Task.detached(priority: .background) { + // Wait for a higher-priority task to escalate this task above the queue's priority. + await enqueuingTaskAllowedToEnqueue.wait() + // Do not await the enqueued task: awaiting it would escalate it. + Task(on: systemUnderTest) { + prioritiesContinuation.yield(Task.currentPriority) + } + } + await value(of: enqueuingTask, awaitedFromTaskWithPriority: .high) { + await enqueuingTaskAllowedToEnqueue.signal() + } + var prioritiesIterator = priorities.makeAsyncIterator() + let executionPriority = await prioritiesIterator.next() + #expect(executionPriority == .medium) + } + + @Test + func task_onQueueWithPriority_enqueuedOutsideOfAnyTask_executesAtHigherOfNewTaskAndQueuePriority() async { + // Threads without a quality of service take the default branch; threads with one, on platforms that support it, do not. + for qualityOfService in [QualityOfService.default, .userInitiated, .utility] { + for queuePriority in [TaskPriority.background, .low, .medium, .high] { + let systemUnderTest = FIFOQueue(priority: queuePriority) + let (priorities, prioritiesContinuation) = AsyncStream<(isEnqueued: Bool, priority: TaskPriority)>.makeStream() + // Enqueue from a thread that is not running a task, and create a plain task there for comparison. + let thread = Thread { + Task { + prioritiesContinuation.yield((isEnqueued: false, priority: Task.currentPriority)) + } + Task(on: systemUnderTest) { + prioritiesContinuation.yield((isEnqueued: true, priority: Task.currentPriority)) + } + } + thread.qualityOfService = qualityOfService + thread.start() + var plainTaskPriority: TaskPriority? + var executionPriority: TaskPriority? + // The thread reports exactly two priorities: one from each task. + for await (isEnqueued, priority) in priorities.prefix(2) { + if isEnqueued { + executionPriority = priority + } else { + plainTaskPriority = priority + } + } + #expect(plainTaskPriority.map { executionPriority == max($0, queuePriority) } == true) + } + } + } + + @Test + func task_onQueueWithPriority_withUnspecifiedPriority_executesAtHigherOfCallersAndQueuePriority() async { + let systemUnderTest = FIFOQueue(priority: .low) + // `Task` treats a priority with a raw value of zero as no priority, so the task inherits the caller's priority. + let executionPriority = await priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: TaskPriority(rawValue: 0), on: systemUnderTest) { report(Task.currentPriority) } + } + #expect(executionPriority == .high) + } + + @Test + func task_onQueueWithUserInteractivePriority_enqueuedFromUserInteractiveTask_executesAtQueuePriority() async { + let userInteractivePriority = TaskPriority(rawValue: 0x21) + let systemUnderTest = FIFOQueue(priority: userInteractivePriority) + // `Task` lowers an inherited user-interactive priority, so only the queue's priority keeps the task user-interactive. + let executionPriority = await priorityOfTask(enqueuedFromTaskWithPriority: userInteractivePriority) { report in + Task(on: systemUnderTest) { report(Task.currentPriority) } + } + #expect(executionPriority.map { $0 >= userInteractivePriority } == true) + } + + @Test + func task_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .low, on: systemUnderTest) { + await taskStarted.signal() + await taskAllowedToReturn.wait() + return Task.currentPriority + } + await taskStarted.wait() + let priority = await value(of: task, awaitedFromTaskWithPriority: .high) { + await taskAllowedToReturn.signal() + } + #expect(priority >= .high) + } + + @Test + func taskIsolatedTo_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .low, on: systemUnderTest, isolatedTo: Counter()) { _ in + await taskStarted.signal() + await taskAllowedToReturn.wait() + return Task.currentPriority + } + await taskStarted.wait() + let priority = await value(of: task, awaitedFromTaskWithPriority: .high) { + await taskAllowedToReturn.signal() + } + #expect(priority >= .high) + } + // MARK: Private private let systemUnderTest = FIFOQueue() diff --git a/Tests/AsyncQueueTests/SemaphoreTests.swift b/Tests/AsyncQueueTests/SemaphoreTests.swift index c5940db..8300041 100644 --- a/Tests/AsyncQueueTests/SemaphoreTests.swift +++ b/Tests/AsyncQueueTests/SemaphoreTests.swift @@ -20,122 +20,157 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. +import Synchronization import Testing @testable import AsyncQueue -final class SemaphoreTests { - // MARK: Initialization +struct SemaphoreTests { + // MARK: Behavior Tests - deinit { - Task { [systemUnderTest] in - let isWaiting = await systemUnderTest.isWaiting - #expect(!isWaiting) - } - } + @Test + func signal_whenSignalCallsReachSuspendedWaitCalls_resumesEveryWaiterAtOnce() async { + let waiters = (1...3).map { _ in Waiter(on: systemUnderTest, executor: executor) } + executor.runUntilIdle() + // No `signal()` call matches any of the three `wait()` calls, so every waiter suspends. + #expect(waiters.map(\.result) == [nil, nil, nil]) - // MARK: Behavior Tests + await systemUnderTest.signal() + executor.runUntilIdle() + // Two `wait()` calls are still unmatched, so every waiter is still suspended. + #expect(waiters.map(\.result) == [nil, nil, nil]) + let isWaitingAfterFirstSignal = await systemUnderTest.isWaiting + #expect(isWaitingAfterFirstSignal) + + await systemUnderTest.signal() + executor.runUntilIdle() + // One `wait()` call is still unmatched, so every waiter is still suspended. + #expect(waiters.map(\.result) == [nil, nil, nil]) + let isWaitingAfterSecondSignal = await systemUnderTest.isWaiting + #expect(isWaitingAfterSecondSignal) + + await systemUnderTest.signal() + executor.runUntilIdle() + // Every `wait()` call is matched, so every waiter has resumed. + #expect(waiters.map(\.result) == [true, true, true]) + let isWaitingAfterThirdSignal = await systemUnderTest.isWaiting + #expect(!isWaitingAfterThirdSignal) + } @Test - func wait_suspendsUntilEqualNumberOfSignalCalls() async { - /* - This test is tricky to pull off! - Our requirements: - 1. We need to call `wait()` before `signal()` - 2. We need to ensure that the `wait()` call suspends _before_ we call `signal()` - 3. We can't `await` the `wait()` call on the test's queue before calling `signal()` since that would deadlock the test. - 4. We must utilize a single actor's isolated context to avoid accidental interleaving when suspending to communicate across actor contexts. - - In order to ensure that we are executing the `wait()` calls before we call `signal()` _without awaiting a `wait()` call_, - we utilize the AsyncQueue.Semaphore's ordered execution context to enqueue ordered `Task`s similar to how an ActorQueue works. - */ - - let iterationCount = 1_000 - /// A counter that will only be accessed from within the `systemUnderTest`'s context - let unsafeCounter = UnsafeCounter() - - for _ in 1...iterationCount { - await systemUnderTest.enqueueAndCount(using: unsafeCounter) { systemUnderTest in - let didSuspend = await systemUnderTest.wait() - #expect(didSuspend) - - return { systemUnderTest in - // Signal that the suspended wait call above has resumed. - // This signal allows us to `wait()` for all of these enqueued `wait()` tasks to have completed later in this test. - systemUnderTest.signal() - } - } + func signal_whenSignalCallsReachAThousandSuspendedWaitCalls_resumesEveryWaiterAtOnce() async { + let waiterCount = 1_000 + let waiters = (1...waiterCount).map { _ in Waiter(on: systemUnderTest, executor: executor) } + executor.runUntilIdle() + // No `signal()` call matches any of the `wait()` calls, so every waiter suspends. + #expect(waiters.allSatisfy { $0.result == nil }) + + for _ in 1.. (@Sendable (isolated AsyncQueue.Semaphore) -> Void)?) async { - // Await the start of the soon-to-be-enqueued `Task` with a continuation. - await withCheckedContinuation { continuation in - // Re-enter the semaphore's ordered context but don't wait for the result. - Task { - // Now that we're back in the semaphore's ordered context, allow the calling code to resume. - continuation.resume() - let executeAfterIncrement = await task(self) - counter.countedTasksCompleted += 1 - executeAfterIncrement?(self) - } +// MARK: - Waiter + +/// A task that calls `wait()` on a semaphore, and that runs only when a test runs its executor. +/// +/// Calls into the semaphore, a default actor, run on the executor that the calling task prefers. So once a test runs +/// the executor until it is idle, every waiter has either returned from `wait()` or is suspended in it. +private final class Waiter: Sendable { + // MARK: Initialization + + init(on semaphore: Semaphore, executor: ManualTaskExecutor) { + Task(executorPreference: executor) { + let didSuspend = await semaphore.wait() + self.waitResult.withLock { $0 = didSuspend } } } - fileprivate func execute(_ task: @Sendable (isolated AsyncQueue.Semaphore) async throws -> Void) async rethrows { - try await task(self) + // MARK: Internal + + /// What `wait()` returned, which is whether it suspended, or `nil` while `wait()` has not returned. + var result: Bool? { + waitResult.withLock(\.self) } -} -// MARK: - UnsafeCounter + // MARK: Private -private final class UnsafeCounter: @unchecked Sendable { - var countedTasksCompleted = 0 + private let waitResult = Mutex(nil) } diff --git a/Sources/AsyncQueue/Utilities/Semaphore.swift b/Tests/AsyncQueueTests/Utilities/Semaphore.swift similarity index 93% rename from Sources/AsyncQueue/Utilities/Semaphore.swift rename to Tests/AsyncQueueTests/Utilities/Semaphore.swift index 7b3034b..f8d45c1 100644 --- a/Sources/AsyncQueue/Utilities/Semaphore.swift +++ b/Tests/AsyncQueueTests/Utilities/Semaphore.swift @@ -44,7 +44,7 @@ actor Semaphore { return true } - /// Increment the counting semaphore. If the previous value was less than zero, this function resumes a waiting thread before returning. + /// Increment the counting semaphore. If the resulting value is greater than or equal to zero, this function resumes every waiting task before returning. func signal() { count += 1 guard !isWaiting else {