Skip to content

Add a minimum priority to ActorQueue - #97

Merged
dfed merged 1 commit into
claude/2.0-10-is-idlefrom
claude/2.0-11-actor-queue-priority
Nov 17, 2026
Merged

dfed merged 1 commit into
claude/2.0-10-is-idlefrom
claude/2.0-11-actor-queue-priority

Conversation

@dfed

@dfed dfed commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

What

Adds ActorQueue(priority:), which gives each of the queue's tasks at least that priority, as FIFOQueue(priority:) already does. ActorQueue() still compiles and gives its tasks no minimum priority.

Why

In 1.x, an ActorQueue ran every operation inside one long-lived task, so operations ran at the priority of the code that created the queue. In 2.0, each Task(on: actorQueue) is its own task and runs at the priority of the code that enqueues it, so an operation enqueued from .background code runs at .background. Before this change, the only way around that was to pass priority: at every call site. A FIFOQueue can be given a priority once, when you create it, and now an ActorQueue can too.

actor LogStore {
    init() {
        queue.adoptExecutionContext(of: self)
    }

    nonisolated func log(_ message: String) {
        // Runs at `.medium` or higher, whatever the caller's priority.
        Task(on: queue) { myself in
            myself.logs.append(message)
        }
    }

    private let queue = ActorQueue<LogStore>(priority: .medium)
    private var logs = [String]()
}

Semantics

These match FIFOQueue exactly:

  • A task enqueued with a lower priority, or with nil from lower-priority code, runs at the queue's priority.
  • A task enqueued with a higher priority, or with nil from higher-priority code, keeps its priority.
  • A queue created with nil, which is the default, changes nothing.
  • When the task's own priority is at least the queue's, the priority passed to Task(on:) goes to Task.init(name:priority:) unchanged, so Task works out the task's priority itself.
  • All four ActorQueue Task(on:) initializers use the queue's priority: the ones for your own actor and the ones for the main actor, each nonthrowing and throwing.
  • The four Task(on:) initializers for a CancellableQueue that wraps an ActorQueue forward to those, so they use it too, as the FIFOQueue-backed ones already did.
  • MainActor.queue has no priority of its own and is unchanged. Its documentation now says so, and tells callers to pass priority: instead.
  • Escalation: a task that runs at the queue's priority is an ordinary task created at that priority, so escalation starts from there. Awaiting it from a higher-priority task raises its priority. On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, a higher-priority task that waits behind it on the queue raises its priority too, and while it waits behind other tasks, it raises the priority of the tasks ahead of it to its own priority, as any task in a queue does.

Implementation

FIFOQueue's code that works out a task's priority moves unchanged into a new internal struct MinimumPriority in Sources/AsyncQueue/Utilities/MinimumPriority.swift, and both queues store one. That includes priorityOfNewTask(enqueuedWith:), the copy of Task's rules for the priority a new task inherits:

  • a raw value of zero means no priority;
  • a new task inherits the base priority, not the escalated priority;
  • outside of a task, the thread's priority applies, or .medium if the thread has none;
  • an inherited user-interactive priority is lowered to .high.

The function bodies are the same code, so FIFOQueue behaves exactly as before. FIFOQueueTests are unchanged and pass.

ActorQueue.init() becomes init(priority: TaskPriority? = nil), the same shape as FIFOQueue's. ActorQueue(), ActorQueue<T>(), MainActor.queue, the README examples and every test that creates a queue compile unchanged. The only call that stops compiling is a reference to the initializer as a () -> ActorQueue function value, such as ActorQueue<T>.init passed as a closure, which this 2.0 release can accept.

Docs

  • The ActorQueue.init(priority:) documentation uses FIFOQueue.init(priority:)'s wording.
  • The priority parameter of each of the four ActorQueue Task(on:) initializers adds the same sentence as FIFOQueue's: "If the queue was created with a higher priority, the task runs at the queue's priority instead."
  • So does the priority parameter of each of the four CancellableQueue Task(on:) initializers that take a CancellableQueue<ActorQueue<…>>, matching the four FIFOQueue-backed ones.
  • MainActor.queue documents that it has no priority of its own.
  • In the README:
    • The Priority bullets say that FIFOQueue(priority:) and ActorQueue(priority:) give each of the queue's tasks at least that priority, and that MainActor.queue has no priority of its own.

Tests

The new tests mirror FIFOQueue's tests of FIFOQueue(priority:). Each one reads Task.currentPriority inside the operation, through priorityOfTask(enqueuedFromTaskWithPriority:) or a stream. No test awaits the enqueued task before it reports, because awaiting would raise its priority. The tests that don't involve escalation assert exact priorities. The two escalation tests assert the starting priority exactly, and the raised priority with >= .high, like every other escalation test in ActorQueueTests and FIFOQueueTests. None of them sleeps, times out or polls.

New tests in ActorQueueTests:

  • task_onQueueWithPriority_withLowerPriority_executesAtQueuePriority: [.medium, .medium, .medium, .medium] across the four initializers.
  • task_onQueueWithPriority_withHigherPriority_executesAtThatPriority: [.high, .high, .high, .high].
  • task_onQueueWithPriority_withNilPriority_executesAtHigherOfCallersAndQueuePriority: .medium from .background and .high from .high, in all four initializers.
  • task_onQueueWithPriority_enqueuedFromEscalatedTaskWithLowerBasePriority_executesAtQueuePriority: the queue's priority is compared with the enqueuing task's base priority, not its escalated priority.
  • task_onQueueWithPriority_enqueuedOutsideOfAnyTask_executesAtHigherOfNewTaskAndQueuePriority: enqueuing from a Thread with each quality of service.
  • task_onQueueWithPriority_withUnspecifiedPriority_executesAtHigherOfCallersAndQueuePriority: TaskPriority(rawValue: 0).
  • task_onQueueWithUserInteractivePriority_enqueuedFromUserInteractiveTask_executesAtQueuePriority: the lowering of an inherited user-interactive priority. This test asserts == where FIFOQueue's uses >=, which is equivalent because nothing ranks above user-interactive.
  • task_onQueueWithPriority_isEscalatedWhenAwaitedFromHigherPriorityTask: the task starts at exactly the queue's priority, .low, and awaiting it then raises it to .high or above.
  • throwingTask_onQueueWithPriority_isEscalatedWhenItsTurnBeginsWhileHigherPriorityTaskWaits: a task that runs at the queue's priority is raised to .high or above by a task waiting behind it.

A queue without a minimum priority is ActorQueue(), which the existing tests already use, so it needs no new tests. The existing task_withNilPriority_inheritsCallersPriority covers it in all four initializers. task_withPriority_executesAtThatPriority, which checked only .low in two initializers, now has FIFOQueue's shape: .background through .high, enqueued from a .high task, in all four initializers.

No separate MinimumPriority unit test was added: the queue tests run every line of it through both queues. No CancellableQueueTests case was added either, since the CancellableQueue initializers only forward to the queue's own, and FIFOQueue(priority:) has none there.

Mutants

Each mutant below was built, and the 10 new and changed ActorQueueTests 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.

Mutant Tests that fail in all 10 runs
ActorQueue ignores its priority (MinimumPriority(nil)) 6: lower, nil, escalated base priority, outside of a task, user-interactive, escalation when awaited
The isolated nonthrowing initializer ignores the queue's priority the same 6
The isolated throwing initializer ignores the queue's priority lower, nil
The main actor nonthrowing initializer ignores the queue's priority lower, nil
The main actor throwing initializer ignores the queue's priority lower, nil
< flipped to >, so the lower of the two priorities wins 8, including higher
Task.currentPriority instead of Task.basePriority ?? Task.currentPriority escalated base priority
No check for a raw value of zero unspecified priority
No lowering of an inherited user-interactive priority user-interactive
The priority passed to Task(on:) dropped when the queue's priority doesn't apply higher, task_withPriority_executesAtThatPriority
A queue without a priority treated as .medium task_withPriority_executesAtThatPriority
The isolated throwing initializer doesn't let waiting tasks raise its priority throwingTask_onQueueWithPriority_isEscalatedWhenItsTurnBeginsWhileHigherPriorityTaskWaits

