Repository navigation
Escalate the task holding the current turn on behalf of waiting tasks - #94
Merged
dfed merged 4 commits intoNov 17, 2026
Merged
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
dfed
force-pushed
the
claude/2.0-9-escalate-turn-holder
branch
from
November 14, 2026 07:06
32cf5a6 to
2a7f3a8
Compare
dfed
force-pushed
the
claude/2.0-9-escalate-turn-holder
branch
from
November 14, 2026 07:30
2a7f3a8 to
eb86881
Compare
dfed
force-pushed
the
claude/2.0-9-escalate-turn-holder
branch
from
November 15, 2026 15:45
eb86881 to
d702536
Compare
This was referenced Nov 15, 2026
dfed
force-pushed
the
claude/2.0-9-escalate-turn-holder
branch
2 times, most recently
from
November 16, 2026 11:40
9f3b26e to
2c1f90f
Compare
Owner
Author
|
Correction: the CodeQL Swift failure I reported here is fixed by 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
force-pushed
the
claude/2.0-9-escalate-turn-holder
branch
from
November 16, 2026 23:40
2c1f90f to
1fec6fc
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
.hightask behind a.backgroundtask waited at.backgroundspeed.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.
.highdrains 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
guardstatements are restored. The review round that removed early returns had rewritten them too, but as clarified since,guardis fine: only an early return from anifwithout anelseis avoided. Here that is sevenguardstatements inregister(escalation:for:),escalateHolder(to:),wait(for:as:recordingPriority:),waitingTicket(_:wasEscalatedTo:)andTurn.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:)).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,waitandendstill escalate synchronously: none of them runs inside a handler the library installs.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.
ManualTaskExecutor, so it is known to be suspended before the test cancels it.ManualTaskExecutor.runUntil(_:)runs the executor each time a job is enqueued until a condition holds, and replaces a private helper inTestHelpersTests.Behavior to be aware of
ActorQueue, that includes the rest of its operation, not only its wait for the actor. The docs and README say so.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 withinActorQueue'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.FIFOQueuetask 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.ticketandTicket, which hold a turn's state, are internal rather than private, and the second commit makesTurns.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 everyFIFOQueueinitializer and for anActorQueuetask that is still waiting for a busy actor; and a task is escalated when its turn begins while a higher-priority task waits, forFIFOQueue's nonthrowing initializer andActorQueue's throwing and main-actor initializers.TurnsTests, which testTurnsdirectly:Turns;Escalation while waiting (second commit):
begin_whenWaitingTaskIsEscalated_recordsEscalationAndEscalatesTaskHoldingTurnescalates a task that already waits, so only its escalation handler can deliver the escalation, and reads the recorded priority through a test-onlyhighestWaitingPriorityaccessor.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_doesNotRecordTaskdelivers an escalation before the task is recorded as waiting;waitingTicket_afterEscalationToHigherPriority_ignoresEscalationToLowerPrioritydelivers an escalation to.highand then a late one to.medium, both throughwaitingTicket, so it does not depend on the runtime running escalation handlers synchronously.Turnsthat 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) andcancelTasks_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'swaitingTask.escalatePriority(to: .high)returns. Signals and semaphores order every step.suspendUntilEscalated(to:)helper, which suspends until the task reaches a priority and hangs if it never does.TestHelpersTestsruns the helper on aManualTaskExecutor, so every line of it is covered whatever the timing.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 archivecopy:It builds with
-warnings-as-errors, andswiftformat --lintis 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.ymlunderbash -e, pass, including the atomic-counter check, which fails when the flag is dropped. No line inSourcesorTestsreads zero in the CI run.The two
waitingTickettests 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 failunpinned and pinned. The restoredguardstatements inTurnswere rechecked: the 29Turnsmutants that earlier rounds wrote against theif/elseform were ported to theguardform, 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 movewait's work across its lock (checkinghasEndedin a separate critical section, or resuming inside the lock) and one that readsTask.currentPrioritybefore taking it, which the checklist below leaves to review; one that cannot be reached (escalateHolderwith no holder); and one with no effect a test can observe (recording a task whose predecessor has already ended, whichbeginremoves 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.Mutexeven in trivially correct code, so the TSan runs replaceMutexwith 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
SourcesorTestsunexecuted 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 showsswift_task_cancelandswift_task_escalaterunning 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:
SourcesorTestsunexecuted.Nothing was run on Apple platforms. CI is the first run there.
Review checklist
Left for code review because no test can force them:
waitmust checkpreviousTicket.hasEndedand store its continuation as the successor in onewithLock, andreservemust read and replacelastTicketin one. No test can force a thread switch inside one.Task.currentPriorityis read inside the samewithLockthat recordsticket.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.turn.begin(). This PR adds aregistercall to every initializer; each must still await its turn before running its operation. Onlymain's ordering loops cover a missingawait turn.begin().Turns(escalatesPriority: false)'s path.begin_withoutEscalation_beginsTurnsInOrderOfReservationchecks its order at theTurnslevel; no queue-level test runs that path, so the queues' order there is checked only through shared code.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.🤖 Generated with Claude Code
https://claude.ai/code/session_01HLuVQLsTNvRnyh155N25UM