Skip to content

Run FIFOQueue operations in the task returned to the caller - #92

Merged
dfed merged 1 commit into
claude/2.0-6-actor-queue-turnsfrom
claude/2.0-7-fifo-queue-turns
Nov 17, 2026
Merged

dfed merged 1 commit into
claude/2.0-6-actor-queue-turnsfrom
claude/2.0-7-fifo-queue-turns

Conversation

@dfed

@dfed dfed commented Nov 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

FIFOQueue gets the same redesign as ActorQueue in #91. Previously each operation ran in a task created by the queue's detached drain loop, so:

  • Operations never saw the caller's task-local values.
  • Operations ran at the drain loop's priority, and three of the four Task(on:) initializers dropped priority from the returned task.
  • Awaiting the returned task did not escalate the operation.

Now the returned task waits its turn, runs the operation, and lets its successor begin. Tasks still begin and end in enqueue order.

A queue's priority is now a floor. A task enqueued with, or from a context with, a lower priority runs at the queue's priority. The comparison uses the priority Task itself would give the new task:

  • Inside a task, that is the enqueuing task's base priority, ignoring escalation.
  • Outside a task, it is the thread's priority, or .medium if the thread has none.
  • An inherited user-interactive priority is lowered to user-initiated.
  • A priority with a raw value of zero counts as no priority.

A queue without a priority no longer raises every task to .medium.

FIFOQueue(name:priority:) is removed in favor of FIFOQueue(priority:): the name labeled the drain task, which no longer exists. The FIFOQueue(priority:) doc comment is reworded to say plainly which priority each task runs at. Delivery and its tests are deleted, and Semaphore moves to the test target.

This series' own guard statements are restored. The review round that removed early returns had rewritten them too, but as clarified since, guard is fine: only an early return from an if without an else is avoided. Here that is the guard in priorityOfNewTask(enqueuedWith:) for an inherited priority with a raw value of zero, which the previous revision had written as an if/else. The if statements in priority(forTaskEnqueuedWith:) and priorityOfNewTask(enqueuedWith:) keep their else. Behavior is unchanged.

Tests

These fail on the parent and pass here:

  • Turn order, without timing. task_, throwingTask_, taskIsolatedTo_ and throwingTaskIsolatedTo_holdsTurnUntilItsOperationReturns check through a probe turn that the next turn cannot begin while an operation is still running, and throwingTask_ and throwingTaskIsolatedTo_whenOperationThrows_allowsNextTaskToBegin that a throwing operation still ends its turn.
  • Task-locals, for every FIFOQueue and CancellableQueue overload.
  • Nil-priority inheritance, and explicit priorities.
  • The floor, including enqueuing from an escalated task, from a thread outside any task, with a raw-zero priority, and at a user-interactive floor.
  • Escalation when the returned task is awaited.

main's FIFO ordering loops (sendsEventsInOrder), the four executesAsyncBlocksAtomically tests and task_/throwingTask_isNotReentrant stay: they are the only guard for a Task(on:) initializer that skips await turn.begin() and for a task enqueued from a task already running on the same queue. taskIsolatedTo_isNotReentrant and throwingTaskIsolatedTo_isNotReentrant are deleted: tasks isolated to the same actor are serialized by that actor, so they could not observe a reentrant turn, and every bug they caught at any rate fails a remaining test 10 of 10 times.

SemaphoreTests cover the test-only Semaphore, which moves here. Five new tests run each waiter as a task on a ManualTaskExecutor, so once a test has run the executor until it is idle, every waiter has either returned from wait() or is suspended in it:

  • signal_whenSignalCallsReachSuspendedWaitCalls_resumesEveryWaiterAtOnce (3 waiters) and signal_whenSignalCallsReachAThousandSuspendedWaitCalls_resumesEveryWaiterAtOnce (1,000 waiters) check, after every signal(), that no waiter resumes until the signals match the waits and that then every waiter resumes, and check isWaiting along the way;
  • wait_whenPrecededByFewerSignalCalls_suspendsOnlyTheUnmatchedWait checks what wait() returns when earlier signals match some of the waits;
  • wait_afterEveryWaiterResumed_suspendsUntilSignaledAgain runs a second round of waiters;
  • wait_whenSignalCallIsEnqueuedBehindIt_resumes enqueues a signal behind a waiter on the same executor, which catches a lost wakeup between wait()'s decrement and its storing its continuation.