The mutants of MinimumPriority change FIFOQueue too. These runs used only the ActorQueueTests listed above; FIFOQueueTests are unchanged and run every line of MinimumPriority as well.

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 (179 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 and changed tests, 100 repetitions: --maximum-repetitions 100 --repeat-until fail on the 10 new and changed ActorQueueTests 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. Every line of MinimumPriority.swift 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

Each round runs 20,000 enqueues with every Task(on:) initializer of FIFOQueue and ActorQueue, for each build, in a shuffled order, each in its own process. The builds are the base branch, a second copy of it as an A/A control, the isIdle change, and this change. The ratios below are the medians, over rounds, of each build's time divided by the base build's time in the same round. "Enqueue" is the time spent in the loop of Task(on:) calls. "Total" also includes waiting for the last task to finish.

Pinned to CPU 0, 60 rounds:

Initializer Base enqueue (ns) A/A enqueue This change, enqueue A/A total This change, total
FIFOQueue 1,128 1.005 0.995 1.003 0.995
FIFOQueue, throwing 1,121 0.998 0.999 1.003 1.008
FIFOQueue, isolatedTo: 1,187 0.997 0.992 0.997 0.986
FIFOQueue, isolatedTo:, throwing 1,156 0.999 1.001 1.002 1.008
ActorQueue 1,152 1.006 1.002 1.000 1.000
ActorQueue, throwing 1,163 0.996 0.996 0.999 0.994
ActorQueue<MainActor> 1,136 0.998 0.998 1.002 0.958
ActorQueue<MainActor>, throwing 1,082 0.998 0.996 1.003 0.970

Unpinned, 40 rounds, the enqueue ratios for this change were 0.988 to 1.021, against 0.980 to 1.036 for the A/A control. Allocations per enqueue are the same as on the base branch.

The total time of the two MainActor cases moves by a few percent, in either direction, between builds of the same library code, so the lower totals in the table are not a speed-up:

  • Across builds of the benchmark with the same library code, this change measured anywhere from 7% slower to 5% faster than the base build in those two cases, while the A/A control stayed within 1.5%.
  • Adding one unused stored byte to ActorQueue on the base code slowed the nonthrowing MainActor case by about 3%. An unused 8-byte field, and changes to code alone, did not.
  • The enqueue time of this change matched the base build in every case, in every build of the benchmark.

Without a minimum priority, the ActorQueue enqueue path adds one check of an optional. ActorQueue gains one stored TaskPriority?, and FIFOQueue stores the same value as before.

Series

Stacked on #96, the isIdle change, which is stacked on #94. The two changes are independent: they touch the same files, but different lines. #99, which adds the macOS Thread Sanitizer and iOS 18 simulator jobs, is stacked on this PR.

🤖 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 (a5a502a) to head (70d113b).

Additional details and impacted files

Impacted file tree graph

@@                   Coverage Diff                    @@
##           claude/2.0-10-is-idle       #97    +/-   ##
========================================================
  Coverage                 100.00%   100.00%            
========================================================
  Files                         14        15     +1     
  Lines                       3120      3294   +174     
========================================================
+ Hits                        3120      3294   +174     
Files with missing lines Coverage Δ
Sources/AsyncQueue/ActorQueue.swift 100.00% <100.00%> (ø)
Sources/AsyncQueue/CancellableQueue.swift 100.00% <ø> (ø)
Sources/AsyncQueue/FIFOQueue.swift 100.00% <100.00%> (ø)
Sources/AsyncQueue/Utilities/MinimumPriority.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/ActorQueueTests.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
dfed force-pushed the claude/2.0-11-actor-queue-priority branch from 1626034 to 9ba2419 Compare November 16, 2026 04:56
@dfed
dfed force-pushed the claude/2.0-11-actor-queue-priority branch from 9ba2419 to e72e580 Compare November 16, 2026 05:13
@dfed
dfed force-pushed the claude/2.0-11-actor-queue-priority branch from e72e580 to 1bf79f4 Compare November 16, 2026 11:40
@dfed
dfed added this pull request to stack #103 November 16, 2026 21:42

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. Analyze (swift) passes on this PR's rebased head, 70d113b. I was wrong that it needed a decision. See the corrected comment on #88.


Generated by Claude Code

In 1.x, an `ActorQueue` ran every operation inside one long-lived task,
at the priority of the code that created the queue. In 2.0, each
`Task(on: actorQueue)` is its own task, so an operation enqueued from
low-priority code runs at low priority, and an `ActorQueue` had no way
to give its tasks a priority of its own.

`ActorQueue(priority:)` works like `FIFOQueue(priority:)`: it gives
each of the queue's tasks at least that priority. A task that would run
at a lower priority runs at the queue's priority instead, and a task
enqueued at a higher priority keeps it. All four `Task(on:)`
initializers for `ActorQueue` use it, and so do the four for a
`CancellableQueue` that wraps an `ActorQueue`; their documentation now
says so. `ActorQueue()` still compiles and gives its tasks no minimum
priority. `MainActor.queue` has none either, which its documentation
now says. The README's priority section now points `ActorQueue` users
to `ActorQueue(priority:)`.

`FIFOQueue`'s code that works out a task's priority moves unchanged
into an internal `MinimumPriority` type that both queues use, so
`FIFOQueue` behaves exactly as before and its tests are unchanged.
Without a minimum priority, the `ActorQueue` enqueue path adds one
check of an optional.

A task that runs at the queue's priority is escalated like any other
task. New tests cover the minimum priority in each `ActorQueue`
initializer, the priority a task inherits inside and outside of a task,
and escalation of a task that runs at the queue's priority. The
existing test of an explicit priority on an `ActorQueue` now covers
four priorities in all four initializers, as `FIFOQueue`'s does.

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-11-actor-queue-priority branch from 1bf79f4 to 70d113b Compare November 16, 2026 23:40
@dfed
dfed merged commit 947faa1 into main Nov 17, 2026
19 of 30 checks passed
@dfed
dfed deleted the claude/2.0-11-actor-queue-priority 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