ractor-forge 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +21 -0
- data/CODE_OF_CONDUCT.md +10 -0
- data/LICENSE.txt +21 -0
- data/README.md +166 -0
- data/Rakefile +12 -0
- data/examples/README.md +26 -0
- data/examples/demo.rb +182 -0
- data/lib/ractor/forge/version.rb +9 -0
- data/lib/ractor/forge.rb +1041 -0
- data/sig/ractor/forge.rbs +42 -0
- metadata +64 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: fa35de42fc1cb03f70f678963ddbce1c4a6b12f1e834c69273292b01dcb0e13a
|
|
4
|
+
data.tar.gz: 4977ff754cf41dc836511191626157c4884e9653138ecf8b0d25f47d7f002eb5
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: ac42dc3ff816e7711847510d9229372c39c75f91dd861ad782c38bde786885702d590b3cf8bbc539aea83fe2f4c17e2980180dbddce8b4941598fce64672bce7
|
|
7
|
+
data.tar.gz: c56f969429c164f1133ad57556bf711740742c4354cc3d71550ad1a323356bb28d79b79b2d53ac9725d377801e60727e911e2bd7fef3abb30637a1a1d1c0ade2
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
## [Unreleased]
|
|
2
|
+
|
|
3
|
+
- Define explicit pool lifecycle states and require `start` before submission.
|
|
4
|
+
- Add `:fail_fast` as the default error policy and preserve `:continue` as an opt-in.
|
|
5
|
+
- Distinguish failed and cancelled futures, and define disjoint terminal metrics.
|
|
6
|
+
- Document the cooperative cancellation contract and Ruby 4.0/4.1 compatibility policy.
|
|
7
|
+
- Add contract tests for lifecycle transitions, failure policies, and metric invariants.
|
|
8
|
+
- Add scaffold files.
|
|
9
|
+
- Expose the configured worker count through `Pool#size` and add `Pool#close` as a `shutdown` alias.
|
|
10
|
+
- Harden pipeline startup and teardown, joining owned workers and waking submitters when shutdown begins.
|
|
11
|
+
- Raise `StartupError` after partial startup cleanup and settle accepted futures on startup failure.
|
|
12
|
+
- Test partial worker startup, source and terminal failures, and concurrent lifecycle calls.
|
|
13
|
+
- Clarify that capacity bounds outstanding task count across the pipeline, while pipeline push links remain individually unbounded and queue depth reports only the Pool input queue.
|
|
14
|
+
- Stress the global capacity bound and blocked submission with a slow single-lane worker.
|
|
15
|
+
- Preserve task identity when result transfer fails, and keep fail-fast queued tasks out of pipeline links so they can be cancelled before execution.
|
|
16
|
+
- Test concurrent task failures, queued cancellation, uncopyable results, and submitters blocked when a failure occurs.
|
|
17
|
+
- Add idempotent `Pool#cancel`, cooperative `TaskContext` checkpoints, cancellation reasons, and cancellation propagation to queued and running tasks.
|
|
18
|
+
- Test cancellation before start, during queued and active work, during fail-fast, and repeated cancellation.
|
|
19
|
+
- Expose Ractor-reported active workers and document throughput and service-time metric definitions.
|
|
20
|
+
- Test immutable metric snapshots across lifecycle and outcome states, including concurrent reads.
|
|
21
|
+
- Pin the `ractor-pipeline` fork revision and add explicit Ractor message-copy compatibility coverage.
|
data/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Code of Conduct
|
|
2
|
+
|
|
3
|
+
"ractor-forge" follows [The Ruby Community Conduct Guideline](https://www.ruby-lang.org/en/conduct) in all "collaborative space", which is defined as community communications channels (such as mailing lists, submitted patches, commit comments, etc.):
|
|
4
|
+
|
|
5
|
+
* Participants will be tolerant of opposing views.
|
|
6
|
+
* Participants must ensure that their language and actions are free of personal attacks and disparaging personal remarks.
|
|
7
|
+
* When interpreting the words and actions of others, participants should always assume good intentions.
|
|
8
|
+
* Behaviour which can be reasonably considered harassment will not be tolerated.
|
|
9
|
+
|
|
10
|
+
If you have any concerns about behaviour within this project, please contact us at ["kenneth.c.demanawa@gmail.com"](mailto:"kenneth.c.demanawa@gmail.com").
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kenneth C. Demanawa
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# Ractor Forge
|
|
2
|
+
|
|
3
|
+
Ractor Forge is an experimental bounded CPU job pool for Ruby. It runs a
|
|
4
|
+
shareable work block in persistent Ractor workers, returns a `Future` for each
|
|
5
|
+
accepted job, and drains accepted work during graceful shutdown. The pipeline
|
|
6
|
+
topology and demand scheduling are provided by
|
|
7
|
+
[`ractor-pipeline`](https://github.com/ko1/ractor-pipeline).
|
|
8
|
+
|
|
9
|
+
Requires Ruby 4.0 or newer. Ruby's Ractor API and this project are experimental.
|
|
10
|
+
CI requires Ruby 4.0.6 and tracks Ruby 4.1 preview as an allowed-to-fail job;
|
|
11
|
+
the suite checks Ractor shareability and task behavior on each CI runtime.
|
|
12
|
+
|
|
13
|
+
See the [generated API reference](https://kanutocd.github.io/ractor-forge/).
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```ruby
|
|
18
|
+
require "ractor/forge"
|
|
19
|
+
|
|
20
|
+
pool = Ractor::Forge::Pool.new(size: 4, capacity: 16, on_error: :fail_fast) do |input|
|
|
21
|
+
expensive_cpu_work(input)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
pool.state #=> :initialized
|
|
25
|
+
pool.start
|
|
26
|
+
futures = (1..10).map { |n| pool.submit(n) }
|
|
27
|
+
results = futures.map(&:value)
|
|
28
|
+
|
|
29
|
+
pool.shutdown
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`capacity` limits the number of accepted tasks whose futures have not settled.
|
|
33
|
+
It counts tasks in the Pool queue, in pipeline links, executing, or awaiting
|
|
34
|
+
result delivery. `submit` blocks when that limit is reached. Pass `timeout:` to
|
|
35
|
+
return `nil` without admitting the task if no slot becomes available:
|
|
36
|
+
|
|
37
|
+
```ruby
|
|
38
|
+
future = pool.submit(input, timeout: 0.1)
|
|
39
|
+
raise "pool is busy" unless future
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Cancellation and fail-fast failure can settle a future while its worker code is
|
|
43
|
+
still unwinding. The pool still waits for the worker pipeline to exit before
|
|
44
|
+
`cancel` returns.
|
|
45
|
+
|
|
46
|
+
`queue_depth` in `metrics` counts only tasks waiting in the Pool's input queue;
|
|
47
|
+
it is distinct from `in_flight`. The current Pool topology has no tee or fan-out,
|
|
48
|
+
and each input produces one result. The underlying `ractor-pipeline` push links,
|
|
49
|
+
including single-lane links, are individually unbounded, so `queue_depth` can be
|
|
50
|
+
lower than `in_flight` while tasks wait in those links. The global capacity
|
|
51
|
+
limit bounds the number of outstanding tasks across this topology, not their
|
|
52
|
+
combined byte size. A single large input or result can still consume substantial
|
|
53
|
+
memory.
|
|
54
|
+
|
|
55
|
+
`Future#value` waits for the result. It accepts an optional timeout in seconds;
|
|
56
|
+
it returns `nil` if the task has not completed by then. A task that raises a
|
|
57
|
+
`StandardError` or a result that cannot be copied across a Ractor boundary
|
|
58
|
+
causes `value` to raise `Ractor::Forge::TaskError`, which provides `task_id`,
|
|
59
|
+
`original_class`, and `original_backtrace`.
|
|
60
|
+
|
|
61
|
+
Pools have explicit states: `:initialized`, `:running`, `:stopping`,
|
|
62
|
+
`:cancelling`, `:cancelled`, `:stopped`, and `:failed`. Construction does not
|
|
63
|
+
start workers. Call `start` before submitting jobs. `shutdown` is idempotent;
|
|
64
|
+
it stops admission and drains accepted work. Calling `shutdown` before `start`
|
|
65
|
+
moves directly to `:stopped`.
|
|
66
|
+
Submitting before `start` raises `StateError`; submitting after shutdown starts
|
|
67
|
+
raises `ClosedError`. `close` is an alias for `shutdown`, and `pool.size` returns
|
|
68
|
+
the configured worker count.
|
|
69
|
+
`start` waits until the worker pipeline and feeder are established. If worker
|
|
70
|
+
startup fails, it joins the dispatcher, settles accepted futures, and raises
|
|
71
|
+
`StartupError` with the startup exception as its cause.
|
|
72
|
+
|
|
73
|
+
The default `on_error: :fail_fast` fails the pool on the first job error. The
|
|
74
|
+
failing future raises `TaskError`; accepted tasks that have not started are
|
|
75
|
+
cancelled, other outstanding futures raise `CancelledError`, and running work
|
|
76
|
+
is signalled to stop cooperatively. Select
|
|
77
|
+
`on_error: :continue`
|
|
78
|
+
to isolate a task error to that future and continue processing later jobs:
|
|
79
|
+
|
|
80
|
+
```ruby
|
|
81
|
+
pool = Ractor::Forge::Pool.new(size: 4, on_error: :continue) do |input|
|
|
82
|
+
parse_and_transform(input)
|
|
83
|
+
end
|
|
84
|
+
pool.start
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The work block must be Ractor-shareable. Inputs and successful results are sent
|
|
88
|
+
across Ractor boundaries using Ruby's normal copying rules, so results must be
|
|
89
|
+
sendable. The block should perform CPU work and avoid relying on mutable state
|
|
90
|
+
outside its Ractor.
|
|
91
|
+
|
|
92
|
+
`shutdown` stops accepting submissions, finishes all accepted tasks, and waits
|
|
93
|
+
for the worker pipeline to exit. It is safe to call repeatedly. `metrics`
|
|
94
|
+
returns a frozen snapshot with `submitted`, `completed`, `failed`, `cancelled`,
|
|
95
|
+
`in_flight`, `active_workers`, and `queue_depth`, plus throughput and average
|
|
96
|
+
service time. `workers` is the configured pool size; `active_workers` counts
|
|
97
|
+
workers reported as executing user work; the gauge is updated through worker
|
|
98
|
+
lifecycle messages and can briefly lag a transition. `queue_depth` counts
|
|
99
|
+
tasks in the Pool input queue. `in_flight` counts accepted tasks whose futures
|
|
100
|
+
do not yet have a terminal outcome.
|
|
101
|
+
`completed` counts successful tasks; `failed` and `cancelled` count futures
|
|
102
|
+
settled with those outcomes. Throughput is completed tasks divided by elapsed
|
|
103
|
+
monotonic time since `start`. Average service time is the arithmetic mean of
|
|
104
|
+
worker-reported service durations for completed and failed tasks, in seconds;
|
|
105
|
+
cancellations are excluded. Before start, both rate and average are zero. At
|
|
106
|
+
each snapshot:
|
|
107
|
+
|
|
108
|
+
```text
|
|
109
|
+
submitted = completed + failed + cancelled + in_flight
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Explore the runnable [examples](examples/README.md) for complete usage scenarios.
|
|
113
|
+
|
|
114
|
+
## Cancellation
|
|
115
|
+
|
|
116
|
+
`shutdown` is a graceful drain. `cancel(reason:)` stops admission, settles all
|
|
117
|
+
outstanding futures as cancelled, and signals running work to stop at a safe
|
|
118
|
+
point. It is idempotent and waits for the pipeline to exit, even if futures
|
|
119
|
+
have already settled. Cancelling a pool before `start` moves it directly to
|
|
120
|
+
`:cancelled`.
|
|
121
|
+
|
|
122
|
+
Existing one-argument work blocks keep working. To cooperate with cancellation,
|
|
123
|
+
declare a second positional argument for the task context:
|
|
124
|
+
|
|
125
|
+
```ruby
|
|
126
|
+
pool = Ractor::Forge::Pool.new(size: 4) do |input, context|
|
|
127
|
+
input.each_slice(1_000) do |batch|
|
|
128
|
+
context.checkpoint!
|
|
129
|
+
process_batch(batch)
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
pool.start
|
|
134
|
+
future = pool.submit(input)
|
|
135
|
+
pool.cancel(reason: "request no longer needed")
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`TaskContext#cancelled?` polls the request, `#reason` returns its string reason
|
|
139
|
+
after cancellation, and `#checkpoint!` raises `CancellationError` with that
|
|
140
|
+
reason. A context-aware job can also rescue the exception for local cleanup;
|
|
141
|
+
the future is already settled as cancelled, while `cancel` waits for the job to
|
|
142
|
+
return. `Future#value` raises `CancelledError`, which exposes `#reason`.
|
|
143
|
+
|
|
144
|
+
Cancellation is cooperative for running work. A job that does not check its
|
|
145
|
+
context continues until it returns, so `cancel` and `shutdown` can wait
|
|
146
|
+
indefinitely for uncooperative work. Ruby cannot forcibly interrupt arbitrary
|
|
147
|
+
code running in a Ractor. Fail-fast uses the same signal to notify active
|
|
148
|
+
contexts after a task error.
|
|
149
|
+
|
|
150
|
+
## Current scope
|
|
151
|
+
|
|
152
|
+
The first version handles independent jobs in one process. It does not restart
|
|
153
|
+
failed workers, retry jobs, or support priorities, keyed routing, or distributed
|
|
154
|
+
execution. The `:continue` error policy is opt-in; retries are not automatic.
|
|
155
|
+
If the pipeline itself fails outside an in-progress cancellation, outstanding
|
|
156
|
+
futures fail and the pool enters `:failed` state.
|
|
157
|
+
|
|
158
|
+
## Development setup
|
|
159
|
+
|
|
160
|
+
The Gemfile uses the `kanutocd/ractor-pipeline` GitHub fork for development;
|
|
161
|
+
the gemspec records `ractor-pipeline` as a runtime dependency. Run `bin/setup`,
|
|
162
|
+
then `bundle exec rake`.
|
|
163
|
+
|
|
164
|
+
## License
|
|
165
|
+
|
|
166
|
+
MIT. See [LICENSE.txt](LICENSE.txt).
|
data/Rakefile
ADDED
data/examples/README.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Ractor Forge examples
|
|
2
|
+
|
|
3
|
+
These runnable examples demonstrate the public pool API and its behavior.
|
|
4
|
+
They are small feature demonstrations, not benchmarks.
|
|
5
|
+
|
|
6
|
+
The feature-tour format is inspired by the [Ractor::Pipeline examples](https://github.com/ko1/ractor-pipeline/tree/master/examples).
|
|
7
|
+
|
|
8
|
+
From the repository root, install the development dependencies and run:
|
|
9
|
+
|
|
10
|
+
~~~sh
|
|
11
|
+
bundle install
|
|
12
|
+
bundle exec ruby -Ilib examples/demo.rb
|
|
13
|
+
~~~
|
|
14
|
+
|
|
15
|
+
## Available examples
|
|
16
|
+
|
|
17
|
+
| File | Demonstrates |
|
|
18
|
+
|---|---|
|
|
19
|
+
| [demo.rb](demo.rb) | Futures, capacity limits, timeouts, fail-fast and continue policies, cooperative cancellation, Ractor message copying, CPU work, metrics, and shutdown |
|
|
20
|
+
|
|
21
|
+
The CPU comparison in demo.rb checks that serial and pooled results match.
|
|
22
|
+
Its timing is illustrative and depends on the Ruby version, CPU, and system
|
|
23
|
+
load; use a dedicated benchmark for performance decisions.
|
|
24
|
+
|
|
25
|
+
Add future runnable examples to this index with a short description of the
|
|
26
|
+
behavior they demonstrate.
|
data/examples/demo.rb
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Feature tour of Ractor Forge.
|
|
4
|
+
#
|
|
5
|
+
# Run from the repository root with:
|
|
6
|
+
#
|
|
7
|
+
# bundle exec ruby -Ilib examples/demo.rb
|
|
8
|
+
|
|
9
|
+
Warning[:experimental] = false # suppress the Ractor API experimental warning
|
|
10
|
+
|
|
11
|
+
require "ractor/forge"
|
|
12
|
+
|
|
13
|
+
Pool = Ractor::Forge::Pool
|
|
14
|
+
|
|
15
|
+
# Print one named feature section at a time.
|
|
16
|
+
def section(title)
|
|
17
|
+
puts
|
|
18
|
+
puts "== #{title}"
|
|
19
|
+
yield
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
section "basic: submit jobs and collect their futures" do
|
|
23
|
+
pool = Pool.new(size: 2, capacity: 4) { |number| number * number }
|
|
24
|
+
pool.start
|
|
25
|
+
|
|
26
|
+
futures = (1..4).map { |number| pool.submit(number) }
|
|
27
|
+
puts "results: #{futures.map(&:value).inspect}"
|
|
28
|
+
|
|
29
|
+
pool.shutdown
|
|
30
|
+
puts "state after shutdown: #{pool.state}"
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
section "capacity: timed submission when all slots are occupied" do
|
|
34
|
+
pool = Pool.new(size: 1, capacity: 1) do |number|
|
|
35
|
+
sleep 0.1
|
|
36
|
+
number * 10
|
|
37
|
+
end
|
|
38
|
+
pool.start
|
|
39
|
+
|
|
40
|
+
first = pool.submit(1)
|
|
41
|
+
second = pool.submit(2, timeout: 0.01)
|
|
42
|
+
puts "second job admitted: #{!second.nil?}"
|
|
43
|
+
puts "first result: #{first.value}"
|
|
44
|
+
|
|
45
|
+
pool.shutdown
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
section "future timeout: stop waiting without cancelling the job" do
|
|
49
|
+
pool = Pool.new(size: 1) do |number|
|
|
50
|
+
sleep 0.1
|
|
51
|
+
number * 10
|
|
52
|
+
end
|
|
53
|
+
pool.start
|
|
54
|
+
|
|
55
|
+
future = pool.submit(7)
|
|
56
|
+
puts "result before deadline: #{future.value(timeout: 0.01).inspect}"
|
|
57
|
+
puts "eventual result: #{future.value}"
|
|
58
|
+
|
|
59
|
+
pool.shutdown
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
section "fail-fast: one job error cancels other outstanding futures" do
|
|
63
|
+
pool = Pool.new(size: 1, capacity: 3) do |input|
|
|
64
|
+
sleep 0.05
|
|
65
|
+
raise ArgumentError, "invalid input" if input == :bad
|
|
66
|
+
|
|
67
|
+
input
|
|
68
|
+
end
|
|
69
|
+
pool.start
|
|
70
|
+
futures = [:bad, :not_started, :also_not_started].map { |input| pool.submit(input) }
|
|
71
|
+
|
|
72
|
+
outcomes = futures.map do |future|
|
|
73
|
+
future.value
|
|
74
|
+
rescue Ractor::Forge::TaskError => e
|
|
75
|
+
[:failed, e.task_id, e.original_class]
|
|
76
|
+
rescue Ractor::Forge::CancelledError => e
|
|
77
|
+
[:cancelled, e.reason]
|
|
78
|
+
end
|
|
79
|
+
puts "outcomes: #{outcomes.inspect}"
|
|
80
|
+
|
|
81
|
+
pool.shutdown
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
section "continue policy: report one task error and keep processing" do
|
|
85
|
+
pool = Pool.new(size: 2, capacity: 3, on_error: :continue) do |input|
|
|
86
|
+
raise ArgumentError, "invalid input" if input == :bad
|
|
87
|
+
|
|
88
|
+
input.to_s.upcase
|
|
89
|
+
end
|
|
90
|
+
pool.start
|
|
91
|
+
|
|
92
|
+
good = pool.submit(:hello)
|
|
93
|
+
bad = pool.submit(:bad)
|
|
94
|
+
after_error = pool.submit(:world)
|
|
95
|
+
|
|
96
|
+
puts "first result: #{good.value}"
|
|
97
|
+
begin
|
|
98
|
+
bad.value
|
|
99
|
+
rescue Ractor::Forge::TaskError => e
|
|
100
|
+
puts "task #{e.task_id}: #{e.message} (original class: #{e.original_class})"
|
|
101
|
+
end
|
|
102
|
+
puts "later result: #{after_error.value}"
|
|
103
|
+
|
|
104
|
+
pool.shutdown
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
section "cancellation: cooperate at safe points" do
|
|
108
|
+
pool = Pool.new(size: 1) do |limit, context|
|
|
109
|
+
total = 0
|
|
110
|
+
limit.times do |number|
|
|
111
|
+
context.checkpoint!
|
|
112
|
+
total += number
|
|
113
|
+
sleep 0.01
|
|
114
|
+
end
|
|
115
|
+
total
|
|
116
|
+
end
|
|
117
|
+
pool.start
|
|
118
|
+
future = pool.submit(1_000)
|
|
119
|
+
|
|
120
|
+
sleep 0.05
|
|
121
|
+
pool.cancel(reason: "demo stopped")
|
|
122
|
+
begin
|
|
123
|
+
future.value
|
|
124
|
+
rescue Ractor::Forge::CancelledError => e
|
|
125
|
+
puts "future cancelled: #{e.reason}"
|
|
126
|
+
end
|
|
127
|
+
puts "state after cancellation: #{pool.state}"
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
section "Ractor boundary: mutable inputs are copied to workers" do
|
|
131
|
+
pool = Pool.new(size: 1) { |input| input << " processed" }
|
|
132
|
+
pool.start
|
|
133
|
+
|
|
134
|
+
input = String.new("job")
|
|
135
|
+
result = pool.submit(input).value
|
|
136
|
+
puts "worker result: #{result.inspect}"
|
|
137
|
+
puts "caller input: #{input.inspect}"
|
|
138
|
+
|
|
139
|
+
pool.shutdown
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
section "CPU work: compare serial and pooled execution" do
|
|
143
|
+
jobs = [2_000_000] * 4
|
|
144
|
+
work = Ractor.shareable_proc do |iterations|
|
|
145
|
+
checksum = 0
|
|
146
|
+
iterations.times do |number|
|
|
147
|
+
checksum = (checksum + number * number) % 1_000_003
|
|
148
|
+
end
|
|
149
|
+
checksum
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
153
|
+
serial_results = jobs.map { |iterations| work.call(iterations) }
|
|
154
|
+
serial_seconds = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at
|
|
155
|
+
|
|
156
|
+
pool = Pool.new(size: jobs.size, capacity: jobs.size, &work)
|
|
157
|
+
pool.start
|
|
158
|
+
started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
159
|
+
parallel_results = jobs.map { |iterations| pool.submit(iterations) }.map(&:value)
|
|
160
|
+
parallel_seconds = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at
|
|
161
|
+
pool.shutdown
|
|
162
|
+
|
|
163
|
+
raise "serial and pooled results differ" unless parallel_results == serial_results
|
|
164
|
+
|
|
165
|
+
printf "serial: %.3fs; pool: %.3fs; observed speedup: %.2fx\n",
|
|
166
|
+
serial_seconds, parallel_seconds, serial_seconds / parallel_seconds
|
|
167
|
+
puts "Illustrative only: timings depend on Ruby, CPU, and system load."
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
section "metrics: inspect outcomes and shut down gracefully" do
|
|
171
|
+
pool = Pool.new(size: 2, capacity: 4, on_error: :continue) { |n| n + 1 }
|
|
172
|
+
pool.start
|
|
173
|
+
futures = [10, 20, 30].map { |n| pool.submit(n) }
|
|
174
|
+
futures.each(&:value)
|
|
175
|
+
pool.close # close is an alias for shutdown
|
|
176
|
+
|
|
177
|
+
puts "state: #{pool.state}"
|
|
178
|
+
puts "metrics: #{pool.metrics}"
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
puts
|
|
182
|
+
puts "done."
|