From a5a502a9b09678c5bb09a2f7b21fab9264a3512d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 17:41:42 +0000 Subject: [PATCH] Add isIdle to ActorQueue and FIFOQueue Code that keeps one queue per key creates each queue on demand, and needs to know when it can remove a queue without breaking the order of the work enqueued on it. `isIdle` tells it. - `FIFOQueue.isIdle` is true when every task enqueued on the queue has finished: its operation has returned or thrown. A task that is suspended at an `await` hasn't finished, and neither has a cancelled task, which keeps its place and whose operation still runs. - `ActorQueue.isIdle` is true when every task enqueued on the queue has started running on the actor, so the operations of its tasks might not have finished. `MainActor.queue` gets it as an `ActorQueue`. A task counts from the moment `Task(on:)` enqueues it, before `Task(on:)` returns, and the value can change as soon as it is read. If one actor enqueues every task on a queue, it can read `isIdle` and then remove an idle queue, without suspending between the read and the removal: no task can be enqueued in between. For a `FIFOQueue`, work enqueued afterward on a new queue then runs after every task on the removed queue. The documentation and a new README section show this with an actor that keeps one `FIFOQueue` per document. The property adds no state and no work to the enqueue path. `Turns` already records the most recently reserved ticket, and a turn ends only after every earlier turn has ended, so `Turns.isIdle` reads `lastTicket?.hasEnded ?? true` under the lock that `reserve()` and `end()` take. `CancellableQueue` gets no `isIdle`. The caller creates the queue it wraps, so the caller can keep a reference to that queue and read its `isIdle`. The tests force each ordering with semaphores, an actor whose executor runs only when the test runs it, or by holding the main actor. They cover a new queue, a task that was just enqueued, a suspended operation in each of the four `FIFOQueue` initializers, a cancelled `FIFOQueue` task, several tasks, and an `ActorQueue` whose last operation hasn't finished, including on the main actor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM --- README.md | 37 ++++++ Sources/AsyncQueue/ActorQueue.swift | 15 +++ Sources/AsyncQueue/FIFOQueue.swift | 44 +++++++ Sources/AsyncQueue/Utilities/Turns.swift | 7 + Tests/AsyncQueueTests/ActorQueueTests.swift | 102 ++++++++++++++ Tests/AsyncQueueTests/FIFOQueueTests.swift | 139 ++++++++++++++++++++ Tests/AsyncQueueTests/TurnsTests.swift | 53 ++++++++ 7 files changed, 397 insertions(+) diff --git a/README.md b/README.md index 094a103..8411362 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,43 @@ Task(on: cancellableQueue) { } ``` +## Checking whether a queue is idle + +A `FIFOQueue` and an `ActorQueue` each have an `isIdle` property: + +- A `FIFOQueue` is idle when every task you enqueued on it has finished. A task that is suspended at an `await` hasn't finished. Neither has a cancelled task: it keeps its place, and its operation still runs. +- An `ActorQueue` is idle when every task you enqueued on it has started running on the actor. The operations of its tasks might not have finished. + +The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again. + +For example, here's how an actor that keeps one `FIFOQueue` per document might remove the queues it no longer needs: + +```swift +actor DocumentStore { + func save(_ contents: String, as name: String) -> Task { + let queue = queues[name] ?? FIFOQueue() + queues[name] = queue + return Task(on: queue) { + await self.write(contents, as: name) + } + } + + func removeIdleQueues() { + queues = queues.filter { !$0.value.isIdle } + } + + private func write(_ contents: String, as name: String) async { + // Write implementation… + } + + private var queues = [String: FIFOQueue]() +} +``` + +In the code above, the actor enqueues every task and reads `isIdle`, and it doesn't suspend between reading `isIdle` and removing the queue. So no task can be enqueued in between. A document you save after its queue is removed gets a new queue, and its task runs after the tasks of the removed queue, which have all finished. + +`CancellableQueue` has no `isIdle` property. To check one, keep a reference to the queue it wraps, and read that queue's `isIdle`. + ## Task-local values, priority, and cancellation `Task(on:)` creates a new [unstructured task](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Unstructured-Concurrency), as `Task.init` does, and your operation runs in that task. So the task behaves like a task you create with `Task.init`. diff --git a/Sources/AsyncQueue/ActorQueue.swift b/Sources/AsyncQueue/ActorQueue.swift index 97a7ceb..a947a8e 100644 --- a/Sources/AsyncQueue/ActorQueue.swift +++ b/Sources/AsyncQueue/ActorQueue.swift @@ -70,6 +70,21 @@ public final class ActorQueue: @unchecked Sendable { weakExecutionContext = actor } + /// Whether every task you enqueued on this queue has started running on the actor. + /// + /// A task counts from the moment you enqueue it until it starts running on the actor. + /// So the queue can be idle while the operations of its tasks haven't finished. + /// A task runs alongside the code that enqueues it, so the task might start running on the actor before that code reads this property. + /// If that code is running on the actor, though, the task can't start running there until the code suspends or returns. + /// + /// The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again. + /// If one actor enqueues every task on the queue, that actor can read this property and then remove an idle queue + /// without suspending between the read and the removal. + /// No task can be enqueued in between, so every task enqueued on the removed queue has started running on the queue's actor. + public var isIdle: Bool { + turns.isIdle + } + // MARK: Internal /// Hands out turns to begin executing on the adopted actor, in the order in which tasks are enqueued. diff --git a/Sources/AsyncQueue/FIFOQueue.swift b/Sources/AsyncQueue/FIFOQueue.swift index 8de755b..702b6f9 100644 --- a/Sources/AsyncQueue/FIFOQueue.swift +++ b/Sources/AsyncQueue/FIFOQueue.swift @@ -38,6 +38,50 @@ public final class FIFOQueue: Sendable { self.priority = priority } + // MARK: Public + + /// Whether every task you enqueued on this queue has finished. + /// + /// A task counts from the moment you enqueue it until its operation returns or throws. + /// A task that is suspended at an `await` hasn't finished, + /// so an operation that reads this property on its own queue always reads `false`. + /// A cancelled task hasn't finished either: it keeps its place in the queue, and its operation still runs. + /// A task runs alongside the code that enqueues it, so the task might finish before that code reads this property. + /// If the task's operation needs an actor that the code is running on, though, + /// the task can't finish until the code suspends or returns. + /// + /// The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again. + /// If one actor enqueues every task on the queue, that actor can read this property and then safely remove an idle queue, + /// without suspending between the read and the removal. + /// No task can be enqueued in between, and a task that the actor enqueues afterward on a new queue + /// runs after every task on the removed queue, because they have all finished. + /// For example, an actor that keeps one queue per document can remove the queues of documents whose work has finished: + /// + /// ```swift + /// actor DocumentStore { + /// func save(_ contents: String, as name: String) -> Task { + /// let queue = queues[name] ?? FIFOQueue() + /// queues[name] = queue + /// return Task(on: queue) { + /// await self.write(contents, as: name) + /// } + /// } + /// + /// func removeIdleQueues() { + /// queues = queues.filter { !$0.value.isIdle } + /// } + /// + /// private func write(_ contents: String, as name: String) async { + /// // Write implementation… + /// } + /// + /// private var queues = [String: FIFOQueue]() + /// } + /// ``` + public var isIdle: Bool { + turns.isIdle + } + // MARK: Internal /// Hands out turns to execute, in the order in which tasks are enqueued. diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index 26f19c9..d538c94 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -59,6 +59,13 @@ final class Turns: Sendable { return Turn(turns: self, previousTicket: previousTicket, ticket: ticket) } + /// Whether every turn reserved so far has ended. + /// + /// A turn ends only after every turn reserved before it has ended, so every turn has ended once the most recently reserved turn has. + var isIdle: Bool { + state.withLock { $0.lastTicket?.hasEnded ?? true } + } + /// The number of tasks waiting for their turn whose priority is recorded. Used by tests. var waitingTaskCount: Int { state.withLock { $0.waitingTaskCounts.values.reduce(0, +) } diff --git a/Tests/AsyncQueueTests/ActorQueueTests.swift b/Tests/AsyncQueueTests/ActorQueueTests.swift index fdfeadd..4b37cd8 100644 --- a/Tests/AsyncQueueTests/ActorQueueTests.swift +++ b/Tests/AsyncQueueTests/ActorQueueTests.swift @@ -514,6 +514,108 @@ struct ActorQueueTests { #expect(executor.wasEachJobEnqueuedOnMainQueue == [true, true]) } + @Test + func isIdle_onNewQueue_isTrue() { + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor() async { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + let task = Task(on: actor.queue) { actor in + actor.queue.isIdle + } + // `Task(on:)` takes the task's place on the queue before it returns, and the task cannot be isolated to the actor + // until the test runs the actor's executor. + let isIdleAfterTaskWasEnqueued = actor.queue.isIdle + // Wait for the task to hop to the actor. It has begun executing, but it is not isolated to the actor yet. + _ = await enqueuedJobs.next() + let isIdleAfterTaskHoppedToActor = actor.queue.isIdle + actor.executor.runUntilIdle() + let isIdleWhileOperationExecuted = await task.value + #expect(!isIdleAfterTaskWasEnqueued) + #expect(!isIdleAfterTaskHoppedToActor) + #expect(isIdleWhileOperationExecuted) + } + + @Test + func isIdle_whileLastOperationIsSuspended_isTrue() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { _ in + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task gave up its place on the queue once it was isolated to the actor, before its operation began. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(isIdleWhileOperationWasSuspended) + } + + @Test + func isIdle_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActor() async { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + // Each operation reads the property before it can suspend. The actor executes one job at a time, so the last task + // cannot be isolated to the actor while the first task's operation executes. + let firstTask = Task(on: actor.queue) { actor in + actor.queue.isIdle + } + let lastTask = Task(on: actor.queue) { actor in + actor.queue.isIdle + } + // Wait for the first task to hop to the actor, then run it. Its operation cannot execute before both tasks are enqueued. + _ = await enqueuedJobs.next() + actor.executor.runUntilIdle() + // Wait for the last task to hop to the actor, then run it if the previous call did not already. + _ = await enqueuedJobs.next() + actor.executor.runUntilIdle() + let isIdleWhileFirstOperationExecuted = await firstTask.value + let isIdleWhileLastOperationExecuted = await lastTask.value + #expect(!isIdleWhileFirstOperationExecuted) + #expect(isIdleWhileLastOperationExecuted) + } + + @Test + func isIdle_onMainActorQueue_afterTaskIsEnqueuedWhileCallerHoldsMainActor_isFalseUntilOperationRuns() 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) + // While this closure holds the main actor, the task cannot be isolated to it. The test cannot wait here for the task + // to hop to the main actor, so `mainTask_holdsTurnUntilItIsIsolatedToMainActor` covers when the task's turn ends. + let (task, isIdleAfterTaskWasEnqueued) = await MainActor.run { + let task = Task(on: mainActorQueue) { + mainActorQueue.isIdle + } + return (task, mainActorQueue.isIdle) + } + let isIdleWhileOperationExecuted = await task.value + #expect(!isIdleAfterTaskWasEnqueued) + #expect(isIdleWhileOperationExecuted) + } + + @Test + func isIdle_onMainActorQueue_whileLastOperationIsSuspended_isTrue() 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 operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: mainActorQueue) { + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task gave up its place on the queue once it was isolated to the main actor, before its operation began. + let isIdleWhileOperationWasSuspended = mainActorQueue.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(isIdleWhileOperationWasSuspended) + } + @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. diff --git a/Tests/AsyncQueueTests/FIFOQueueTests.swift b/Tests/AsyncQueueTests/FIFOQueueTests.swift index b8163cc..a833c12 100644 --- a/Tests/AsyncQueueTests/FIFOQueueTests.swift +++ b/Tests/AsyncQueueTests/FIFOQueueTests.swift @@ -570,6 +570,145 @@ struct FIFOQueueTests { #expect(didNextTurnBeginAfterTaskCompleted) } + @Test + func isIdle_onNewQueue_isTrue() { + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTaskIsEnqueuedWhileOperationCannotReturn_isFalse() async { + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { + await operationAllowedToReturn.wait() + } + // `Task(on:)` takes the task's place on the queue before it returns, and the operation cannot return yet. + let isIdleAfterTaskWasEnqueued = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + _ = await task.value + #expect(!isIdleAfterTaskWasEnqueued) + } + + @Test + func isIdle_whileOperationIsSuspended_isFalseUntilOperationReturns() 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 place on the queue until its operation returns. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_whileThrowingOperationIsSuspended_isFalseUntilOperationThrows() async { + struct TestError: Error {} + let operationStarted = Semaphore() + let operationAllowedToThrow = Semaphore() + let task = Task(on: systemUnderTest) { + await operationStarted.signal() + await operationAllowedToThrow.wait() + throw TestError() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation throws. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToThrow.signal() + await #expect(throws: TestError.self) { try await task.value } + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_whileOperationIsolatedToActorIsSuspended_isFalseUntilOperationReturns() 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 place on the queue until its operation returns. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_whileThrowingOperationIsolatedToActorIsSuspended_isFalseUntilOperationThrows() async { + struct TestError: Error {} + let operationStarted = Semaphore() + let operationAllowedToThrow = Semaphore() + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in + await operationStarted.signal() + await operationAllowedToThrow.wait() + throw TestError() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation throws. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToThrow.signal() + await #expect(throws: TestError.self) { try await task.value } + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_withCancelledTask_isFalseUntilItsOperationReturns() async { + let firstOperationAllowedToReturn = Semaphore() + let cancelledOperationStarted = Semaphore() + let cancelledOperationAllowedToReturn = Semaphore() + let firstTask = Task(on: systemUnderTest) { + await firstOperationAllowedToReturn.wait() + } + let cancelledTask = Task(on: systemUnderTest) { + await cancelledOperationStarted.signal() + await cancelledOperationAllowedToReturn.wait() + return Task.isCancelled + } + // The first operation cannot return yet, so this cancels the task while it waits on the queue. + cancelledTask.cancel() + await firstOperationAllowedToReturn.signal() + _ = await firstTask.value + // The cancelled task keeps its place on the queue, and its operation still runs. + let isIdleAfterFirstTaskCompleted = systemUnderTest.isIdle + await cancelledOperationStarted.wait() + let isIdleWhileCancelledOperationWasSuspended = systemUnderTest.isIdle + await cancelledOperationAllowedToReturn.signal() + let wasCancelledWhileOperationRan = await cancelledTask.value + #expect(!isIdleAfterFirstTaskCompleted) + #expect(!isIdleWhileCancelledOperationWasSuspended) + #expect(wasCancelledWhileOperationRan) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_withSeveralTasks_isFalseUntilLastOperationReturns() async { + let firstOperationAllowedToReturn = Semaphore() + let lastOperationAllowedToReturn = Semaphore() + let firstTask = Task(on: systemUnderTest) { + await firstOperationAllowedToReturn.wait() + } + let lastTask = Task(on: systemUnderTest) { + await lastOperationAllowedToReturn.wait() + } + await firstOperationAllowedToReturn.signal() + _ = await firstTask.value + // The last operation cannot return yet, so the last task still holds its place on the queue. + let isIdleAfterFirstTaskCompleted = systemUnderTest.isIdle + await lastOperationAllowedToReturn.signal() + _ = await lastTask.value + #expect(!isIdleAfterFirstTaskCompleted) + #expect(systemUnderTest.isIdle) + } + @Test func task_seesCallersTaskLocalValues() async throws { let systemUnderTest = TestTaskLocal.$value.withValue("queue creator") { diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index 8cfb24d..ad8d9ee 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -697,6 +697,59 @@ struct TurnsTests { #expect(priority.map { $0 >= .high } == true) } + @Test + func isIdle_beforeAnyTurnIsReserved_isTrue() { + let systemUnderTest = Turns() + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTurnIsReserved_isFalseUntilTurnEnds() async { + let systemUnderTest = Turns() + let turn = systemUnderTest.reserve() + let isIdleAfterTurnWasReserved = systemUnderTest.isIdle + await turn.begin() + let isIdleAfterTurnBegan = systemUnderTest.isIdle + turn.end() + #expect(!isIdleAfterTurnWasReserved) + #expect(!isIdleAfterTurnBegan) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_withSeveralTurns_isFalseUntilLastTurnEnds() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let lastTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + let isIdleAfterFirstTurnEnded = systemUnderTest.isIdle + await secondTurn.begin() + secondTurn.end() + let isIdleAfterSecondTurnEnded = systemUnderTest.isIdle + await lastTurn.begin() + lastTurn.end() + #expect(!isIdleAfterFirstTurnEnded) + #expect(!isIdleAfterSecondTurnEnded) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTurnIsReservedOnceEveryEarlierTurnEnded_isFalseUntilThatTurnEnds() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + // The value is a snapshot: reserving another turn makes the turns busy again. + let laterTurn = systemUnderTest.reserve() + let isIdleAfterLaterTurnWasReserved = systemUnderTest.isIdle + await laterTurn.begin() + laterTurn.end() + #expect(!isIdleAfterLaterTurnWasReserved) + #expect(systemUnderTest.isIdle) + } + // MARK: Private /// Creates a task that takes `turn` and, once its turn begins, installs an escalation handler that uses `turns`,