Skip to content

Escalate the task holding the current turn on behalf of waiting tasks - #94

Merged
dfed merged 4 commits into
claude/2.0-8-document-behaviorfrom
claude/2.0-9-escalate-turn-holder
Nov 17, 2026
Merged

dfed merged 4 commits into
claude/2.0-8-document-behaviorfrom
claude/2.0-9-escalate-turn-holder

Conversation

@dfed

@dfed dfed commented Nov 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

This is a prototype. It is safe to drop if you don't want it.

A task waiting for its turn could not make the tasks ahead of it run any sooner: a .high task behind a .background task waited at .background speed.

Where the runtime supports SE-0462 (the 26 releases of Apple platforms and later, and Linux), a waiting task now escalates the task holding the current turn to its own priority. It does so when it starts waiting and again whenever it is itself escalated while waiting.

  • The current turn is held by the earliest turn that has not ended, even if its task hasn't started running.
  • When a turn ends, the next turn's task is escalated to the highest waiting priority before it is resumed, so it is scheduled at that priority.
  • Only the task holding the current turn is escalated, and waiting priorities are tracked in a per-priority count. Escalation is therefore constant-time however many tasks are waiting.
  • Escalating by awaiting each predecessor's task would recurse once per waiting task, which crashed with 30,000 or more waiting tasks in an earlier prototype. Here, a backlog of 1,000,000 tasks whose last task is awaited at .high drains in about 2–3 s.

To escalate another task, the queue holds a reference to each task from creation until its turn ends. Turns(escalatesPriority: false) lets tests cover the path that older runtimes take.

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 seven guard statements in register(escalation:for:), escalateHolder(to:), wait(for:as:recordingPriority:), waitingTicket(_:wasEscalatedTo:) and Turn.register(_:), which the previous revision had rewritten to build one result and return it at the end. Behavior is unchanged.

Third commit: escalate the task holding the turn outside the escalation handler. A second review found a deadlock. The runtime holds a task's status lock while it runs the task's cancellation and escalation handlers. A waiting task's escalation handler escalated the task holding the turn before returning, which takes the holder's status lock while the waiting task's is held. A cancellation handler on the holder that cancels the waiting task, or calls cancelTasks(), takes the same two locks in the opposite order, so the two threads could block each other forever.

  • Turns.waitingTicket(_:wasEscalatedTo:) still records the escalation before it returns, but escalates the holder from a new task created at the escalated priority (Task.detached(priority:)).
  • A task is created only when an escalation raises the holder's priority: 5 of the suite's 10,009 calls, at about 3 µs each on Linux. Enqueuing is unchanged.
  • Escalation of the holder is now asynchronous. If the turn ends first, end() still escalates the next task to the highest recorded waiting priority, so no escalation is lost; a late escalation can only raise the priority of a task whose turn has ended.
  • register, wait and end still escalate synchronously: none of them runs inside a handler the library installs.
  • Plain tasks that await each other have the same hazard inside the runtime, which escalates an awaited task under the waiting task's lock. This change removes the library's part of it.

Fourth commit: keep the deadlock tests off the cooperative thread pool while the status lock is held. Test-only. In the third commit's two regression tests, the test could cancel the first task before it had suspended, and the test task then needed a thread from the shared pool before it could let the cancellation handler return. With enough copies running at once, every pool thread could be blocked on a status lock while every test task waited for a thread, so whether the tests finish depended on load.

  • The first task now waits on a ManualTaskExecutor, so it is known to be suspended before the test cancels it.
  • The test escalates the waiting task and lets the handler return from a dispatch queue of its own, which it starts before it cancels, so nothing in that window needs a pool thread.
  • A new ManualTaskExecutor.runUntil(_:) runs the executor each time a job is enqueued until a condition holds, and replaces a private helper in TestHelpersTests.

