Repository navigation
Add isIdle to ActorQueue and FIFOQueue - #96
Merged
Merged
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
dfed
force-pushed
the
claude/2.0-10-is-idle
branch
from
November 16, 2026 04:56
ff44701 to
dfed4d9
Compare
dfed
force-pushed
the
claude/2.0-10-is-idle
branch
2 times, most recently
from
November 16, 2026 11:40
b9023c5 to
8047e87
Compare
This was referenced Nov 16, 2026
Owner
Author
|
Correction: the CodeQL Swift failure I reported here is fixed by 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
force-pushed
the
claude/2.0-10-is-idle
branch
from
November 16, 2026 23:40
8047e87 to
a5a502a
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Adds a public, synchronous
var isIdle: BooltoFIFOQueueandActorQueue, and so toMainActor.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
The actor enqueues every task and reads
isIdle, and it doesn't suspend between readingisIdleand 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 theFIFOQueue.isIdledocumentation and in a new README section, "Checking whether a queue is idle". Both compile with-warnings-as-errors.Semantics
FIFOQueue:truewhen every task enqueued on the queue has finished, which means its operation has returned or thrown. A task that is suspended at anawaithasn'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:truewhen 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.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 readsisIdle, a shortFIFOQueueoperation may already have returned, or anActorQueuetask 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 aFIFOQueueoperation is isolated to, or the actor of anActorQueue.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.FIFOQueue, work enqueued afterward on a new queue runs after every task on the removed queue.ActorQueue, every task enqueued on the removed queue has started running on the queue's actor.Implementation
Turns.isIdleisstate.withLock { $0.lastTicket?.hasEnded ?? true }:reserve()already recordslastTicketunder theTurnslock.end()setshasEndedunder the same lock.The change adds no stored state and leaves the enqueue path untouched. The only additions to
Sourcesare three computed properties and their documentation.CancellableQueueCancellableQueuegets noisIdle:CancellableQueuekeeps that queue private, so a caller who wants to remove aCancellableQueuekeeps their own reference to the wrapped queue and reads itsisIdle, as the README says.Task(on:)on aCancellableQueueenqueues on the wrapped queue before it returns, so the wrapped queue'sisIdlealready covers tasks enqueued through the wrapper.CancellableQueuestops tracking a task only when its operation finishes. For anActorQueue, 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.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 inMainActor.run.TurnsTests:isIdle_beforeAnyTurnIsReserved_isTrueisIdle_afterTurnIsReserved_isFalseUntilTurnEndsisIdle_withSeveralTurns_isFalseUntilLastTurnEndsisIdle_afterTurnIsReservedOnceEveryEarlierTurnEnded_isFalseUntilThatTurnEnds(the value changes when a turn is reserved after the turns were idle)FIFOQueueTests:isIdle_onNewQueue_isTrueisIdle_afterTaskIsEnqueuedWhileOperationCannotReturn_isFalseisIdle_whileOperationIsSuspended_isFalseUntilOperationReturnsisIdle_whileThrowingOperationIsSuspended_isFalseUntilOperationThrowsisIdle_whileOperationIsolatedToActorIsSuspended_isFalseUntilOperationReturns(Task(on:isolatedTo:))isIdle_whileThrowingOperationIsolatedToActorIsSuspended_isFalseUntilOperationThrows(throwingTask(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, seesTask.isCancelledin its operation, and leaves the queue idle once its operation returns.isIdle_withSeveralTasks_isFalseUntilLastOperationReturnsActorQueueTests:isIdle_onNewQueue_isTrueisIdle_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor: reads the property afterTask(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_isTrueisIdle_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActor: each operation reads the property on the actor before it can suspend.isIdle_onMainActorQueue_afterTaskIsEnqueuedWhileCallerHoldsMainActor_isFalseUntilOperationRunsisIdle_onMainActorQueue_whileLastOperationIsSuspended_isTrueThe two main actor tests use a private
ActorQueue<MainActor>, not the sharedMainActor.queue. The main actor has no hook that lets a test wait for a task to switch to it without running it, so noisIdletest can tell "busy until the task is running on the main actor" from "busy until the task starts". The existingmainTask_holdsTurnUntilItIsIsolatedToMainActorandmainThrowingTask_holdsTurnUntilItIsIsolatedToMainActortests pin when a main actor task stops counting, andisIdlereads the same state.Mutants
Each mutant below was built and the 18
isIdletests were run 10 times against it: 7 runs unpinned and 3 pinned to one CPU withtaskset -c 0. Each mutant failed all 10 runs, and no run hung. The table lists the new tests that failed in all 10 runs.isIdlealwaystruefalse, such asisIdle_afterTaskIsEnqueuedWhileOperationCannotReturn_isFalseandisIdle_withCancelledTask_isFalseUntilItsOperationReturns(13 tests)isIdlealwaysfalsetrue, such asisIdle_onNewQueue_isTrueon both queues andisIdle_whileLastOperationIsSuspended_isTrue(17 tests)?? falseinstead of?? trueisIdle_beforeAnyTurnIsReserved_isTrueandisIdle_onNewQueue_isTrueon both queueshasEnded(lastTicket == nil)trueafter a task is enqueued (14 tests)falsewhile the last task is the only one left (13 tests)FIFOQueuetask stops counting before its operation runs: nonthrowingTask(on:)isIdle_whileOperationIsSuspended_isFalseUntilOperationReturns,isIdle_withCancelledTask_isFalseUntilItsOperationReturns,isIdle_withSeveralTasks_isFalseUntilLastOperationReturnsTask(on:)isIdle_whileThrowingOperationIsSuspended_isFalseUntilOperationThrowsTask(on:isolatedTo:)isIdle_whileOperationIsolatedToActorIsSuspended_isFalseUntilOperationReturnsTask(on:isolatedTo:)isIdle_whileThrowingOperationIsolatedToActorIsSuspended_isFalseUntilOperationThrowsFIFOQueuetask stops counting before its operation runsisIdle_withCancelledTask_isFalseUntilItsOperationReturnsActorQueuetask counts until its operation returnsisIdle_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor,isIdle_whileLastOperationIsSuspended_isTrue,isIdle_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActorActorQueuetask stops counting before it runs on the actorisIdle_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor,isIdle_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActorisIdle_onMainActorQueue_…testsTwo mutants survive the new tests:
mainTask_holdsTurnUntilItIsIsolatedToMainActorandmainThrowingTask_holdsTurnUntilItIsIsolatedToMainActortests catch it.Mutexonly exposes its value insidewithLock, 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.
-warnings-as-errors.SourcesorTests.--maximum-repetitions 100 --repeat-until failon the 18isIdletests passed unpinned and pinned to CPU 0.SourcesorTeststhat never runs.Mutexreplaced by a pthread-based lock. On Linux, ThreadSanitizer flagsSynchronization.Mutexwhen two threads contend for it, because it can't see the lock's slow path in the prebuilt standard library.-warnings-as-errors.Task(on:)initializer ofFIFOQueueandActorQueueagainst 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 inTask(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