Skip to content

Add isIdle to ActorQueue and FIFOQueue - #96

Merged
dfed merged 1 commit into
claude/2.0-9-escalate-turn-holderfrom
claude/2.0-10-is-idle
Nov 17, 2026
Merged

dfed merged 1 commit into
claude/2.0-9-escalate-turn-holderfrom
claude/2.0-10-is-idle

Conversation

@dfed

@dfed dfed commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

What

Adds a public, synchronous var isIdle: Bool to FIFOQueue and ActorQueue, and so to MainActor.queue.

Why

Code that keeps one queue per key creates each queue on demand, and later wants to remove it. Without isIdle, it can tell when a queue can go, without breaking the order of the work enqueued on it, only by counting tasks itself, which repeats what the queue already tracks.

Use case

actor DocumentStore {
    func save(_ contents: String, as name: String) -> Task<Void, Never> {
        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]()
}

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 saved after its queue is removed gets a new queue. Every task on the removed queue has already finished, so the new task still runs after them. This example is in the FIFOQueue.isIdle documentation and in a new README section, "Checking whether a queue is idle". Both compile with -warnings-as-errors.

Semantics

  • FIFOQueue: true when every task enqueued on the queue has finished, which means its operation has returned or thrown. A task that is suspended at an await hasn't finished, so an operation always finds its own queue busy. A cancelled task hasn't finished either: it keeps its place, and its operation still runs.
  • ActorQueue: true when every task enqueued on the queue has started running on the actor. A task stops counting as soon as it is running on the actor, before its operation runs, so the queue can be idle while the operations of its tasks haven't finished.
  • When a task starts counting: Task(on:) enqueues the task before it returns, so the task counts from that moment. The task runs alongside the code that enqueued it, though. By the time that code reads isIdle, a short FIFOQueue operation may already have returned, or an ActorQueue task may already be running on its actor. That can't happen while the reading code is running on the actor the task needs: the actor a FIFOQueue operation is isolated to, or the actor of an ActorQueue.
  • The value can change as soon as it is read: a task enqueued afterward makes the queue busy again.
  • Removing a queue safely: one actor must enqueue every task on the queue, read isIdle, and remove the queue, without suspending between the read and the removal. Running the same code from several threads isn't enough, because another thread could enqueue a task between the read and the removal.
    • For a FIFOQueue, work enqueued afterward on a new queue runs after every task on the removed queue.
    • For an ActorQueue, every task enqueued on the removed queue has started running on the queue's actor.

Implementation

Turns.isIdle is state.withLock { $0.lastTicket?.hasEnded ?? true }:

  • reserve() already records lastTicket under the Turns lock.
  • end() sets hasEnded under the same lock.
  • A turn ends only after every earlier turn has ended, so once the last ticket has ended, every ticket has.

The change adds no stored state and leaves the enqueue path untouched. The only additions to Sources are three computed properties and their documentation.

CancellableQueue

CancellableQueue gets no isIdle:

  • The caller creates the wrapped queue. CancellableQueue keeps that queue private, so a caller who wants to remove a CancellableQueue keeps their own reference to the wrapped queue and reads its isIdle, as the README says. Task(on:) on a CancellableQueue enqueues on the wrapped queue before it returns, so the wrapped queue's isIdle already covers tasks enqueued through the wrapper.
  • A CancellableQueue stops tracking a task only when its operation finishes. For an ActorQueue, that is later than the point where the queue becomes idle, so a forwarding property would invite confusion about which of the two it reports.
  • It can be added later as a conditional extension without breaking anything.

Tests

