Skip to content

Cancel queued tasks outside of Delivery's lock - #86

Merged
dfed merged 1 commit into
claude/2.0-0-atomic-coveragefrom
claude/2.0-1-delivery-cancel-outside-lock
Nov 17, 2026
Merged

dfed merged 1 commit into
claude/2.0-0-atomic-coveragefrom
claude/2.0-1-delivery-cancel-outside-lock

Conversation

@dfed

@dfed dfed commented Nov 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Delivery.cancel() called Task.cancel() while holding a lock backed by a single, process-wide serial DispatchQueue. Cancellation handlers run synchronously, so a handler that cancelled another queued task, on any queue, re-entered DispatchQueue.sync and trapped with SIGILL. Forwarding cancellation to an inner task is a common pattern, so ordinary code hits this:

let outer = Task(on: queueA) {
	let inner = Task(on: queueB) { await work() }
	await withTaskCancellationHandler { await inner.value } onCancel: { inner.cancel() }
}
outer.cancel() // traps

This change reads the task under the lock and cancels it after releasing the lock. It also gives each Delivery its own lock.

Tests

  • task_canBeCancelledFromCancellationHandlerOfAnotherQueuedTask (FIFOQueue and ActorQueue) crashes 10 of 10 times against the parent's Delivery and passes here. The inner task waits in a new suspendUntilCancelled() helper (Utilities/TestHelpers.swift), which returns only once the task is cancelled and involves no sleep. If cancellation stops reaching the inner task, the test hangs until the CI job's timeout rather than failing an expectation.
  • mainTask_cancelledWhileMainActorIsBusy_executesOperationCancelled (ActorQueue) and task_cancelledWhileWaitingForPriorTask_executesOperationCancelled (FIFOQueue) cancel a task before its operation begins and check that the operation then runs cancelled. The ActorQueue test cancels while the test itself occupies the main actor, and the FIFOQueue test while an earlier task waits on a semaphore, so the cancellation always lands first, with no sleep.
  • DeliveryTests.getValue_whenValueIsSentAfterGetValueSuspends and getValueThrowing_whenFailureIsSentAfterGetValueSuspends send the value or failure only once getValue() has suspended, so the path that resumes a suspended getValue() runs in every run.

Series

PR 2 of 10 in a 2.0 series (#95, then #86 through #94, each stacked on the previous one). It is stacked on #95, which adds atomic coverage counters, their check and job timeouts to CI and removes the unused Expectation helper, and which is based on main. This PR changes no API, so it can ship in a 1.x patch release together with #87.

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. Across the CI run and 4 more runs of the test binary (2 pinned), the only lines in Sources or Tests that read zero are the four spinner lines of main's CancellableQueueTests that Update coverage counters atomically and time out test jobs #95 describes; Cancel tasks outside of CancellableQueue's lock #87 rewrites them.
  • This round changed no test here. Rechecked on this commit: both task_canBeCancelledFromCancellationHandlerOfAnotherQueuedTask tests crash 10 of 10 runs (3 pinned to one CPU) against the parent's Delivery, pass 10 of 10 here, and pass --repetitions 100 --repeat-until fail unpinned and pinned. 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:

  • Delivery: one critical section each. cancel() must set isCancelled and read the task in a single withLock, and execute must store the task and read isCancelled in a single withLock. Splitting either lets a cancellation slip between the two and be lost. No test can force a thread switch inside that window.
  • The timeout is the failure signal. If cancellation stops reaching the inner task, task_canBeCancelledFromCancellationHandlerOfAnotherQueuedTask hangs; CI reports that as the job stopping after 15 minutes (50 for the simulator jobs).
  • Darwin. Nothing was run on Apple platforms; the new tests' handshakes rely only on documented actor and queue ordering.

🤖 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 (02d93e6) to head (5fbedc8).

Additional details and impacted files

Impacted file tree graph

@@                      Coverage Diff                       @@
##           claude/2.0-0-atomic-coverage       #86   +/-   ##
==============================================================
  Coverage                        100.00%   100.00%           
==============================================================
  Files                                11        12    +1     
  Lines                              1209      1298   +89     
==============================================================
+ Hits                               1209      1298   +89     
Files with missing lines Coverage Δ
Sources/AsyncQueue/Utilities/Delivery.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/ActorQueueTests.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/DeliveryTests.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/FIFOQueueTests.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.

`Delivery.cancel()` called `Task.cancel()` while holding a lock backed by
a single process-wide serial queue. Cancellation handlers run
synchronously, so a handler that cancelled any other queued task – on any
queue – re-entered `DispatchQueue.sync` and trapped. Forwarding
cancellation to an inner task is a common pattern, so ordinary code hit
this.

Read the task under the lock and cancel it after releasing the lock, and
give each `Delivery` its own lock so unrelated tasks no longer contend.

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-1-delivery-cancel-outside-lock branch from e69a296 to 5fbedc8 Compare November 15, 2026 15:45
@dfed
dfed changed the base branch from main to claude/2.0-0-atomic-coverage November 15, 2026 15:47
@dfed
dfed added this pull request to stack #103 November 16, 2026 21:42
@dfed
dfed merged commit 38ad81b into main Nov 17, 2026
14 checks passed
@dfed
dfed deleted the claude/2.0-1-delivery-cancel-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