Behavior to be aware of

  • Escalation is permanent. As with any escalation, an escalated task keeps its priority until it completes. On an ActorQueue, that includes the rest of its operation, not only its wait for the actor. The docs and README say so.
  • Shared queues can reorder. On a shared queue such as MainActor.queue, a higher-priority task enqueued by unrelated code escalates the tasks ahead of it. Work those tasks do after their first suspension can then overtake work from earlier tasks that weren't escalated. That stays within ActorQueue's documented guarantee, which only covers order up to the first suspension. However, two existing tests relied on stricter ordering on the shared queue, so they now use a queue of their own.
  • Cost: about 0.6 µs extra per waiting FIFOQueue task on Linux.

Tests

The tests run waiting tasks on a ManualTaskExecutor, so each test decides when every task runs, and they observe priority from outside the task, so awaiting can't escalate the task being measured. None sleeps or waits with a time limit. So that tests can drive turns and observe their state, Turn.ticket and Ticket, which hold a turn's state, are internal rather than private, and the second commit makes Turns.waitingTicket(_:wasEscalatedTo:) internal for the same reason. The escalation tests are marked @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *), so Swift Testing reports them as skipped on older OS versions.

  • Queue escalation (ActorQueueTests, FIFOQueueTests), which fails on the parent: the task holding the turn is escalated by a higher-priority task that starts waiting behind it, for every FIFOQueue initializer and for an ActorQueue task that is still waiting for a busy actor; and a task is escalated when its turn begins while a higher-priority task waits, for FIFOQueue's nonthrowing initializer and ActorQueue's throwing and main-actor initializers.

  • TurnsTests, which test Turns directly:

    • waiting without escalation, the path older runtimes take, and turns beginning in order of reservation on that path;
    • recording a waiting task until its turn begins, and making a turn current once every earlier turn has ended (two turns, each with a higher-priority waiter);
    • escalating the holder when a waiting task is escalated, behind a 10,000-task backlog;
    • registering a task after a higher-priority task begins waiting, including for a later turn, after higher and then lower waiters, after the turn ended, and with an escalation handler that calls back into Turns;
    • ending a turn: releasing its task, releasing later turns while an earlier one is retained, and handing the highest waiting priority to the next task before resuming it, or not once the higher-priority waiters stopped waiting.
  • Escalation while waiting (second commit): begin_whenWaitingTaskIsEscalated_recordsEscalationAndEscalatesTaskHoldingTurn escalates a task that already waits, so only its escalation handler can deliver the escalation, and reads the recorded priority through a test-only highestWaitingPriority accessor.

  • Escalations in orders the runtime cannot be made to produce (second commit): Turns.waitingTicket(_:wasEscalatedTo:), which a waiting task's escalation handler calls, is internal rather than private, and two tests call it directly:

    • waitingTicket_beforeTaskIsRecordedAsWaiting_doesNotRecordTask delivers an escalation before the task is recorded as waiting;
    • waitingTicket_afterEscalationToHigherPriority_ignoresEscalationToLowerPriority delivers an escalation to .high and then a late one to .medium, both through waitingTicket, so it does not depend on the runtime running escalation handlers synchronously.
    • They fail 10 of 10 runs against a Turns that records an escalation for a task that is not waiting yet, or that accepts an escalation to a lower priority, respectively.
  • Lock-order deadlock (third commit), both deterministic and both hang on the previous revision:

    • begin_whenWaitingTaskIsEscalatedWhileTaskHoldingTurnRunsCancellationHandler_escalatesTaskHoldingTurnWithoutWaitingForHandler (TurnsTests) and cancelTasks_fifoQueue_whileTaskWaitingForItsTurnIsEscalated_escalatesTaskHoldingTurnWithoutWaitingForCancellationHandler (CancellableQueueTests). The holder's cancellation handler, run from a dispatch queue of its own, holds the holder's status lock until the test's waitingTask.escalatePriority(to: .high) returns. Signals and semaphores order every step.
    • The three tests that read the holder's priority right after escalating a waiting task now wait for it with a new suspendUntilEscalated(to:) helper, which suspends until the task reaches a priority and hangs if it never does. TestHelpersTests runs the helper on a ManualTaskExecutor, so every line of it is covered whatever the timing.
    • The fourth commit keeps both tests' names and assertion. They still hang 5 of 5 runs if the escalation handler escalates the holder before returning, or never escalates it.

Series

PR 10 of the 2.0 series. It is stacked on #93, and #96 is stacked on it.

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, which fails when the flag is dropped. No line in Sources or Tests reads zero in the CI run.

  • The two waitingTicket tests fail 10 of 10 runs (3 pinned to one CPU) against the mutants named under Tests, pass 10 of 10 on the real code, and pass --repetitions 100 --repeat-until fail unpinned and pinned. The restored guard statements in Turns were rechecked: the 29 Turns mutants that earlier rounds wrote against the if/else form were ported to the guard form, and at the first commit each port fails exactly the tests that its original fails on the previous revision (full suite, 2 runs unpinned and 1 pinned). Each port that fails a test fails one of them 10 of 10 runs alone (3 pinned). Five survive in both forms: two that move wait's work across its lock (checking hasEnded in a separate critical section, or resuming inside the lock) and one that reads Task.currentPriority before taking it, which the checklist below leaves to review; one that cannot be reached (escalateHolder with no holder); and one with no effect a test can observe (recording a task whose predecessor has already ended, which begin removes again at once). 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 third commit, at its own commit and at the top of the series: the full suite passed 5 runs unpinned and 3 pinned to one CPU, and the coverage steps leave no line in Sources or Tests unexecuted in 10 runs (5 pinned). With the synchronous escalation restored, both deadlock tests hang 5 of 5 runs; with the holder's escalation dropped, they and the three changed tests hang 3 of 3. The 6.4.2 runtime source shows swift_task_cancel and swift_task_escalate running a task's handlers under its status lock, and a backtrace of the hang shows both threads blocked there.

  • The fourth commit, at its own commit and at the top of the series:

    • The full suite passed 10 runs, and the coverage steps leave no line in Sources or Tests unexecuted.
    • To starve the pool on purpose, a harness let it run nothing between two jobs that the test enqueues from its own dispatch threads. The old tests hung 59 of 60 times and the new ones 0 of 60. Under real load, with up to 256 copies on one CPU next to CPU-bound work, neither form hung, so this removes a risk rather than a failure seen in practice.
    • The two tests ran together 5.8 million times at the top of the series, and the suites that use the manual executors ran 2,000 times each, with no failure, crash or hang.

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

Review checklist

Left for code review because no test can force them:

  • Turns: one critical section each. wait must check previousTicket.hasEnded and store its continuation as the successor in one withLock, and reserve must read and replace lastTicket in one. No test can force a thread switch inside one.
  • Task.currentPriority is read inside the same withLock that records ticket.waitingPriority. Reading it before taking the lock opens a window in which an escalation reaches the escalation handler before the task is recorded and is lost. The runtime offers no way to escalate a task at that exact point.
  • Every queue initializer awaits turn.begin(). This PR adds a register call to every initializer; each must still await its turn before running its operation. Only main's ordering loops cover a missing await turn.begin().
  • The fallback path's multi-waiter order. Without escalation (macOS 15–25, iOS 18–25 and the other pre-26 releases), the queues take Turns(escalatesPriority: false)'s path. begin_withoutEscalation_beginsTurnsInOrderOfReservation checks its order at the Turns level; no queue-level test runs that path, so the queues' order there is checked only through shared code.
  • Darwin. The escalation tests assume that escalatePriority(to:) runs a task's escalation handler synchronously, and the main-actor tests assume the main actor runs jobs in FIFO order. Both hold on Linux and were not checked on Apple platforms.
  • The timeout is the failure signal for hang-type regressions. If a turn's end stops resuming its successor, several escalation tests hang rather than fail; CI reports that as the job stopping after 15 minutes (50 for the simulator jobs).

🤖 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 (ab0abd7) to head (1fec6fc).

Additional details and impacted files

Impacted file tree graph

@@                        Coverage Diff                         @@
##           claude/2.0-8-document-behavior       #94     +/-   ##
==================================================================
  Coverage                          100.00%   100.00%             
==================================================================
  Files                                  12        14      +2     
  Lines                                1876      2890   +1014     
==================================================================
+ Hits                                 1876      2890   +1014     
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/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/TestHelpersTests.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/TurnsTests.swift 100.00% <100.00%> (ø)
...ts/AsyncQueueTests/Utilities/ManualExecutors.swift 100.00% <100.00%> (ø)
... and 1 more
🚀 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-9-escalate-turn-holder branch from 32cf5a6 to 2a7f3a8 Compare November 14, 2026 07:06
@dfed
dfed force-pushed the claude/2.0-9-escalate-turn-holder branch from 2a7f3a8 to eb86881 Compare November 14, 2026 07:30
@dfed
dfed force-pushed the claude/2.0-9-escalate-turn-holder branch from eb86881 to d702536 Compare November 15, 2026 15:45
@dfed
dfed force-pushed the claude/2.0-9-escalate-turn-holder branch 2 times, most recently from 9f3b26e to 2c1f90f 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, 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

A task waiting for its turn could not make the tasks ahead of it run any
sooner: a `.high` task enqueued behind a `.background` task waited at
`.background` speed.

Where the runtime supports SE-0462 (the 26 releases of Apple platforms
and later, and other platforms with a Swift 6.2 or later runtime), a task
waiting for its turn now escalates the task holding the current turn to
its own priority, both when it starts waiting and whenever it is itself
escalated while it waits. The current turn is held by the earliest turn
that has not ended, even if its task has not started running yet. When
a turn ends, the next turn's task is escalated to the highest priority of
the tasks still waiting before it is resumed, so it is scheduled at that
priority rather than at its own.

Only the task holding the current turn is escalated, and the queue
tracks waiting priorities in a per-priority count, so escalation is
constant-time however many tasks are waiting. Escalating through a chain
of predecessors instead recurses once per waiting task: an earlier
prototype that awaited each predecessor's task crashed once 30,000 or
more tasks were waiting.

As with any escalation, an escalated task keeps its priority until it
completes. On an `ActorQueue`, that includes the rest of its operation,
not only its wait for the actor. The documentation and README say so.
One visible consequence: on a shared queue such as `MainActor.queue`, a
higher-priority task enqueued by unrelated code escalates the tasks
ahead of it, so work those tasks do after their first suspension can
overtake work of earlier tasks that were not escalated. An `ActorQueue`
only orders tasks up to their first suspension, so this is within its
documented behavior, but two existing tests relied on stricter ordering
on the shared `MainActor.queue`; they now use a queue of their own.

To escalate another task, the queue retains the task's handle from the
moment `Task(on:)` creates it until its turn ends. `Turns` can be created
without escalation so that tests cover the path that older runtimes
take.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM
`begin_whenWaitingTaskIsEscalated_recordsEscalationAndEscalatesTaskHoldingTurn`
escalates a task that is already waiting for its turn, so only the
task's escalation handler can deliver the escalation. It checks that
`Turns` then records the task as waiting at the new priority, without
counting it twice, escalates the task holding the current turn to that
priority, and stops recording the task once its turn begins.

The test reads the recorded priority through a new test-only accessor,
`highestWaitingPriority`, alongside the existing `waitingTaskCount`.

`Turns.waitingTicket(_:wasEscalatedTo:)`, which a waiting task's
escalation handler calls, is now internal rather than private. Two new
tests call it directly to deliver escalations in orders that the
runtime allows but cannot be made to produce on demand: an escalation
that arrives before the task is recorded as waiting, and an escalation
to a lower priority that arrives after one to a higher priority.
`Turns` ignores both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM
The runtime holds a task's status lock while it runs the task's
cancellation and escalation handlers. A waiting task's escalation
handler escalated the task holding the current turn before returning,
and escalating a task takes that task's status lock, so the handler
held the waiting task's lock while it waited for the holder's. A
cancellation handler of the task holding the turn runs under the
holder's lock. If it cancels the waiting task, or calls `cancelTasks()`
on a queue that holds the waiting task, it takes the waiting task's
lock. The two tasks then take the same two locks in opposite orders,
and they can deadlock.

`Turns.waitingTicket(_:wasEscalatedTo:)` still records the escalation
before it returns, but it now escalates the task holding the turn from a
new task, created at the escalated priority, so the escalation handler
never waits for another task's status lock. A task is created only when
an escalation raises the holder's priority. Escalation of the holder is
now asynchronous: it happens when the new task runs, not before
`escalatePriority(to:)` returns. If the turn ends first, `end()`
escalates the next task to the highest recorded waiting priority, as
before, so no escalation is lost. A late escalation can reach a task
whose turn has already ended, which only raises that task's priority.

Plain tasks that await each other have the same hazard in the runtime,
which escalates an awaited task while it holds the waiting task's
status lock. This change removes the library's part of it.

Two new tests, one on `Turns` and one through `cancelTasks()`, escalate
a waiting task while the holder's cancellation handler holds the
holder's status lock until that escalation returns. They are
deterministic, and they hang if the escalation handler escalates the
holder before returning. Tests that checked the holder's priority right
after escalating a waiting task now wait for the escalation to arrive,
with a new `suspendUntilEscalated(to:)` helper that suspends until the
task reaches a priority and hangs if it never does. New tests of the
helper run it on a manual executor, so they cover each of its paths
whatever the timing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM
…k is held

The two lock-order regression tests hold the first task's status lock in
its cancellation handler until escalating the waiting task returns. Two
things in that window needed a thread from the cooperative thread pool.

The first task ran on the pool and announced that its cancellation
handler was installed before it suspended. The test could cancel it in
between, and a task that suspends or resumes while another thread holds
its status lock blocks its thread until the lock is released. The test
task then had to resume from an `AsyncStream` before it could escalate
the waiting task and release the lock. With enough copies running at
once on a slow machine, every pool thread could be blocked by a first
task while every test task waited for a thread, so whether the tests
finish depended on load.

The first task now waits on a `ManualTaskExecutor`, so it is suspended
before it is cancelled. In the `Turns` test it prefers the executor for
its whole life. In the `CancellableQueue` test, `Task(on:)` creates an
unstructured task, which doesn't inherit a task executor preference, so
the operation waits inside `withTaskExecutorPreference(_:)`, and the
test runs it once it moves to the executor. Neither task is running once
`runUntilIdle()` returns, and only then does the test cancel.

The test now escalates the waiting task on a dispatch queue of its own,
and dispatches that work before it cancels the first task, so the test
task has nothing left to do once the cancellation handler runs. The
cancellation handler signals a `DispatchSemaphore`. The escalation's
queue waits for it, escalates the waiting task, signals the handler to
return, and then resumes the test, so nothing in the window waits for a
pool thread. A pool thread may still wait for the first task's status
lock for a moment, as when the library escalates the first task from a
new task, but the thread that holds the lock is a dispatch thread that
never needs the pool. The tests still hang if the waiting task's
escalation handler escalates the task holding the turn before it
returns, or never escalates it.

`ManualTaskExecutor.runUntil(_:)` runs the executor each time a job is
enqueued until a condition holds. It replaces the private helper in
`TestHelpersTests`, and the two tests use it to run both tasks to the
end.

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-9-escalate-turn-holder branch from 2c1f90f to 1fec6fc Compare November 16, 2026 23:40
@dfed
dfed merged commit 7aa01df into main Nov 17, 2026
12 checks passed
@dfed
dfed deleted the claude/2.0-9-escalate-turn-holder 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