Every new test is deterministic. None of them sleeps, times out or polls. Each one forces its ordering with Semaphore, the manually run actor (ManualSerialExecutor, whose jobs run only when the test runs them), or by holding the main actor in MainActor.run.

  • TurnsTests:
    • isIdle_beforeAnyTurnIsReserved_isTrue
    • isIdle_afterTurnIsReserved_isFalseUntilTurnEnds
    • isIdle_withSeveralTurns_isFalseUntilLastTurnEnds
    • isIdle_afterTurnIsReservedOnceEveryEarlierTurnEnded_isFalseUntilThatTurnEnds (the value changes when a turn is reserved after the turns were idle)
  • FIFOQueueTests:
    • isIdle_onNewQueue_isTrue
    • isIdle_afterTaskIsEnqueuedWhileOperationCannotReturn_isFalse
    • isIdle_whileOperationIsSuspended_isFalseUntilOperationReturns
    • isIdle_whileThrowingOperationIsSuspended_isFalseUntilOperationThrows
    • isIdle_whileOperationIsolatedToActorIsSuspended_isFalseUntilOperationReturns (Task(on:isolatedTo:))
    • isIdle_whileThrowingOperationIsolatedToActorIsSuspended_isFalseUntilOperationThrows (throwing Task(on:isolatedTo:))
    • isIdle_withCancelledTask_isFalseUntilItsOperationReturns: a task cancelled while it waits behind another task keeps the queue busy after the first task finishes and while its own operation is suspended, sees Task.isCancelled in its operation, and leaves the queue idle once its operation returns.
    • isIdle_withSeveralTasks_isFalseUntilLastOperationReturns
  • ActorQueueTests:
    • isIdle_onNewQueue_isTrue
    • isIdle_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor: reads the property after Task(on:) returns, again once the task has switched to the manually run actor but before the test runs that job, and inside the operation.
    • isIdle_whileLastOperationIsSuspended_isTrue
    • isIdle_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActor: each operation reads the property on the actor before it can suspend.
    • isIdle_onMainActorQueue_afterTaskIsEnqueuedWhileCallerHoldsMainActor_isFalseUntilOperationRuns
    • isIdle_onMainActorQueue_whileLastOperationIsSuspended_isTrue

The two main actor tests use a private ActorQueue<MainActor>, not the shared MainActor.queue. The main actor has no hook that lets a test wait for a task to switch to it without running it, so no isIdle test can tell "busy until the task is running on the main actor" from "busy until the task starts". The existing mainTask_holdsTurnUntilItIsIsolatedToMainActor and mainThrowingTask_holdsTurnUntilItIsIsolatedToMainActor tests pin when a main actor task stops counting, and isIdle reads the same state.

Mutants

Each mutant below was built and the 18 isIdle tests were run 10 times against it: 7 runs unpinned and 3 pinned to one CPU with taskset -c 0. Each mutant failed all 10 runs, and no run hung. The table lists the new tests that failed in all 10 runs.

Mutant Tests that fail
isIdle always true Every test that expects false, such as isIdle_afterTaskIsEnqueuedWhileOperationCannotReturn_isFalse and isIdle_withCancelledTask_isFalseUntilItsOperationReturns (13 tests)
isIdle always false Every test that expects true, such as isIdle_onNewQueue_isTrue on both queues and isIdle_whileLastOperationIsSuspended_isTrue (17 tests)
?? false instead of ?? true isIdle_beforeAnyTurnIsReserved_isTrue and isIdle_onNewQueue_isTrue on both queues
Ignores hasEnded (lastTicket == nil) Every test that expects true after a task is enqueued (14 tests)
Idle while the last task is still the first in line Every test that expects false while the last task is the only one left (13 tests)
FIFOQueue task stops counting before its operation runs: nonthrowing Task(on:) isIdle_whileOperationIsSuspended_isFalseUntilOperationReturns, isIdle_withCancelledTask_isFalseUntilItsOperationReturns, isIdle_withSeveralTasks_isFalseUntilLastOperationReturns
The same, throwing Task(on:) isIdle_whileThrowingOperationIsSuspended_isFalseUntilOperationThrows
The same, Task(on:isolatedTo:) isIdle_whileOperationIsolatedToActorIsSuspended_isFalseUntilOperationReturns
The same, throwing Task(on:isolatedTo:) isIdle_whileThrowingOperationIsolatedToActorIsSuspended_isFalseUntilOperationThrows
A cancelled FIFOQueue task stops counting before its operation runs isIdle_withCancelledTask_isFalseUntilItsOperationReturns
ActorQueue task counts until its operation returns isIdle_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor, isIdle_whileLastOperationIsSuspended_isTrue, isIdle_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActor
ActorQueue task stops counting before it runs on the actor isIdle_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor, isIdle_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActor
Main actor task counts until its operation returns both isIdle_onMainActorQueue_… tests

