Repository navigation
Run ActorQueue operations in the task returned to the caller - #91
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
6af1761 to
eaf4480
Compare
eaf4480 to
e07cf88
Compare
|
Build Xcode (visionOS) failed on 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 One thing in the log could point at the library instead. Every test that uses the shared 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 Generated by Claude Code |
|
Correction: the CodeQL Swift failure I reported here is fixed by 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
e07cf88 to
779736e
Compare
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:
.hightask overtook an earlier.lowone. In 20 tasks alternating.lowand.high, 199 of 200 runs were out of order.MainActor.queueis created lazily, it handed its first caller's task-local values to every later caller for the life of the process.Now each
Task(on:)runs its operation in the task it returns, so task-local values, priority, escalation, and cancellation behave as they do forTask. 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 ofActorQueue(): the name labeled the drain task, which no longer exists. TheTask(on:)signatures don't change.Tests
These fail on the parent and pass here:
task_,throwingTask_,mainTask_andmainThrowingTask_holdsTurnUntilItIsIsolatedTo{Actor,MainActor}hold a task on its way to the actor, on aManualSerialExecutorthat 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_andmainTask_seesCallersTaskLocalValues), including the leak throughMainActor.queue.Utilities/ManualExecutors.swiftaddsManualTaskExecutor,ManualSerialExecutorand a probe-turn helper, so tests decide exactly when a task runs.Both executors keep themselves alive while
enqueue(_:)runs. The runtime callsenqueue(_:)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 beforeenqueue(_:)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_disposeor inAsyncStream. 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 fourActorQueuesendsEventsInOrderloop tests stay. Each initializer'sawait 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 archivecopy:-warnings-as-errors, andswiftformat --lintis clean.ci.ymlunderbash -e, pass, including the atomic-counter check. No line inSourcesorTestsreads zero in the CI run.cancelTasks_actorQueue_cancelsCurrentlyExecutingAndPendingTasks, whose spinner runs onDispatchQueueExecutor, fails 10 of 10 runs (3 pinned to one CPU) when the firstActorQueueinitializer skips registering its task, passes 10 of 10 on the real code, and passes--repetitions 100 --repeat-until failunpinned and pinned. Earlier rounds checked the other tests against mutants the same way.Synchronization.Mutexeven in trivially correct code, so the TSan runs replaceMutexwith a pthread-based lock that TSan understands.Unmanaged.passRetained(self)keeps its retain and release at-Ononeand-O.withExtendedLifetime(self)emits no retain, becauseselfis 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.waitmust checkisFiredand store its continuation in onewithLock,firemust setisFiredand take the waiter in one, andTurns.reservemust read and replace the last turn's signal in one. No test can force a thread switch inside one.ActorQueueinitializer awaitsturn.begin(). Onlymain's probabilistic ordering loops cover a missingawait 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 inlineawait turn.begin()and review covers this.ManualTaskExecutorandManualSerialExecutorwere not built under Xcode. CI is the first run there.🤖 Generated with Claude Code
https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM