Skip to content

Commit f7d3446

Browse files
authored
Propagate cancellation causes through task trees. (#461)
1 parent 677a3a1 commit f7d3446

13 files changed

Lines changed: 411 additions & 22 deletions

File tree

‎benchmark/cancel_cause.rb‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#!/usr/bin/env ruby
2+
# frozen_string_literal: true
3+
4+
# Released under the MIT License.
5+
# Copyright, 2026, by Shopify Inc.
6+
# Copyright, 2026, by Samuel Williams.
7+
8+
require "async"
9+
10+
module CountCancelCauses
11+
attr_accessor :for_calls
12+
13+
def for(*arguments, **options, &block)
14+
self.for_calls ||= 0
15+
self.for_calls += 1
16+
17+
super(*arguments, **options, &block)
18+
end
19+
end
20+
21+
Async::Cancel::Cause.singleton_class.prepend(CountCancelCauses)
22+
23+
def positive_integer(name, default)
24+
Integer(ENV.fetch(name, default)).tap do |value|
25+
abort("#{name} must be positive!") unless value.positive?
26+
end
27+
end
28+
29+
def measure_cancel(total_tasks)
30+
scheduler = Async::Scheduler.new
31+
ready = Thread::Queue.new
32+
33+
Fiber.set_scheduler(scheduler)
34+
35+
begin
36+
total_tasks.times do
37+
scheduler.async do
38+
ready.push(true)
39+
sleep
40+
end
41+
end
42+
43+
total_tasks.times do
44+
ready.pop
45+
end
46+
47+
GC.start
48+
Async::Cancel::Cause.for_calls = 0
49+
50+
# Measure the synchronous fan-out only; draining cancelled tasks happens in `ensure`.
51+
allocated_before = GC.stat(:total_allocated_objects)
52+
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
53+
54+
scheduler.cancel
55+
56+
duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time
57+
allocated_after = GC.stat(:total_allocated_objects)
58+
59+
return {
60+
tasks: total_tasks,
61+
cause_for_calls: Async::Cancel::Cause.for_calls,
62+
allocated_objects: allocated_after - allocated_before,
63+
duration_ms: duration * 1000.0
64+
}
65+
ensure
66+
scheduler.run unless scheduler.closed?
67+
Fiber.set_scheduler(nil)
68+
end
69+
end
70+
71+
tasks = positive_integer("TASKS", 1365)
72+
73+
result = measure_cancel(tasks)
74+
75+
puts "tasks=#{result.fetch(:tasks)}"
76+
puts "cause_for_calls=#{result.fetch(:cause_for_calls)}"
77+
puts "allocated_objects=#{result.fetch(:allocated_objects)}"
78+
puts "duration_ms=#{format('%.2f', result.fetch(:duration_ms))}"

‎lib/async/node.rb‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -283,9 +283,10 @@ def terminate
283283
# Attempt to cancel the current node immediately, including all non-transient children. Invokes {#stop_children} to cancel all children.
284284
#
285285
# @parameter later [Boolean] Whether to defer cancelling until some point in the future.
286-
def cancel(later = false)
286+
# @parameter cause [Exception | Nil] The cause of the cancel operation.
287+
def cancel(later = false, cause: $!)
287288
# The implementation of this method may defer calling `stop_children`.
288-
stop_children(later)
289+
stop_children(later, cause: cause)
289290
end
290291

291292
# Backward compatibility alias for {#cancel}.
@@ -295,9 +296,9 @@ def stop(...)
295296
end
296297

297298
# Attempt to stop all non-transient children.
298-
private def stop_children(later = false)
299+
private def stop_children(later = false, cause:)
299300
@children&.each do |child|
300-
child.cancel(later) unless child.transient?
301+
child.cancel(later, cause: cause) unless child.transient?
301302
end
302303
end
303304

‎lib/async/promise.rb‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,9 @@ def value
9898
end
9999

100100
# Wait with deadline tracking:
101-
until @resolved
101+
loop do
102+
break if @resolved
103+
102104
# Get remaining time for this wait iteration:
103105
remaining = deadline.remaining
104106

‎lib/async/scheduler.rb‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -514,15 +514,19 @@ def run_once(timeout = nil)
514514
# Cancel all children, including transient children.
515515
#
516516
# @public Since *Async v1*.
517-
def cancel
517+
def cancel(later = false, cause: $!)
518+
if @children and !cause
519+
cause = Cancel::Cause.for("Cancelling task!")
520+
end
521+
518522
@children&.each do |child|
519-
child.cancel
523+
child.cancel(later, cause: cause)
520524
end
521525
end
522526

523527
# Backward compatibility alias for cancel.
524-
def stop
525-
cancel
528+
def stop(...)
529+
cancel(...)
526530
end
527531

528532
# Run the event loop, until the scheduler is interrupted or finished.

‎lib/async/task.rb‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ def cancel(later = false, cause: $!)
333333

334334
if self.cancelled?
335335
# If the task is already cancelled, a `cancel` state transition re-enters the same state which is a no-op. However, we will also attempt to cancel any running children too. This can happen if the children did not cancel correctly the first time around. Doing this should probably be considered a bug, but it's better to be safe than sorry.
336-
return cancelled!
336+
return cancelled!(cause)
337337
end
338338

339339
# If the fiber is alive, we need to cancel it:
@@ -369,7 +369,7 @@ def cancel(later = false, cause: $!)
369369
end
370370
else
371371
# We are not running, but children might be, so transition directly into cancelled state:
372-
cancel!
372+
cancel!(cause)
373373
end
374374
end
375375

@@ -479,7 +479,7 @@ def failed!(exception = false)
479479
@promise.reject(exception)
480480
end
481481

482-
def cancelled!
482+
def cancelled!(cause = $!)
483483
# Console.info(self, status:) {"Task #{self} was cancelled with #{@children&.size.inspect} children!"}
484484

485485
# Cancel the promise, specify nil here so that no exception is raised when waiting on the promise:
@@ -489,24 +489,25 @@ def cancelled!
489489

490490
begin
491491
# We are not running, but children might be so we should stop them:
492-
stop_children(true)
493-
rescue Cancel
492+
stop_children(true, cause: cause)
493+
rescue Cancel => exception
494494
cancelled = true
495+
cause ||= exception.cause || exception
495496
# If we are cancelling children, and one of them tries to cancel the current task, we should ignore it. We will be cancelled later.
496497
retry
497498
end
498499

499500
if cancelled
500-
raise Cancel, "Cancelling current task!"
501+
raise Cancel, "Cancelling current task!", cause: cause
501502
end
502503
end
503504

504505
def stopped!
505506
cancelled!
506507
end
507508

508-
def cancel!
509-
cancelled!
509+
def cancel!(cause = $!)
510+
cancelled!(cause)
510511

511512
finish!
512513
end
@@ -519,8 +520,8 @@ def schedule(&block)
519520
@fiber = Fiber.new(annotation: self.annotation) do
520521
begin
521522
completed!(yield)
522-
rescue Cancel
523-
cancelled!
523+
rescue Cancel => exception
524+
cancelled!(exception.cause || exception)
524525
rescue StandardError => error
525526
failed!(error)
526527
rescue Exception => exception

‎releases.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Releases
22

3+
## Unreleased
4+
5+
- Propagate cancellation causes through task trees so child tasks observe the original cancellation cause.
6+
37
## v2.42.0
48

59
- `Sync` and `Async` can now be invoked from a non-blocking fiber that has no scheduler (e.g. inside an `Enumerator` or a bare `Fiber.new`). Previously this raised `RuntimeError: Running scheduler on non-blocking fiber!`. The reactor is now run within `Fiber.blocking`, so the scheduler always runs on a blocking fiber.

‎test/async/limited_queue.rb‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,39 @@
44
# Copyright, 2025, by Samuel Williams.
55
# Copyright, 2025, by Shopify Inc.
66

7-
require "async/limited_queue"
7+
require "async/queue"
88

99
require "sus/fixtures/async"
1010
require "async/a_queue"
1111

12+
limited_queue_new = Async::LimitedQueue.method(:new)
13+
14+
require "async/limited_queue"
15+
1216
describe Async::LimitedQueue do
1317
include Sus::Fixtures::Async::ReactorContext
1418

1519
it_behaves_like Async::AQueue
1620

21+
it "warns when constructed through async/queue" do
22+
verbose = $VERBOSE
23+
$VERBOSE = true
24+
25+
warning = nil
26+
Async::LimitedQueue.define_singleton_method(:warn) do |*arguments, **options|
27+
warning = arguments.first
28+
end
29+
30+
queue = limited_queue_new.call(1)
31+
32+
expect(queue.limit).to be == 1
33+
expect(warning).to be =~ /require 'async\/limited_queue'/
34+
ensure
35+
singleton_class = class << Async::LimitedQueue; self; end
36+
singleton_class.remove_method(:warn) if singleton_class.instance_methods(false).include?(:warn)
37+
$VERBOSE = verbose
38+
end
39+
1740
let(:queue) {subject.new}
1841

1942
with "#limit" do
@@ -108,4 +131,3 @@ def before
108131
end
109132
end
110133
end
111-

‎test/async/list.rb‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@ def initialize(value)
6767
expect(list.each.map(&:value)).to be(:empty?)
6868
end
6969

70+
it "returns nil when removing an item that is not in the list" do
71+
item = Item.new(1)
72+
73+
expect(list.remove?(item)).to be_nil
74+
end
75+
7076
it "can't remove an item twice" do
7177
item = Item.new(1)
7278

‎test/async/node.rb‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,17 @@
288288

289289
node.cancel
290290
end
291+
292+
it "forwards the cause to child tasks" do
293+
cause = RuntimeError.new("boom")
294+
295+
middle = Async::Node.new(node, annotation: "middle")
296+
child = Async::Node.new(middle, annotation: "child")
297+
298+
expect(child).to receive(:cancel).with(false, cause: cause)
299+
300+
middle.cancel(cause: cause)
301+
end
291302
end
292303

293304
with "#terminate" do

‎test/async/promise.rb‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,17 @@
5252
end
5353
end
5454

55+
with "#wait" do
56+
it "waits until a pending promise resolves before timeout" do
57+
reactor.async do
58+
sleep(0.001)
59+
promise.resolve(:done)
60+
end
61+
62+
expect(promise.wait(timeout: 1)).to be == :done
63+
end
64+
end
65+
5566
with "#reject" do
5667
it "can be rejected with an exception" do
5768
error = StandardError.new("test error")

0 commit comments

Comments
 (0)