Skip to content

Start main-actor queue tasks on the main actor - #101

Merged
dfed merged 3 commits into
claude/2.0-14-has-started-all-workfrom
claude/project-thread-2aoan1
Nov 17, 2026
Merged

dfed merged 3 commits into
claude/2.0-14-has-started-all-workfrom
claude/project-thread-2aoan1

Conversation

@dfed

@dfed dfed commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

Requested by Dan · project thread

Part of the 2.0 stack, on top of claude/2.0-14-has-started-all-work (#102).

What

Removes executor hops for queue tasks whose operation runs on the main actor:

Path Before After (turn is free when enqueued)
Task(on: MainActor.queue) / any ActorQueue<MainActor> global job → hop to main starts on main
Task(on: fifoQueue) { @MainActor in … } (incl. ops that inherit main isolation) global job → hop to main → hop back to global to end the turn starts on main, ends its turn on main
Task(on: CancellableQueue<FIFOQueue>) with a main-actor op same as FIFO before same as FIFO after

If a task has to wait for its turn, it still starts on the global executor. A continuation always resumes on the global executor, whichever executor it suspended on, so waiting on the main actor would cost an extra main-queue job. FIFO main-actor tasks still end their turn on main in that case.

How it works:

  • Turns.reserve() now records whether the turn was current when it was reserved (Turn.wasCurrentWhenReserved).
  • Turn.begin() is now nonisolated(nonsending), so a current turn begins without hopping off the main actor.

Why not other actors?

I first built this for every actor, using a generic way to start a task on any actor. On default actors it made things ~1.5× slower. A task can switch from the global executor to an idle default actor (and back) inline, without enqueuing a job, so that "hop" was nearly free. Starting a task on an actor, by contrast, always costs a real actor enqueue. The main actor and custom executors can't take an inline switch, which is where the saving is. I limited the change to the main actor because there's no public API to tell a default actor from a custom-executor actor. Ending FIFO turns on default actors without hopping back also gave no measurable gain, so I dropped it.

Benchmarks

Release build on an M-series Mac, median of 7. Tasks are enqueued from a non-main task. Numbers are from three alternating old/new rounds; the machine was noisy, so unchanged paths vary ±15%.

Benchmark Before After
MainActor.queue: enqueue + await, one at a time (10k) 89–146 ms 68–77 ms
FIFOQueue @MainActor op: enqueue + await, one at a time (10k) 90–116 ms 63–71 ms
FIFOQueue @MainActor op: enqueue 10k, await last 90–145 ms 62–73 ms
ActorQueue / FIFO on default actors 139–167 ms 122–160 ms (no slowdown; see below)

Does the main-actor check slow down other actors?

No. For ActorQueue, the main-actor path is a separate overload, chosen at compile time. Generic actor queues pick up only an extra Bool that Turns.reserve() computes under the lock it already holds. FIFO's isolatedTo: initializers are unchanged. FIFO's @isolated(any) initializers check at runtime: they read the operation's isolation and compare it by pointer to MainActor.shared, which is a couple of loads per enqueue. Over five alternating rounds, the regular-actor paths came out 4–16% faster in the new build. That's noise, since that code didn't change, but it shows no measurable cost.

Observable ordering change on the main actor

When a task's turn is free, it now starts as a main-actor job at the moment you enqueue it. Before, it started on the global executor and hopped over later. So a main-actor queue task now runs before main-actor work enqueued after it, such as a plain Task { @MainActor in } created right after Task(on: MainActor.queue). Before, it usually ran after that work, though that was never guaranteed. Ordering among the queue's own tasks is unchanged. ActorQueue.hasStartedAllWork and FIFOQueue.isIdle can also become true sooner for main-actor tasks.

Tests

  • New ordering tests: a queued main-actor task enqueued while the test holds the main actor must run before a plain Task { @MainActor in } created right after it. The main queue is FIFO, so this passes deterministically only if the task starts on main. These tests fail on the 2.0 tip.
  • begin() on a current turn doesn't suspend or hop off the main actor. This also fails on the 2.0 tip.
  • Ending FIFO turns on the main actor is tested through a new debug-only hook: Turns(didEndTurn:) and FIFOQueue(turns:) exist only under #if DEBUG, so release builds compile neither. The tests record Thread.isMainThread each time a turn ends. They cover both the waiting and non-waiting paths, throwing and non-throwing, plus CancellableQueue. I checked that all 6 fail on 3 of 3 runs when executeOnMainActor is changed to end the turn off the main actor. These tests don't run in the release CI jobs.
  • Ordering under a backlog, where every task waits, is preserved.
  • wasCurrentWhenReserved unit tests.
  • 202 tests pass in debug and TSan, and 196 in release, which skips the debug-only tests. Coverage of the changed files is 100%. swiftformat --lint is clean.

Notes for review

  • Reading .isolation directly from a sending @isolated(any) parameter inside a Task extension initializer crashes the Swift 6.4 compiler in SILGen. The small isolation(of:) helper works around it.
  • While prototyping I also hit what looks like a miscompile: a typed-throws (throws(Failure)) helper that took an isolated (any Actor)? parameter silently swallowed errors thrown by the operation. The final code doesn't use typed throws.

🤖 Generated with Claude Code

@dfed dfed self-assigned this Nov 16, 2026
@codecov

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files

Impacted file tree graph

@@                          Coverage Diff                          @@
##           claude/2.0-14-has-started-all-work      #101    +/-   ##
=====================================================================
  Coverage                              100.00%   100.00%            
=====================================================================
  Files                                      15        15            
  Lines                                    3290      3605   +315     
=====================================================================
+ Hits                                     3290      3605   +315     
Files with missing lines Coverage Δ
Sources/AsyncQueue/ActorQueue.swift 100.00% <100.00%> (ø)
Sources/AsyncQueue/CancellableQueue.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/CancellableQueueTests.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
dfed force-pushed the claude/project-thread-2aoan1 branch from 84566c3 to 8442ac5 Compare November 16, 2026 20:41
@dfed dfed changed the title Start main-actor queue tasks on the main actor (2.1) Start main-actor queue tasks on the main actor Nov 16, 2026
@dfed
dfed changed the base branch from claude/2.0-13-readme to claude/2.0-14-has-started-all-work November 16, 2026 20:41
@dfed
dfed added this pull request to stack #103 November 16, 2026 21:42
dfed and others added 3 commits November 16, 2026 15:39
A task enqueued on `MainActor.queue`, or on a `FIFOQueue` with an operation
isolated to the main actor, started on the global concurrent executor and
then hopped to the main actor, which costs a job on the main queue plus one
on the global executor. A FIFO task also hopped back off of the main actor
to end its turn.

When a task's turn is current at the moment it is enqueued, start it on the
main actor directly. `Turn.begin()` is now `nonisolated(nonsending)` so that
a current turn begins without hopping off. FIFO tasks with main-actor
operations end their turn on the main actor. A task that has to wait for its
turn still starts on the global executor, because a continuation always
resumes there whichever executor it waited on.

Tasks on other actors are unchanged: a task switches from the global
executor to an idle default actor without enqueuing a job, and benchmarks
showed starting those tasks on the actor made them slower.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tests that checked a FIFO task ends its turn on the main actor passed
on the old code too, so they could not fail every run on the regression
they guard. Remove them, and cover the throwing FIFO path for a main-actor
operation that waits for its turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a debug-only hook to `Turns` that is called each time a turn ends, and
a debug-only `FIFOQueue.init(turns:)` to inject it. Tests record whether
each turn ended on the main thread: a task that hopped off of the main
actor before ending its turn fails every run.

Release builds compile neither the hook nor the tests that use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dfed
dfed force-pushed the claude/project-thread-2aoan1 branch from 8442ac5 to b38aaa3 Compare November 16, 2026 23:40
@dfed
dfed merged commit ccbfc26 into main Nov 17, 2026
15 of 28 checks passed
@dfed
dfed deleted the claude/project-thread-2aoan1 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.

1 participant