Against 30 mutants of Semaphore, every mutant but one fails at least one new test 10 of 10 runs, 3 of them pinned to one CPU; one of those kills (a mutant that resumes continuations twice) is a crash. The survivor resumes waiters in reverse order. No test catches it, including the two older tests, and Semaphore promises no order. The older wait_suspendsUntilEqualNumberOfSignalCalls (1,000 waiters and a yield loop) and wait_doesNotSuspendIfSignalCalledFirst are therefore deleted, along with the Semaphore extension and counter that only they used: they catch no mutant that the new tests miss. With them gone, no line of Semaphore or SemaphoreTests reads zero in the Linux job's coverage steps.

signal()'s doc comment now says that it resumes every waiting task once the count is zero or more, rather than "a waiting thread".

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

Series

PR 8 of 10. It is stacked on #91.

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.
  • Each new SemaphoreTests test passes 10 of 10 runs (3 pinned to one CPU) on the real code and --repetitions 100 --repeat-until fail unpinned and pinned; the mutant results are under Tests. The restored guard in priorityOfNewTask(enqueuedWith:) was rechecked: returning the raw-zero inherited priority instead of .medium fails task_onQueueWithPriority_enqueuedOutsideOfAnyTask_executesAtHigherOfNewTaskAndQueuePriority 10 of 10 runs, as it did against the if/else form. 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.

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 FIFOQueue initializer awaits turn.begin(). A missing await turn.begin() in one initializer fails only the probabilistic executesAsyncBlocksAtomically loop for that initializer (10 of 10 runs in our checks, including pinned to one CPU). 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. SemaphoreTests now run their waiters on a ManualTaskExecutor through Task(executorPreference:); nothing was 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 (779736e) to head (a442493).

Additional details and impacted files

Impacted file tree graph

@@                        Coverage Diff                        @@
##           claude/2.0-6-actor-queue-turns       #92    +/-   ##
=================================================================
  Coverage                          100.00%   100.00%            
=================================================================
  Files                                  14        12     -2     
  Lines                                1739      1865   +126     
=================================================================
+ Hits                                 1739      1865   +126     
Files with missing lines Coverage Δ
Sources/AsyncQueue/FIFOQueue.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/SemaphoreTests.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/Utilities/Semaphore.swift 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/FIFOQueue.swift Resolved
Comment thread Sources/AsyncQueue/FIFOQueue.swift Resolved
@dfed
dfed force-pushed the claude/2.0-7-fifo-queue-turns branch 2 times, most recently from 071e02d to 319308a Compare November 14, 2026 07:30
@dfed
dfed force-pushed the claude/2.0-7-fifo-queue-turns branch from 319308a to 1f23244 Compare November 15, 2026 15:45
@dfed
dfed force-pushed the claude/2.0-7-fifo-queue-turns branch from 1f23244 to 601ea69 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: I was wrong that this needed a decision. 9a40bac on #88 now builds the CodeQL Swift job with --disable-sandbox, and the job passes: Analyze (swift) succeeded on #97's rebased head (70d113b).

What happened, for the record. On 601ea69, Analyze (swift) failed after #88 moved the job to xcode-27 with Xcode 27.2:

  • CodeQL warned "Traced analysis is not supported on macOS 27 or above".
  • swift build then failed with posix_spawn error: Bad CPU type in executable (86), launching the package manifest through SwiftPM's sandbox-exec.

From that warning and GitHub's changelog for 2026-10-19, I concluded CodeQL couldn't analyze this package at all. That was wrong: the error came from SwiftPM's sandbox, and building without the sandbox avoids it.


Generated by Claude Code

Previously each operation ran in a task created by the queue's detached
drain loop, and the returned task waited on a continuation for the
result. As a result:

- Operations never saw the caller's task-local values.
- Operations ran at the drain loop's priority rather than the caller's,
  and three of the four `Task(on:)` initializers dropped `priority` from
  the returned task.
- 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 finish, runs, and then lets its
successor begin.

A queue's priority is now a floor: a task enqueued with, or from a
context with, a lower priority executes at the queue's priority. The
comparison uses the priority `Task` would give the new task: the
enqueuing task's base priority, ignoring escalation, or outside of a
task the thread's priority, which defaults to `.medium`; an inherited
user-interactive priority is lowered to user-initiated, and a priority
with a raw value of zero counts as no priority. A queue without a
priority no longer raises every task to the drain loop's priority.

The queue's `name` named the drain task, which no longer exists, so
`FIFOQueue(name:priority:)` is removed in favor of
`FIFOQueue(priority:)`. Its doc comment is reworded to say plainly which
priority each task runs at.

`Delivery` is no longer used, so it and its tests are deleted.
`Semaphore` is now used only by tests, so it moves to the test target.

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-7-fifo-queue-turns branch from 601ea69 to a442493 Compare November 16, 2026 23:40
@dfed
dfed merged commit 52cec6b into main Nov 17, 2026
12 of 22 checks passed
@dfed
dfed deleted the claude/2.0-7-fifo-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