Skip to content

Run ActorQueue operations in the task returned to the caller - #91

Merged
dfed merged 1 commit into
claude/2.0-5-cancel-enqueuing-tasksfrom
claude/2.0-6-actor-queue-turns
Nov 17, 2026
Merged

dfed merged 1 commit into
claude/2.0-5-cancel-enqueuing-tasksfrom
claude/2.0-6-actor-queue-turns

Conversation

@dfed

@dfed dfed commented Nov 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Previously a drain loop created a separate task for each operation, and the task returned to the caller waited on a continuation for the result. That caused three bugs:

  • Out-of-order starts with mixed priorities. The drain loop enqueued each operation's task on the adopted actor without waiting for it to start. A default actor runs higher-priority jobs first, so a later .high task overtook an earlier .low one. In 20 tasks alternating .low and .high, 199 of 200 runs were out of order.
  • Wrong task-local values. Operations saw the task-local values bound when the queue was created rather than the caller's. Because MainActor.queue is created lazily, it handed its first caller's task-local values to every later caller for the life of the process.
  • Wrong priority. Operations ran at the drain loop's priority rather than the caller's, and awaiting the returned task did not escalate the operation.

Now each Task(on:) runs its operation in the task it returns, so task-local values, priority, escalation, and cancellation behave as they do for Task. Tasks take turns in enqueue order (Utilities/Turns.swift). Each task waits for its predecessor to become isolated to the adopted actor. It ends its own turn as soon as it is isolated, which lets the next task hop to the actor but not run until the current operation suspends or returns.

ActorQueue(name:) is removed in favor of ActorQueue(): the name labeled the drain task, which no longer exists. The Task(on:) signatures don't change.

Tests

These fail on the parent and pass here:

  • Turn order, without timing. task_, throwingTask_, mainTask_ and mainThrowingTask_holdsTurnUntilItIsIsolatedTo{Actor,MainActor} hold a task on its way to the actor, on a ManualSerialExecutor that runs jobs only when the test says so, or by occupying the main actor, and check through a probe turn that the next turn cannot begin until the task is isolated.
  • Task-local inheritance (task_ and mainTask_seesCallersTaskLocalValues), including the leak through MainActor.queue.
  • Inheriting a nil priority, and running at an explicit priority.
  • Escalation when the returned task is awaited, on an actor and on the main actor.

Utilities/ManualExecutors.swift adds ManualTaskExecutor, ManualSerialExecutor and a probe-turn helper, so tests decide exactly when a task runs.

Both executors keep themselves alive while enqueue(_:) runs. The runtime calls enqueue(_:) without keeping the executor alive. When another thread enqueues the job that lets a test finish, the test can run the job and release the executor before enqueue(_:) returns, which then writes to freed memory. Tests added later in this series crashed this way on Linux about once in 300,000 runs, with no error message, in _dispatch_queue_dispose or in AsyncStream. That fits the iOS test process that died on #96. With the fix, 22.9 million runs of those tests had no crash.

main's four ActorQueue sendsEventsInOrder loop tests stay. Each initializer's await turn.begin() has no deterministic test yet, and those loops are its only guard (see the checklist).

Per-task cost is roughly 15 µs → 9 µs on Linux (noisy; release build).

Series

PR 7 of 10. It is stacked on #90.

Validation

Each commit in the series was validated on its own, on Linux with Swift 6.4.2, from a git archive copy:

  • It builds with -warnings-as-errors, and swiftformat --lint is clean.
  • The full suite passed 3 runs unpinned and 1 with the test runner pinned to one CPU.
  • The Linux job's coverage steps, run from the commit's own ci.yml under bash -e, pass, including the atomic-counter check. No line in Sources or Tests reads zero in the CI run.
  • Rechecked on this commit: cancelTasks_actorQueue_cancelsCurrentlyExecutingAndPendingTasks, whose spinner runs on DispatchQueueExecutor, fails 10 of 10 runs (3 pinned to one CPU) when the first ActorQueue initializer skips registering its task, passes 10 of 10 on the real code, and passes --repetitions 100 --repeat-until fail unpinned and pinned. Earlier rounds checked the other tests against mutants the same way.
  • At the top of the series, 3 rounds of 10 concurrent full suites pinned to one CPU pass, and ThreadSanitizer reports no races in 3 runs. TSan on Linux flags Synchronization.Mutex even in trivially correct code, so the TSan runs replace Mutex with a pthread-based lock that TSan understands.
  • The executor fix: in Swift 6.4.2, Unmanaged.passRetained(self) keeps its retain and release at -Onone and -O. withExtendedLifetime(self) emits no retain, because self is passed without one, so it would not fix the bug.

Nothing was run on Apple platforms. CI is the first run there.

Review checklist

Left for code review because no test can force them:

  • Signal: one critical section each. Signal.wait must check isFired and store its continuation in one withLock, fire must set isFired and take the waiter in one, and Turns.reserve must read and replace the last turn's signal in one. No test can force a thread switch inside one.
  • Every ActorQueue initializer awaits turn.begin(). Only main's probabilistic ordering loops cover a missing await turn.begin() in one initializer. Testing it deterministically would need a production change (shared functions, a begun-turn token or an executor seam), and each of those measured slower per task, so the code keeps the inline await turn.begin() and review covers this.
  • Darwin. ManualTaskExecutor and ManualSerialExecutor were not built under Xcode. CI is the first run there.

🤖 Generated with Claude Code

https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM

@codecov

codecov Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files

Impacted file tree graph

@@                          Coverage Diff                           @@
##           claude/2.0-5-cancel-enqueuing-tasks       #91    +/-   ##
======================================================================
  Coverage                               100.00%   100.00%            
======================================================================
  Files                                       12        14     +2     
  Lines                                     1540      1739   +199     
======================================================================
+ Hits                                      1540      1739   +199     
Files with missing lines Coverage Δ
Sources/AsyncQueue/ActorQueue.swift 100.00% <100.00%> (ø)
Sources/AsyncQueue/Utilities/Turns.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/ActorQueueTests.swift 100.00% <100.00%> (ø)
...ts/AsyncQueueTests/Utilities/ManualExecutors.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/Utilities/TestHelpers.swift 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread Sources/AsyncQueue/ActorQueue.swift Resolved
@dfed
dfed force-pushed the claude/2.0-6-actor-queue-turns branch 2 times, most recently from 6af1761 to eaf4480 Compare November 15, 2026 15:45
@dfed
dfed force-pushed the claude/2.0-6-actor-queue-turns branch from eaf4480 to e07cf88 Compare November 16, 2026 11:40

dfed commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner Author

Build Xcode (visionOS) failed on e07cf88 without a test failure. The test runner stopped printing at 11:59:47 and was silent for about 10 minutes. In the middle of that, xcodebuild timed out reaching the simulator's instruments service (com.apple.instruments.deviceservice.lockdown). It then restarted the runner ("Restarting after unexpected exit, crash, or test timeout"), and the relaunch ran 0 tests. The 46 "failing" tests are the ones that were still running when the runner stopped. The log has no ✘, Expectation failed or crash signal.

This is most likely the simulator or runner hanging. This branch still runs every test 100 times in parallel on the simulator, and #99 removes that. All eight rebuilt PRs were pushed at once, so the macOS runners are heavily shared. The same lockdown and runner errors appeared on two recent iOS/watchOS jobs. The iOS,watchOS job on this same commit passed all 100 iterations.

One thing in the log could point at the library instead. Every test that uses the shared MainActor.queue, and every 1,000-iteration ordering test, stopped making progress about 26 s before the silence. Tests on their own main-actor queue kept going. No test sends low-priority work through MainActor.queue, so this isn't a priority inversion. At most, a task holding the shared queue's turn could have been delayed on a slow simulator.

CI doesn't save the result bundle on this branch, which would show what happened. I'll re-run the failed job once when the run finishes. If it stalls again in the same place, I'll treat it as a library problem rather than CI.

Edited: the first version suggested a starved low-priority task. The tests don't enqueue any low-priority work on MainActor.queue, so that explanation doesn't hold.


Generated by Claude Code

@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, 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

Previously a drain loop created a separate task for each operation and
the returned task waited on a continuation for its result. That caused
three bugs:

- Tasks with different priorities began executing out of order. The
  drain loop enqueued each operation's task on the adopted actor without
  waiting for it to start, and a default actor runs higher-priority jobs
  first, so a later `.high` task overtook an earlier `.low` one.
- Operations saw the task-local values bound when the queue was created
  rather than the caller's. Since `MainActor.queue` is created lazily, it
  handed its first caller's task-local values to every later caller.
- Operations ran at the drain loop's priority rather than the caller's,
  and awaiting the returned task did not escalate the operation.

Now each `Task(on:)` runs its operation in the task it returns, so
task-local values, priority, escalation, and cancellation behave as they
do for `Task`. Tasks take turns in the order in which they are enqueued:
each waits for its predecessor to become isolated to the adopted actor,
and ends its own turn as soon as it is isolated, which lets the next
task hop to the actor but not run until the current operation suspends
or returns.

The queue's `name` named the drain task, which no longer exists, so
`ActorQueue(name:)` is removed in favor of `ActorQueue()`.

`ManualTaskExecutor` and `ManualSerialExecutor` keep themselves alive
while `enqueue(_:)` runs. The runtime calls `enqueue(_:)` without
keeping the executor alive. When another thread enqueues the job that
lets a test finish, `yield()` resumes the test, and the test can run the
job and release the executor before `yield()` returns, so `yield()`
would go on to use freed memory. Tests added later in this series
crashed this way on Linux about once in 300,000 runs, in
`_dispatch_queue_dispose` or in `AsyncStream`.

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-6-actor-queue-turns branch from e07cf88 to 779736e Compare November 16, 2026 23:40
@dfed
dfed merged commit bb0e83b into main Nov 17, 2026
12 of 22 checks passed
@dfed
dfed deleted the claude/2.0-6-actor-queue-turns branch November 17, 2026 02:27
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