Skip to content

Cancel tasks outside of CancellableQueue's lock - #87

Merged
dfed merged 1 commit into
claude/2.0-1-delivery-cancel-outside-lockfrom
claude/2.0-2-cancel-tasks-outside-lock
Nov 17, 2026
Merged

dfed merged 1 commit into
claude/2.0-1-delivery-cancel-outside-lockfrom
claude/2.0-2-cancel-tasks-outside-lock

Conversation

@dfed

@dfed dfed commented Nov 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

CancellableQueue.cancelTasks() invoked every registered cancel closure while holding the queue's lock. A cancellation handler that called cancelTasks() on the same queue re-entered DispatchQueue.sync and trapped with SIGILL.

This change collects the cancel closures under the lock and invokes them after releasing it. The doc comment now notes the cost of not cancelling under the lock: when another cancelTasks() call is in progress, a call can return before that call finishes cancelling the tasks it found. Re-cancelling every task from every call would close that window, but under stress it slows down quadratically.

Tests

  • cancelTasks_{fifoQueue,actorQueue}_canBeCalledFromCancellationHandler crash 10 of 10 times on the parent and pass here. The task waits in suspendUntilCancelled() from Cancel queued tasks outside of Delivery's lock #86, and the test cancels it explicitly at the end, so a regression that keeps cancelTasks() from reaching it fails the test rather than leaving the task running.
  • The three cancelTasks_*_doesNotCancelFutureTasks tests are rewritten without timing: each waits for the task to end, then calls cancelTasks() once more, which at this commit returns only once the queue has processed every earlier registration, and checks that the task was not cancelled. Replace DispatchQueue-backed locks with Mutex #89 drops that second call once registration is synchronous.
  • Thirteen gap tests check the queue's bookkeeping directly, across the Task(on:) initializers of each queue:
    • …doesNotCancelCompletedNonthrowingTask (4), cancelTasks_fifoQueue_doesNotCancelCompletedThrowingTaskIsolatedToActor (a throwing initializer whose operation returns) and …ThatThrew (4): a task that has finished, by returning or throwing, is not cancelled by a later cancelTasks();
    • …cancelsCurrentlyExecutingThrowingTask (4): a running throwing task is cancelled.
  • The spinning task in cancelTasks_actorQueue_cancelsCurrentlyExecutingAndPendingTasks now runs on a DispatchQueueActor, an actor with a dispatch-queue executor of its own, so it cannot occupy a cooperative thread that the test needs, which could hang on a single CPU. Both spinner tests spin on while !Task.isCancelled {}, cancel the spinner explicitly at the end and await every task, so every line runs in every passing run.
  • DispatchQueueExecutor implements enqueue(_ job: UnownedJob) with an explicit asUnownedSerialExecutor(), because main's deployment targets predate ExecutorJob. Raise minimum Swift, Xcode, and platform versions #88 switches it to ExecutorJob when it raises the minimums.

Series

PR 3 of 10. It is stacked on #86, but it is independent of it and could be retargeted to #95. It changes no API, so it can ship in a 1.x patch release together with #86.

Validation

Each commit in the series was validated on its own, on Linux, from a git archive copy. For this PR, with Swift 6.2.4 as the swift:6.2 job uses:

  • It builds with Swift 6.2.4 and 6.4.2, and swiftformat --lint is clean. The test target has exactly the nine weak var warnings it inherits from main, which Raise minimum Swift, Xcode, and platform versions #88 fixes, and no others.
  • The full suite passed 7 runs unpinned and 3 with the test runner pinned to one CPU.
  • The linux-6-2 job's coverage steps, run from this commit's 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 or in 4 more runs of the test binary (2 pinned).
  • This round changed no test here. Rechecked on this commit: each cancelsCurrentlyExecutingThrowingTask gap test fails 10 of 10 runs (3 pinned to one CPU) when its initializer skips registering the task's cancellation. 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:

  • CancellableQueue: one critical section each. cancelTasks() must collect the cancel closures in a single critical section, and the reservation, registration and removal of a task must each be a single critical section. No test can force a thread switch inside one.
  • The timeout is the failure signal for re-entry. Here, cancelling under the lock again would trap in DispatchQueue.sync, so the canBeCalledFromCancellationHandler tests would crash. From Replace DispatchQueue-backed locks with Mutex #89 on, the lock is a Mutex, and re-entering it would deadlock instead: the tests would hang, and CI would report the job stopping after 15 minutes (50 for the simulator jobs).
  • Darwin. DispatchQueueExecutor's enqueue(_: UnownedJob) and a user-defined unownedExecutor at the macOS 10.15 deployment target were not built under Xcode. CI is the first build 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 (5fbedc8) to head (bc2f49d).

Additional details and impacted files

Impacted file tree graph

@@                             Coverage Diff                              @@
##           claude/2.0-1-delivery-cancel-outside-lock       #87    +/-   ##
============================================================================
  Coverage                                     100.00%   100.00%            
============================================================================
  Files                                             12        12            
  Lines                                           1298      1510   +212     
============================================================================
+ Hits                                            1298      1510   +212     
Files with missing lines Coverage Δ
Sources/AsyncQueue/CancellableQueue.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/CancellableQueueTests.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.

`cancelTasks()` invoked every registered cancel closure while holding the
queue's lock. A cancellation handler that called `cancelTasks()` on the
same queue re-entered `DispatchQueue.sync` and trapped.

Collect the cancel closures under the lock and invoke them after
releasing it.

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-2-cancel-tasks-outside-lock branch from 2425565 to bc2f49d Compare November 15, 2026 15:45
@dfed
dfed added this pull request to stack #103 November 16, 2026 21:42
@dfed
dfed merged commit 1e8ab22 into main Nov 17, 2026
12 of 20 checks passed
@dfed
dfed deleted the claude/2.0-2-cancel-tasks-outside-lock 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