Two mutants survive the new tests:

  • A main actor task stops counting before it runs on the main actor. No new test can catch it, for the reason given above. The existing mainTask_holdsTurnUntilItIsIsolatedToMainActor and mainThrowingTask_holdsTurnUntilItIsIsolatedToMainActor tests catch it.
  • A read that skips the lock. No deterministic test can catch it. Mutex only exposes its value inside withLock, and a deterministic test orders every read after the writes it observes, so a read without the lock returns the same value.

Checks

All checks used Swift 6.4.2 on Linux, in release mode.

  • Lint: SwiftFormat reports no files that need formatting.
  • Build: the package and its tests build with -warnings-as-errors.
  • Full suite (170 tests): passed 10 of 10 runs, 3 of them pinned to CPU 0.
  • Rebase: these checks ran before Escalate the task holding the current turn on behalf of waiting tasks #94 gained its third commit, the lock-order fix. This PR was rebased onto it without conflicts and is otherwise unchanged. At the top of the rebased series, the full suite (184 tests) passed 5 runs unpinned and 3 pinned to CPU 0, with no unexecuted line in Sources or Tests.
  • New tests, 100 repetitions: --maximum-repetitions 100 --repeat-until fail on the 18 isIdle tests passed unpinned and pinned to CPU 0.
  • Coverage: CI's coverage command, with atomic counters and the check that every counter update is atomic, leaves no line in Sources or Tests that never runs.
  • ThreadSanitizer: 3 full-suite runs with no reports, with Mutex replaced by a pthread-based lock. On Linux, ThreadSanitizer flags Synchronization.Mutex when two threads contend for it, because it can't see the lock's slow path in the prebuilt standard library.
  • Examples: the README examples and the documentation examples compile with -warnings-as-errors.
  • Benchmark: the change doesn't touch the enqueue path, and a benchmark of every Task(on:) initializer of FIFOQueue and ActorQueue against the base branch shows no difference. It ran 60 rounds pinned to CPU 0 and 40 rounds unpinned. Each round runs 20,000 enqueues per initializer for each build, in a shuffled order, with a second copy of the base build as an A/A control. Pinned, the median ratio to the base build of the time spent in Task(on:) was 0.994 to 1.006 for this change and 0.996 to 1.006 for the A/A control. Unpinned, it was 0.974 to 1.035 for this change and 0.980 to 1.036 for the A/A control. The benchmark executable's machine code is byte for byte the same as the base build's, and allocations per enqueue are the same.

Series

Stacked on #94, which now has a third commit, the lock-order fix. #97, ActorQueue(priority:), is stacked on this one.

🤖 Generated with Claude Code

https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (1fec6fc) to head (a5a502a).

Additional details and impacted files

Impacted file tree graph

@@                         Coverage Diff                          @@
##           claude/2.0-9-escalate-turn-holder       #96    +/-   ##
====================================================================
  Coverage                             100.00%   100.00%            
====================================================================
  Files                                     14        14            
  Lines                                   2890      3120   +230     
====================================================================
+ Hits                                    2890      3120   +230     
Files with missing lines Coverage Δ
Sources/AsyncQueue/ActorQueue.swift 100.00% <100.00%> (ø)
Sources/AsyncQueue/FIFOQueue.swift 100.00% <100.00%> (ø)
Sources/AsyncQueue/Utilities/Turns.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/ActorQueueTests.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/FIFOQueueTests.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/TurnsTests.swift 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

dfed commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner Author

Correction: the CodeQL Swift failure I reported here is fixed by 9a40bac on #88, which builds without SwiftPM's sandbox under CodeQL, and this PR now sits on top of it. I was wrong that it needed a decision. See the corrected comment on #88.


Generated by Claude Code

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM
@dfed
dfed force-pushed the claude/2.0-10-is-idle branch from 8047e87 to a5a502a Compare November 16, 2026 23:40
@dfed
dfed merged commit 9865161 into main Nov 17, 2026
12 of 22 checks passed
@dfed
dfed deleted the claude/2.0-10-is-idle branch November 17, 2026 02:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants