Skip to content

Fix CancellableQueue retaining tasks that finish before registration - #81

Merged
dfed merged 2 commits into
dfed:mainfrom
Bortlesboat:fix-cancellable-queue-registration-race
Oct 26, 2026
Merged

dfed merged 2 commits into
dfed:mainfrom
Bortlesboat:fix-cancellable-queue-registration-race

Conversation

@Bortlesboat

Copy link
Copy Markdown
Contributor

A task enqueued on a CancellableQueue can finish before its cancel handle is registered. When that happens, its removal from the map is processed before the registration, so the entry is never removed. The task and its result stay alive, and a later cancelTasks() cancels already-completed tasks. This reserves the identifier before the task starts and skips registration if the identifier is already gone.

The new tests complete 1000 tasks and then call cancelTasks(). They failed every run on Linux (swift:6.2) before this change and pass consistently after it. Not tested on Apple platforms.

@codecov

codecov Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (bf8db34) to head (96944f2).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff            @@
##              main       #81   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           13        13           
  Lines         1297      1313   +16     
=========================================
+ Hits          1297      1313   +16     
Files with missing lines Coverage Δ
Sources/AsyncQueue/CancellableQueue.swift 100.00% <100.00%> (ø)
Tests/AsyncQueueTests/CancellableQueueTests.swift 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dfed dfed left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great find!

Two things before this can merge, both detailed inline with suggestions:

  1. The fix introduces a new race. cancelTasks() removes reservations, so a task enqueued while cancelTasks() is running can end up permanently uncancellable.
  2. The new tests are probabilistic. I'd like them to be deterministic like the rest of the suite, and I've suggested one way to get there. If you see a different way to force the ordering, I'm open to it.

I ran the suggested changes locally and the full suite passes with them.

Comment on lines 50 to 52
$0.removeAll()
}
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removeAll() also removes the nil reservations. If cancelTasks() runs on another thread between a task's reservation and its registration, the registration is skipped because the key is gone. That task is still running but is now untracked, so no later cancelTasks() can cancel it. On main the same task would be registered late and cancelled by the next call.

Keeping the reservations fixes it. This suggestion also moves the bookkeeping into three internal methods so the tests can drive the ordering deterministically (see my comments on the tests).

Suggested change
$0.removeAll()
}
}
// Keep reservations so that tasks that have not yet registered remain cancellable.
$0 = $0.filter { $0.value == nil }
}
}
// MARK: Internal
/// Reserves an identifier for a task that is about to be created.
/// Reserving before the task starts ensures the task's removal of the identifier can never be processed before the reservation.
func reserveTaskIdentifier() -> UUID {
let identifier = UUID()
taskIdentifierToCancelMap.writeAsync {
$0.updateValue(nil, forKey: identifier)
}
return identifier
}
/// Registers the `cancel` closure for a task whose identifier was previously reserved.
func registerCancellation(forTaskWithIdentifier identifier: UUID, _ cancel: @escaping @Sendable () -> Void) {
taskIdentifierToCancelMap.writeAsync {
// Skip registration if the identifier was already removed because the task already finished.
if $0.keys.contains(identifier) {
$0[identifier] = cancel
}
}
}
/// Removes the identifier of a task that has finished executing.
func taskDidFinish(withIdentifier identifier: UUID) {
taskIdentifierToCancelMap.writeAsync {
$0[identifier] = nil
}
}

Comment on lines +90 to +95
let identifier = UUID()
// Reserve the identifier before the task starts so that the task's removal of the identifier
// can never be processed before the task's registration below.
actorQueue.taskIdentifierToCancelMap.writeAsync {
$0.updateValue(nil, forKey: identifier)
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the helpers above, this becomes one line. Could you apply the same change to the other seven initializers?

Suggested change
let identifier = UUID()
// Reserve the identifier before the task starts so that the task's removal of the identifier
// can never be processed before the task's registration below.
actorQueue.taskIdentifierToCancelMap.writeAsync {
$0.updateValue(nil, forKey: identifier)
}
let identifier = actorQueue.reserveTaskIdentifier()

The defer body just below would then become actorQueue.taskDidFinish(withIdentifier: identifier).

Comment on lines 104 to 109
actorQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in
$0[identifier] = cancel
// Skip registration if the identifier was already removed, e.g. because the task already finished.
if $0.keys.contains(identifier) {
$0[identifier] = cancel
}
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, and in the other seven initializers.

Suggested change
actorQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in
$0[identifier] = cancel
// Skip registration if the identifier was already removed, e.g. because the task already finished.
if $0.keys.contains(identifier) {
$0[identifier] = cancel
}
}
actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel)

Comment on lines +163 to +186
@Test
func cancelTasks_actorQueue_doesNotCancelManyCompletedTasks() async {
let actorQueue = ActorQueue<Counter>()
let counter = Counter()
actorQueue.adoptExecutionContext(of: counter)
let systemUnderTest = CancellableQueue(underlyingQueue: actorQueue)

// Create and complete many tasks. A task can finish before it is registered with the queue,
// so use enough tasks to reliably exercise that ordering.
var tasks = [Task<Void, any Error>]()
for _ in 0..<1_000 {
let task = Task(on: systemUnderTest) { _ in
try doWork()
}
_ = await task.result
tasks.append(task)
}

// Now cancel tasks - should have no effect since every task already completed.
systemUnderTest.cancelTasks()

#expect(tasks.allSatisfy { !$0.isCancelled })
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two deterministic tests above cover the bookkeeping for both queue types, so this one can go.

Suggested change
@Test
func cancelTasks_actorQueue_doesNotCancelManyCompletedTasks() async {
let actorQueue = ActorQueue<Counter>()
let counter = Counter()
actorQueue.adoptExecutionContext(of: counter)
let systemUnderTest = CancellableQueue(underlyingQueue: actorQueue)
// Create and complete many tasks. A task can finish before it is registered with the queue,
// so use enough tasks to reliably exercise that ordering.
var tasks = [Task<Void, any Error>]()
for _ in 0..<1_000 {
let task = Task(on: systemUnderTest) { _ in
try doWork()
}
_ = await task.result
tasks.append(task)
}
// Now cancel tasks - should have no effect since every task already completed.
systemUnderTest.cancelTasks()
#expect(tasks.allSatisfy { !$0.isCancelled })
}

@Bortlesboat

Copy link
Copy Markdown
Contributor Author

Thanks, good catch on the removeAll() race. Applied your suggestions across all eight initializers and swapped the probabilistic tests for your two deterministic ones. I also checked that the first fails without the reservation check and the second fails with removeAll() restored.

@dfed
dfed enabled auto-merge (squash) October 26, 2026 04:00
@dfed
dfed merged commit 0f1ec3f into dfed:main Oct 26, 2026
13 checks passed
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