From 779736edf564fc35a31987ce946671d23232807d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 22:19:50 +0000 Subject: [PATCH] Run ActorQueue operations in the task returned to the caller Previously a drain loop created a separate task for each operation and the returned task waited on a continuation for its result. That caused three bugs: - Tasks with different priorities began executing out of order. The drain loop enqueued each operation's task on the adopted actor without waiting for it to start, and a default actor runs higher-priority jobs first, so a later `.high` task overtook an earlier `.low` one. - Operations saw the task-local values bound when the queue was created rather than the caller's. Since `MainActor.queue` is created lazily, it handed its first caller's task-local values to every later caller. - Operations ran at the drain loop's priority rather than the caller's, and 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 become isolated to the adopted actor, and ends its own turn as soon as it is isolated, which lets the next task hop to the actor but not run until the current operation suspends or returns. The queue's `name` named the drain task, which no longer exists, so `ActorQueue(name:)` is removed in favor of `ActorQueue()`. `ManualTaskExecutor` and `ManualSerialExecutor` keep themselves alive while `enqueue(_:)` runs. The runtime calls `enqueue(_:)` without keeping the executor alive. When another thread enqueues the job that lets a test finish, `yield()` resumes the test, and the test can run the job and release the executor before `yield()` returns, so `yield()` would go on to use freed memory. Tests added later in this series crashed this way on Linux about once in 300,000 runs, in `_dispatch_queue_dispose` or in `AsyncStream`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM --- Sources/AsyncQueue/ActorQueue.swift | 165 ++++---------- Sources/AsyncQueue/Utilities/Turns.swift | 126 +++++++++++ Tests/AsyncQueueTests/ActorQueueTests.swift | 213 ++++++++++++++++++ .../Utilities/ManualExecutors.swift | 195 ++++++++++++++++ .../Utilities/TestHelpers.swift | 24 ++ 5 files changed, 606 insertions(+), 117 deletions(-) create mode 100644 Sources/AsyncQueue/Utilities/Turns.swift create mode 100644 Tests/AsyncQueueTests/Utilities/ManualExecutors.swift diff --git a/Sources/AsyncQueue/ActorQueue.swift b/Sources/AsyncQueue/ActorQueue.swift index 9d882ef..45322af 100644 --- a/Sources/AsyncQueue/ActorQueue.swift +++ b/Sources/AsyncQueue/ActorQueue.swift @@ -55,24 +55,7 @@ public final class ActorQueue: @unchecked Sendable { // MARK: Initialization /// Instantiates an actor queue. - /// - Parameter name: Human readable name of the queue. - public init(name: String? = nil) { - let (taskStream, taskStreamContinuation) = AsyncStream.makeStream() - self.taskStreamContinuation = taskStreamContinuation - - Task(name: name) { - // In an ideal world, we would isolate this `for await` loop to the `ActorType`. - // However, there's no good way to do that without retaining the actor and creating a cycle. - for await actorTask in taskStream { - // Await switching to the ActorType context. - await actorTask.task(actorTask.executionContext) - } - } - } - - deinit { - taskStreamContinuation.finish() - } + public init() {} // MARK: Public @@ -87,9 +70,12 @@ public final class ActorQueue: @unchecked Sendable { weakExecutionContext = actor } - // MARK: Fileprivate + // MARK: Internal + + /// Hands out turns to begin executing on the adopted actor, in the order in which tasks are enqueued. + let turns = Turns() - fileprivate let taskStreamContinuation: AsyncStream.Continuation + // MARK: Fileprivate /// The actor on whose isolated context our tasks run, force-unwrapped. /// Utilize this accessor to retrieve the weak execution context in order to avoid repeating the below comment. @@ -100,19 +86,6 @@ public final class ActorQueue: @unchecked Sendable { weakExecutionContext! } - fileprivate struct ActorTask: Sendable { - init( - executionContext: ActorType, - task: @escaping @Sendable (isolated ActorType) async -> Void, - ) { - self.executionContext = executionContext - self.task = task - } - - let executionContext: ActorType - let task: @Sendable (isolated ActorType) async -> Void - } - // MARK: Private /// The actor on whose isolated context our tasks run. @@ -158,26 +131,11 @@ extension Task { on actorQueue: ActorQueue, operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { - let delivery = Delivery() - let semaphore = Semaphore() - let task = ActorQueue.ActorTask( - executionContext: actorQueue.executionContext, - task: { executionContext in - await semaphore.wait() - delivery.execute({ @Sendable executionContext in - await delivery.sendValue(operation(executionContext)) - }, in: executionContext, name: name, priority: priority) - }, - ) - actorQueue.taskStreamContinuation.yield(task) + let executionContext = actorQueue.executionContext + let turn = actorQueue.turns.reserve() self.init(name: name, priority: priority) { - await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + await turn.begin() + return await execute(operation, on: executionContext, endingTurn: turn) } } @@ -215,30 +173,11 @@ extension Task { on actorQueue: ActorQueue, operation: @escaping @Sendable (isolated ActorType) async throws -> Success, ) where Failure == any Error { - let delivery = Delivery() - let semaphore = Semaphore() - let task = ActorQueue.ActorTask( - executionContext: actorQueue.executionContext, - task: { executionContext in - await semaphore.wait() - delivery.execute({ @Sendable executionContext in - do { - try await delivery.sendValue(operation(executionContext)) - } catch { - await delivery.sendFailure(error) - } - }, in: executionContext, name: name, priority: priority) - }, - ) - actorQueue.taskStreamContinuation.yield(task) + let executionContext = actorQueue.executionContext + let turn = actorQueue.turns.reserve() self.init(name: name, priority: priority) { - try await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return try await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + await turn.begin() + return try await execute(operation, on: executionContext, endingTurn: turn) } } @@ -276,26 +215,10 @@ extension Task { on actorQueue: ActorQueue, operation: @MainActor @escaping () async -> Success, ) where Failure == Never { - let delivery = Delivery() - let semaphore = Semaphore() - let task = ActorQueue.ActorTask( - executionContext: actorQueue.executionContext, - task: { executionContext in - await semaphore.wait() - delivery.execute({ @Sendable executionContext in - await delivery.sendValue(operation()) - }, in: executionContext, name: name, priority: priority) - }, - ) - actorQueue.taskStreamContinuation.yield(task) + let turn = actorQueue.turns.reserve() self.init(name: name, priority: priority) { - await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + await turn.begin() + return await executeOnMainActor(operation, endingTurn: turn) } } @@ -333,34 +256,42 @@ extension Task { on actorQueue: ActorQueue, operation: @escaping @MainActor () async throws -> Success, ) where Failure == any Error { - let delivery = Delivery() - let semaphore = Semaphore() - let task = ActorQueue.ActorTask( - executionContext: actorQueue.executionContext, - task: { executionContext in - await semaphore.wait() - delivery.execute({ @Sendable executionContext in - do { - try await delivery.sendValue(operation()) - } catch { - await delivery.sendFailure(error) - } - }, in: executionContext, name: name, priority: priority) - }, - ) - actorQueue.taskStreamContinuation.yield(task) + let turn = actorQueue.turns.reserve() self.init(name: name, priority: priority) { - try await withTaskCancellationHandler( - operation: { - await semaphore.signal() - return try await delivery.getValue() - }, - onCancel: delivery.cancel, - ) + await turn.begin() + return try await executeOnMainActor(operation, endingTurn: turn) } } } +// MARK: - Execution + +/// Executes `operation` on `actor`, ending `turn` as soon as the task is isolated to `actor`. +/// +/// Ending the turn lets the next enqueued task hop to `actor`. That task cannot execute on `actor` +/// until `operation` suspends or returns, so tasks begin executing in the order in which they were enqueued. +private func execute( + _ operation: (isolated ActorType) async throws -> Success, + on actor: isolated ActorType, + endingTurn turn: Turn, +) async rethrows -> Success { + turn.end() + return try await operation(actor) +} + +/// Executes `operation` on the main actor, ending `turn` as soon as the task is isolated to the main actor. +/// +/// Ending the turn lets the next enqueued task hop to the main actor. That task cannot execute on the main actor +/// until `operation` suspends or returns, so tasks begin executing in the order in which they were enqueued. +@MainActor +private func executeOnMainActor( + _ operation: @MainActor () async throws -> Success, + endingTurn turn: Turn, +) async rethrows -> Success { + turn.end() + return try await operation() +} + extension MainActor { /// A global instance of an `ActorQueue`. public static var queue: ActorQueue { diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift new file mode 100644 index 0000000..1c78f82 --- /dev/null +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -0,0 +1,126 @@ +// 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 + +/// Hands out turns in the order in which they are reserved. +/// +/// Each turn begins once every turn reserved before it has ended. +final class Turns: Sendable { + // MARK: Initialization + + init() {} + + // MARK: Internal + + /// Reserves the next turn. + func reserve() -> Turn { + let ended = Signal() + let previousTurnEnded = lastTurnEnded.withLock { lastTurnEnded in + defer { lastTurnEnded = ended } + return lastTurnEnded + } + return Turn(previousTurnEnded: previousTurnEnded, ended: ended) + } + + // MARK: Private + + /// The signal fired when the most recently reserved turn ends. + private let lastTurnEnded = Mutex(nil) +} + +/// A turn reserved from a `Turns` instance. +struct Turn: Sendable { + // MARK: Initialization + + fileprivate init(previousTurnEnded: Signal?, ended: Signal) { + self.previousTurnEnded = previousTurnEnded + self.ended = ended + } + + // MARK: Internal + + /// Suspends until every earlier turn has ended. + /// - Warning: Must be called at most once. + func begin() async { + await previousTurnEnded?.wait() + } + + /// Ends this turn, allowing the next turn to begin. + func end() { + ended.fire() + } + + // MARK: Private + + private let previousTurnEnded: Signal? + private let ended: Signal +} + +// MARK: - Signal + +/// A one-shot latch that a single waiter can await. +private final class Signal: Sendable { + // MARK: Initialization + + init() {} + + // MARK: Internal + + /// 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 + } + // 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. + await withUnsafeContinuation { (continuation: UnsafeContinuation) in + let isFired = state.withLock { state in + if !state.isFired { + state.waiter = continuation + } + return state.isFired + } + if isFired { + continuation.resume() + } + } + } + + // MARK: Private + + private struct State { + var isFired = false + var waiter: UnsafeContinuation? + } + + private let state = Mutex(State()) +} diff --git a/Tests/AsyncQueueTests/ActorQueueTests.swift b/Tests/AsyncQueueTests/ActorQueueTests.swift index 292e212..ba6481c 100644 --- a/Tests/AsyncQueueTests/ActorQueueTests.swift +++ b/Tests/AsyncQueueTests/ActorQueueTests.swift @@ -435,6 +435,203 @@ struct ActorQueueTests { }.value } + @Test + func task_holdsTurnUntilItIsIsolatedToActor() async { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + let task = Task(on: actor.queue) { _ in } + // Wait for the task to hop to the actor, whose executor holds the task's job until the test runs it. + _ = await enqueuedJobs.next() + // The task holds its turn until it is isolated to the actor, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: actor.queue.turns) + let didNextTurnBeginBeforeTaskWasIsolatedToActor = hasNextTurnBegun() + // Running the task's job isolates the task to the actor, which ends its turn. + actor.executor.runUntilIdle() + await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeTaskWasIsolatedToActor) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func throwingTask_holdsTurnUntilItIsIsolatedToActor() async throws { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + let task = Task(on: actor.queue) { _ in try doWork() } + // Wait for the task to hop to the actor, whose executor holds the task's job until the test runs it. + _ = await enqueuedJobs.next() + // The task holds its turn until it is isolated to the actor, so the next turn cannot begin yet. + let hasNextTurnBegun = probeNextTurn(of: actor.queue.turns) + let didNextTurnBeginBeforeTaskWasIsolatedToActor = hasNextTurnBegun() + // Running the task's job isolates the task to the actor, which ends its turn. + actor.executor.runUntilIdle() + try await task.value + let didNextTurnBeginAfterTaskCompleted = hasNextTurnBegun() + #expect(!didNextTurnBeginBeforeTaskWasIsolatedToActor) + #expect(didNextTurnBeginAfterTaskCompleted) + } + + @Test + func mainTask_holdsTurnUntilItIsIsolatedToMainActor() 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) + let executor = ManualTaskExecutor() + // While this closure holds the main actor, the task cannot be isolated to it, so its turn cannot end. + let task = await MainActor.run { + let task = Task(on: mainActorQueue) {} + let nextTurn = mainActorQueue.turns.reserve() + Task(executorPreference: executor) { + await nextTurn.begin() + nextTurn.end() + } + // Run the probe until it waits for its turn. + executor.runUntilIdle() + return task + } + await task.value + executor.runUntilIdle() + // The probe is enqueued when it is created, here on the main actor, and again by whoever ends the task's turn. + // `false` for the second job means that the task's turn ended before the task was isolated to the main actor. + #expect(executor.wasEachJobEnqueuedOnMainQueue == [true, true]) + } + + @Test + func mainThrowingTask_holdsTurnUntilItIsIsolatedToMainActor() async throws { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executor = ManualTaskExecutor() + // While this closure holds the main actor, the task cannot be isolated to it, so its turn cannot end. + let task = await MainActor.run { + let task = Task(on: mainActorQueue) { try doWork() } + let nextTurn = mainActorQueue.turns.reserve() + Task(executorPreference: executor) { + await nextTurn.begin() + nextTurn.end() + } + // Run the probe until it waits for its turn. + executor.runUntilIdle() + return task + } + try await task.value + executor.runUntilIdle() + // The probe is enqueued when it is created, here on the main actor, and again by whoever ends the task's turn. + // `false` for the second job means that the task's turn ended before the task was isolated to the main actor. + #expect(executor.wasEachJobEnqueuedOnMainQueue == [true, true]) + } + + @Test + func task_seesCallersTaskLocalValues() async throws { + // Create the queue while a task-local value is bound: enqueued tasks must see their caller's values instead. + let systemUnderTest = TestTaskLocal.$value.withValue("queue creator") { + ActorQueue() + } + systemUnderTest.adoptExecutionContext(of: counter) + let (value, throwingValue) = try await TestTaskLocal.$value.withValue("caller") { + try await ( + Task(on: systemUnderTest) { _ in TestTaskLocal.value }.value, + Task(on: systemUnderTest) { _ in try doWork(); return TestTaskLocal.value }.value, + ) + } + #expect(value == "caller") + #expect(throwingValue == "caller") + #expect(await Task(on: systemUnderTest) { _ in TestTaskLocal.value }.value == "default") + } + + @Test + func mainTask_seesCallersTaskLocalValues() async throws { + let (value, throwingValue) = try await TestTaskLocal.$value.withValue("caller") { + try await ( + Task(on: MainActor.queue) { TestTaskLocal.value }.value, + Task(on: MainActor.queue) { try doWork(); return TestTaskLocal.value }.value, + ) + } + #expect(value == "caller") + #expect(throwingValue == "caller") + #expect(await Task(on: MainActor.queue) { TestTaskLocal.value }.value == "default") + } + + @Test + func task_withNilPriority_inheritsCallersPriority() 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) + for priority in [TaskPriority.background, .low, .medium, .high] { + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: priority) { [systemUnderTest] report in + Task(on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { [systemUnderTest] report in + Task(on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: priority) { report in + Task(on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == Array(repeating: priority, count: 4)) + } + } + + @Test + func task_withPriority_executesAtThatPriority() async { + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + await Task.detached(priority: .high) { [systemUnderTest] in + // Do not await these tasks: awaiting them from this task would escalate them. + Task(priority: .low, on: systemUnderTest) { _ in + prioritiesContinuation.yield(Task.currentPriority) + } + Task(priority: .low, on: mainActorQueue) { + prioritiesContinuation.yield(Task.currentPriority) + } + }.value + var prioritiesIterator = priorities.makeAsyncIterator() + #expect(await prioritiesIterator.next() == .low) + #expect(await prioritiesIterator.next() == .low) + } + + @Test + func task_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .low, on: systemUnderTest) { _ 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) + } + + @Test + func mainTask_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + // Use a queue of our own rather than `MainActor.queue`: a higher-priority task that a test running in parallel + // enqueues on the shared queue may escalate this task, which would hide whether awaiting this task escalates it. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .low, on: mainActorQueue) { + 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: ActorQueue @@ -443,3 +640,19 @@ struct ActorQueueTests { @Sendable private func doWork() throws {} } + +// MARK: - ManuallyExecutedActor + +/// An actor whose jobs run only when a test calls `executor.runUntilIdle()`. +private actor ManuallyExecutedActor { + init() { + queue.adoptExecutionContext(of: self) + } + + nonisolated let queue = ActorQueue() + nonisolated let executor = ManualSerialExecutor() + + nonisolated var unownedExecutor: UnownedSerialExecutor { + executor.asUnownedSerialExecutor() + } +} diff --git a/Tests/AsyncQueueTests/Utilities/ManualExecutors.swift b/Tests/AsyncQueueTests/Utilities/ManualExecutors.swift new file mode 100644 index 0000000..eb2a531 --- /dev/null +++ b/Tests/AsyncQueueTests/Utilities/ManualExecutors.swift @@ -0,0 +1,195 @@ +// 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 + +@testable import AsyncQueue + +/// A task executor that runs its jobs only when a test calls `runUntilIdle()`. +/// +/// A task that prefers this executor makes progress only while the test runs it, +/// so the test decides exactly when the task runs, and knows when it has suspended. +final class ManualTaskExecutor: TaskExecutor { + // MARK: Initialization + + init() { + (enqueuedJobs, enqueuedJobsContinuation) = AsyncStream.makeStream() + } + + // MARK: Internal + + /// Yields once each time a job is enqueued. + let enqueuedJobs: AsyncStream + + /// 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) } + } + + func enqueue(_ job: consuming ExecutorJob) { + // The caller doesn't keep this executor alive. Once `yield()` resumes the test, the test may run the job to the end + // and release its last reference to this executor before `yield()` returns, so keep the executor alive until this + // method returns. + let retainedSelf = Unmanaged.passRetained(self) + defer { retainedSelf.release() } + let job = UnownedJob(job) + let enqueuedJob = EnqueuedJob( + wasEnqueuedOnMainQueue: Self.mainQueueKey.withLock { DispatchQueue.getSpecific(key: $0) } == true, + ) + state.withLock { state in + state.pendingJobs.append(job) + state.enqueuedJobs.append(enqueuedJob) + } + enqueuedJobsContinuation.yield() + } + + /// Runs every pending job, and every job those jobs enqueue on this executor, until none is pending. + /// + /// The jobs run synchronously, one call at a time. `DispatchQueue.sync` runs them on the calling thread, so a job run + /// from a test's task runs nested inside that task, which the runtime makes current again once the job returns. + func runUntilIdle() { + dispatchQueue.sync { + while let job = state.withLock({ $0.pendingJobs.isEmpty ? nil : $0.pendingJobs.removeFirst() }) { + job.runSynchronously(on: asUnownedTaskExecutor()) + } + } + } + + // MARK: Private + + private struct EnqueuedJob { + let wasEnqueuedOnMainQueue: Bool + } + + private struct State { + var pendingJobs = [UnownedJob]() + var enqueuedJobs = [EnqueuedJob]() + } + + /// A key whose value is `true` on the main dispatch queue, and `nil` on every other queue. + /// A `Mutex` holds the key because it is `Sendable` whether or not `DispatchSpecificKey` is on a given platform. + private static let mainQueueKey = { + let key = DispatchSpecificKey() + DispatchQueue.main.setSpecific(key: key, value: true) + return Mutex(key) + }() + + private let enqueuedJobsContinuation: AsyncStream.Continuation + private let state = Mutex(State()) + private let dispatchQueue = DispatchQueue(label: "ManualTaskExecutor") +} + +/// A serial executor that runs its jobs only when a test calls `runUntilIdle()`. +/// +/// An actor that uses this executor runs nothing until the test runs it, +/// so the test can hold a task that has hopped to the actor before the task executes there. +final class ManualSerialExecutor: SerialExecutor { + // MARK: Initialization + + init() { + (enqueuedJobs, enqueuedJobsContinuation) = AsyncStream.makeStream() + } + + // MARK: Internal + + /// Yields once each time a job is enqueued. + let enqueuedJobs: AsyncStream + + func enqueue(_ job: consuming ExecutorJob) { + // The caller doesn't keep this executor alive. Once `yield()` resumes the test, the test may run the job to the end + // and release its last reference to this executor before `yield()` returns, so keep the executor alive until this + // method returns. + let retainedSelf = Unmanaged.passRetained(self) + defer { retainedSelf.release() } + let job = UnownedJob(job) + pendingJobs.withLock { $0.append(job) } + enqueuedJobsContinuation.yield() + } + + /// Runs every pending job, and every job those jobs enqueue on this executor, until none is pending. + /// + /// The jobs run synchronously, one call at a time. `DispatchQueue.sync` runs them on the calling thread, so a job run + /// from a test's task runs nested inside that task, which the runtime makes current again once the job returns. + func runUntilIdle() { + dispatchQueue.sync { + while let job = pendingJobs.withLock({ $0.isEmpty ? nil : $0.removeFirst() }) { + job.runSynchronously(on: asUnownedSerialExecutor()) + } + } + } + + // MARK: Private + + private let enqueuedJobsContinuation: AsyncStream.Continuation + private let pendingJobs = Mutex<[UnownedJob]>([]) + private let dispatchQueue = DispatchQueue(label: "ManualSerialExecutor") +} + +/// Reserves the next turn of `turns` for a probe task that runs only when a test runs it. +/// +/// A test calls the returned closure to find out whether the turn can begin at a point of the test's choosing: +/// the closure runs the probe until it suspends or completes, so the answer never depends on how the probe is scheduled. +/// - Returns: A closure that runs the probe until it suspends or completes, and returns whether the probe's turn has begun. +func probeNextTurn(of turns: Turns) -> @Sendable () -> Bool { + let executor = ManualTaskExecutor() + let turn = turns.reserve() + let hasTurnBegun = Mutex(false) + Task(executorPreference: executor) { + await turn.begin() + hasTurnBegun.withLock { $0 = true } + turn.end() + } + return { + executor.runUntilIdle() + return hasTurnBegun.withLock(\.self) + } +} + +/// 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 +/// awaits `task`. Awaiting a task escalates it to the awaiting task's priority before the awaiting task suspends. +/// - Parameters: +/// - task: The task whose value to await. +/// - priority: The priority of the awaiting task. +/// - afterEscalating: Runs once the awaiting task awaits `task`, and so once `task` has been escalated. +/// - Returns: The value of `task`, as the awaiting task received it. +func value( + of task: Task, + awaitedFromTaskWithPriority priority: TaskPriority, + afterEscalating: () async -> Void, +) async -> Success { + let executor = ManualTaskExecutor() + var enqueuedJobs = executor.enqueuedJobs.makeAsyncIterator() + let awaitingTask = Task(executorPreference: executor, priority: priority) { + await task.value + } + // Run the awaiting task until it awaits `task`. + await enqueuedJobs.next() + executor.runUntilIdle() + await afterEscalating() + // Completing `task` resumes the awaiting task on the executor. + await enqueuedJobs.next() + executor.runUntilIdle() + return await awaitingTask.value +} diff --git a/Tests/AsyncQueueTests/Utilities/TestHelpers.swift b/Tests/AsyncQueueTests/Utilities/TestHelpers.swift index 506a9f1..8d72cfc 100644 --- a/Tests/AsyncQueueTests/Utilities/TestHelpers.swift +++ b/Tests/AsyncQueueTests/Utilities/TestHelpers.swift @@ -22,6 +22,30 @@ import Dispatch +/// A task-local value that tests use to check which task-local values an enqueued operation sees. +enum TestTaskLocal { + @TaskLocal static var value = "default" +} + +/// Returns the priority at which a task executes when `enqueue` creates it from a task with the given priority. +/// +/// The task is never awaited, since awaiting it would escalate its priority. +/// - Parameters: +/// - enqueuingPriority: The priority of the task that calls `enqueue`. +/// - enqueue: Creates a task that passes its `Task.currentPriority` to `report`. +func priorityOfTask( + enqueuedFromTaskWithPriority enqueuingPriority: TaskPriority, + _ enqueue: @escaping @Sendable (_ report: @escaping @Sendable (TaskPriority) -> Void) -> Void, +) async -> TaskPriority? { + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Do not await this task either: awaiting it would escalate the priority it enqueues from. + Task.detached(priority: enqueuingPriority) { + enqueue { prioritiesContinuation.yield($0) } + } + var prioritiesIterator = priorities.makeAsyncIterator() + return await prioritiesIterator.next() +} + /// Suspends the calling task until it is cancelled. /// /// Returns once the calling task is cancelled. If the task is never cancelled, this function suspends forever, so a