Skip to content

Cancel tasks that are still being enqueued when cancelTasks() is called - #90

Merged
dfed merged 1 commit into
claude/2.0-4-mutexfrom
claude/2.0-5-cancel-enqueuing-tasks
Nov 17, 2026
Merged

dfed merged 1 commit into
claude/2.0-4-mutexfrom
claude/2.0-5-cancel-enqueuing-tasks

Conversation

@dfed

@dfed dfed commented Nov 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

A CancellableQueue reserves an identifier for each task, creates the task on the underlying queue, and only then registers the task's cancel closure. cancelTasks() cancelled only registered tasks. A task that was reserved but not yet registered when cancelTasks() ran was skipped, and nothing cancelled it later unless cancelTasks() was called again. Such a task can already be executing, for example when its own operation calls cancelTasks().

cancelTasks() now marks those reservations. When a marked task registers its cancel closure, it is cancelled immediately, after the lock is released. This bug predates the series; it gets its own PR because it is a separate bug.

Every Task(on:) initializer of CancellableQueue now tracks its task through one internal method, trackTask(performing:createdBy:), which reserves the identifier, creates the task, and registers its cancel closure, in that order. Tests call it directly to finish a task, or to call cancelTasks(), while the task is being created, which the initializers cannot be made to do on demand. It is marked @inline(__always): without the attribute, enqueuing on a CancellableQueue measured about 11% slower (30 interleaved rounds of 20,000 tasks pinned to one CPU, median 1.113× against the original); with it, the cost is within noise (1.007×, against 0.995× for an A/A run), and heap allocations per task are unchanged.

Tests

All of these drive the queue's own methods in a fixed order, so none depends on timing:

  • cancelTasks_cancelsTaskThatRegistersCancellationAfterward and …AfterRepeatedCancelTasks call cancelTasks() between a task's reservation and its registration. They fail 10 of 10 times on the parent.
  • cancelTasks_doesNotCancelTaskThatFinishedBeforeRegisteringCancellationAfterCancelTasks guards the new state against cancelling a task that has already finished.
  • cancelTasks_canBeCalledFromCancellationHandlerOfTaskThatRegistersCancellationAfterward checks that the cancellation a registration triggers runs after the lock is released, so its handler can call cancelTasks().
  • cancelTasks_doesNotCancelTrackedTaskThatFinishedWhileBeingCreated and cancelTasks_calledWhileTrackedTaskIsBeingCreated_cancelsTask call trackTask with a createTask closure that finishes the task, or calls cancelTasks(), before trackTask registers it. Both fail 10 of 10 times if trackTask reserves only after creating the task, and the second if it never registers the task.

Series

PR 6 of 10. It is stacked on #89.

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. No line in Sources or Tests reads zero in the CI run.
  • The two trackTask tests fail 10 of 10 runs (3 pinned to one CPU) against a trackTask that reserves the identifier only after creating the task, and the second also against one that never registers the task. Both pass 10 of 10 on the real code and pass --repetitions 100 --repeat-until fail unpinned and pinned, and still fail 10 of 10 against the first mutant at every later commit in the series.
  • 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 registered closures and mark the reservations in one withLock, and registerCancellation must read and update the task's state in one. No test can force a thread switch inside one.
  • Darwin. Nothing was run on Apple platforms. CI is the first run there. The @inline(__always) cost was measured on Linux only.

🤖 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 (0958fc0) to head (a47fa99).

Additional details and impacted files

Impacted file tree graph

@@                 Coverage Diff                  @@
##           claude/2.0-4-mutex       #90   +/-   ##
====================================================
  Coverage              100.00%   100.00%           
====================================================
  Files                      12        12           
  Lines                    1476      1540   +64     
====================================================
+ Hits                     1476      1540   +64     
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 force-pushed the claude/2.0-5-cancel-enqueuing-tasks branch from 9fb84c6 to 83b0b2d Compare November 15, 2026 15:45
@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 `CancellableQueue` reserves an identifier for each task, creates the
task on the underlying queue, and only then registers the task's cancel
closure. `cancelTasks()` cancelled only registered tasks. A task that was
reserved but not yet registered when `cancelTasks()` ran was skipped,
and nothing cancelled it later unless `cancelTasks()` was called again.
Such a task can already be executing, for example when its own operation
calls `cancelTasks()`.

`cancelTasks()` now marks such reservations, and registering a marked
task's cancel closure cancels the task immediately, after releasing the
lock.

Every `Task(on:)` initializer of `CancellableQueue` now tracks its task
through one internal method, `trackTask(performing:createdBy:)`, which
reserves the identifier, creates the task, and registers its cancel
closure, in that order. Tests call it directly to finish a task, or to
call `cancelTasks()`, while the task is being created, which the
initializers cannot be made to do on demand. The method is always
inlined, so enqueuing a task costs what it did before.

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-5-cancel-enqueuing-tasks branch from 83b0b2d to a47fa99 Compare November 16, 2026 23:40
@dfed
dfed merged commit 2238977 into main Nov 17, 2026
19 of 20 checks passed
@dfed
dfed deleted the claude/2.0-5-cancel-enqueuing-tasks 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