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.
@@ -0,0 +1,1041 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ractor/pipeline"
4
+ require_relative "forge/version"
5
+
6
+ class Ractor
7
+ # A bounded, experimental CPU job pool built on persistent Ractor workers.
8
+ #
9
+ # Jobs execute in isolated Ractors. The work block must be shareable, and
10
+ # inputs and results cross Ractor boundaries using Ruby's message-copying
11
+ # rules. A pool applies backpressure with a global limit on accepted jobs
12
+ # whose futures have not reached a terminal outcome.
13
+ #
14
+ # The supported entry point is {Ractor::Forge::Pool}. Pools are configured
15
+ # at construction and started explicitly:
16
+ #
17
+ # pool = Ractor::Forge::Pool.new(size: 4, capacity: 16) do |input|
18
+ # expensive_cpu_work(input)
19
+ # end
20
+ # pool.start
21
+ # results = inputs.map { |input| pool.submit(input).value }
22
+ # pool.shutdown
23
+ #
24
+ # Cancellation is cooperative for work that has started. See
25
+ # {Ractor::Forge::TaskContext}. Ruby's Ractor API and this library are
26
+ # experimental.
27
+ module Forge
28
+ # Base class for errors exposed by Ractor Forge.
29
+ class Error < StandardError; end
30
+
31
+ # Raised when work is submitted after the pool has stopped accepting jobs.
32
+ class ClosedError < Error; end
33
+
34
+ # Raised when a pool operation is invalid for its current lifecycle state.
35
+ class StateError < Error; end
36
+
37
+ # Raised when worker-pipeline startup fails. The original startup exception
38
+ # is available through Ruby's standard {Exception#cause} method.
39
+ class StartupError < Error; end
40
+
41
+ # Raised by {Future#value} when that future is cancelled.
42
+ #
43
+ # @attr_reader [String] reason cancellation reason associated with the pool
44
+ # or task
45
+ class CancelledError < Error
46
+ attr_reader :reason
47
+
48
+ # @param reason [String] human-readable cancellation reason
49
+ def initialize(reason)
50
+ @reason = reason
51
+ super("pool cancelled: #{reason}")
52
+ end
53
+ end
54
+
55
+ # Raised by {TaskContext#checkpoint!} when cooperative cancellation is
56
+ # requested.
57
+ #
58
+ # @attr_reader [String] reason reason supplied to {Pool#cancel}
59
+ class CancellationError < Error
60
+ attr_reader :reason
61
+
62
+ # @param reason [String] cancellation reason
63
+ def initialize(reason)
64
+ @reason = reason
65
+ super("task cancelled: #{reason}")
66
+ end
67
+ end
68
+
69
+ # Cooperative cancellation interface passed to context-aware work blocks.
70
+ #
71
+ # A work block receives a context when it declares a second positional
72
+ # parameter or a rest parameter. Check it at safe points; Ractor Forge does
73
+ # not forcibly interrupt arbitrary Ruby code.
74
+ #
75
+ # pool = Ractor::Forge::Pool.new(size: 2) do |input, context|
76
+ # input.each_slice(1_000) do |batch|
77
+ # context.checkpoint!
78
+ # process_batch(batch)
79
+ # end
80
+ # end
81
+ #
82
+ # Instances are created by the worker runtime and supplied to the block;
83
+ # applications should not construct them directly.
84
+ class TaskContext
85
+ # @private
86
+ def initialize(signal_port, reason_port)
87
+ @signal_port = signal_port
88
+ @reason_port = reason_port
89
+ end
90
+
91
+ # Whether cancellation has been requested for this job.
92
+ #
93
+ # This is a non-blocking poll. Use {#checkpoint!} when work should stop
94
+ # by raising immediately at a safe point.
95
+ #
96
+ # @return [Boolean] `true` after cancellation is signalled
97
+ def cancelled? = @signal_port.closed?
98
+
99
+ # The reason for cancellation, or `nil` while the job is not cancelled.
100
+ #
101
+ # @return [String, nil] cancellation reason, if present
102
+ def reason
103
+ return unless cancelled?
104
+ return @reason if defined?(@reason)
105
+
106
+ @reason = @reason_port.receive
107
+ rescue Ractor::ClosedError
108
+ @reason = "pool cancelled"
109
+ end
110
+
111
+ # Raises {CancellationError} if cancellation has been requested.
112
+ #
113
+ # Place checkpoints between units of work where the application can
114
+ # safely stop and release its own resources.
115
+ #
116
+ # @return [nil] when cancellation has not been requested
117
+ # @raise [CancellationError] when the pool has requested cancellation
118
+ def checkpoint!
119
+ raise CancellationError, reason if cancelled?
120
+ end
121
+ end
122
+
123
+ # Error raised by a future when its job fails.
124
+ #
125
+ # The worker's exception is represented by its class name, message, and
126
+ # backtrace. The original exception object itself does not cross the Ractor
127
+ # boundary.
128
+ #
129
+ # @attr_reader [Integer] task_id identifier assigned to the submitted job
130
+ # @attr_reader [String] original_class original exception class name
131
+ # @attr_reader [Array<String>, nil] original_backtrace worker backtrace
132
+ class TaskError < Error
133
+ attr_reader :task_id, :original_class, :original_backtrace
134
+
135
+ # Constructed by the pool when a job fails.
136
+ # @private
137
+ def initialize(task_id, original_class, message, backtrace)
138
+ @task_id = task_id
139
+ @original_class = original_class
140
+ @original_backtrace = backtrace
141
+ super("task #{task_id} failed with #{original_class}: #{message}")
142
+ end
143
+ end
144
+
145
+ # Carries task failure details into fail-fast settlement on the dispatcher.
146
+ # @private
147
+ class TaskFailure < StandardError
148
+ attr_reader :task_id, :original_class, :original_message, :original_backtrace, :service_time
149
+
150
+ def initialize(task_id, original_class, original_message, original_backtrace, service_time)
151
+ @task_id = task_id
152
+ @original_class = original_class
153
+ @original_message = original_message
154
+ @original_backtrace = original_backtrace
155
+ @service_time = service_time
156
+ super("task #{task_id} failed with #{original_class}: #{original_message}")
157
+ end
158
+ end
159
+ private_constant :TaskFailure
160
+
161
+ # Internal counter definitions and immutable snapshot builder.
162
+ # @private
163
+ class Metrics
164
+ def initialize(workers)
165
+ @workers = workers
166
+ @submitted = @completed = @failed = @cancelled = 0
167
+ @service_time = 0.0
168
+ @started_at = nil
169
+ end
170
+
171
+ def start
172
+ @started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
173
+ end
174
+
175
+ def submitted
176
+ @submitted += 1
177
+ end
178
+
179
+ def finish(status, service_time)
180
+ case status
181
+ when :completed
182
+ @completed += 1
183
+ @service_time += service_time
184
+ when :failed
185
+ @failed += 1
186
+ @service_time += service_time
187
+ when :cancelled then @cancelled += 1
188
+ end
189
+ end
190
+
191
+ def snapshot(state:, queue_depth:, in_flight:, active_workers:)
192
+ elapsed = @started_at ? Process.clock_gettime(Process::CLOCK_MONOTONIC) - @started_at : 0.0
193
+ {
194
+ state:,
195
+ workers: @workers,
196
+ active_workers:,
197
+ queue_depth:,
198
+ submitted: @submitted,
199
+ completed: @completed,
200
+ failed: @failed,
201
+ cancelled: @cancelled,
202
+ in_flight:,
203
+ throughput_per_second: elapsed.positive? ? @completed / elapsed : 0.0,
204
+ average_service_time: (@completed + @failed).positive? ? @service_time / (@completed + @failed) : 0.0
205
+ }.freeze
206
+ end
207
+ end
208
+
209
+ # Converts one worker invocation into a compact pipeline outcome.
210
+ # @private
211
+ class Worker
212
+ Config = Data.define(:work, :context_port, :accepts_context)
213
+
214
+ def self.build_proc(work, context_monitor, accepts_context)
215
+ config = Config.new(work:, context_port: context_monitor.port, accepts_context:)
216
+ Ractor.shareable_proc do |job|
217
+ Ractor::Forge::Worker.call(config, job)
218
+ end
219
+ end
220
+
221
+ def self.call(config, job)
222
+ task_id = job.first
223
+ cancellation_port = job.last
224
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
225
+ return cancelled(task_id, started) if cancellation_port.closed?
226
+
227
+ worker_control = request_start(config.context_port, task_id, cancellation_port)
228
+ directive = worker_control.receive
229
+ return cancelled(task_id, started, directive) unless directive == :run
230
+
231
+ execute(config, job, worker_control, started)
232
+ ensure
233
+ notify_finished(config.context_port, task_id) if worker_control
234
+ end
235
+
236
+ def self.request_start(context_port, task_id, cancellation_port)
237
+ worker_control = Ractor::Port.new
238
+ context_port << [:starting, task_id, worker_control, cancellation_port]
239
+ worker_control
240
+ end
241
+
242
+ def self.execute(config, job, worker_control, started)
243
+ task_id, input, result_port, cancellation_port = job
244
+ context = TaskContext.new(cancellation_port, worker_control) if config.accepts_context
245
+ return cancelled(task_id, started) if cancellation_port.closed?
246
+
247
+ report_running(config.context_port, task_id)
248
+ result = run_work(config, input, context)
249
+ return cancelled(task_id, started) if cancellation_port.closed?
250
+
251
+ result_port << result
252
+ [:ok, task_id, nil, nil, nil, elapsed(started)]
253
+ rescue CancellationError => e
254
+ [:cancelled, task_id, e.reason, nil, nil, elapsed(started)]
255
+ rescue StandardError => e
256
+ return cancelled(task_id, started) if cancellation_port.closed?
257
+
258
+ failure(task_id, e, elapsed(started))
259
+ end
260
+
261
+ def self.report_running(context_port, task_id)
262
+ context_port << [:running, task_id]
263
+ end
264
+
265
+ def self.run_work(config, input, context)
266
+ # Deliver each value on its task-owned port so transfer errors retain
267
+ # the task ID instead of surfacing later as an unattributed pipeline error.
268
+ config.accepts_context ? config.work.call(input, context) : config.work.call(input)
269
+ end
270
+
271
+ def self.notify_finished(context_port, task_id)
272
+ context_port << [:finished, task_id]
273
+ rescue Ractor::ClosedError
274
+ nil
275
+ end
276
+
277
+ def self.cancelled(task_id, started, reason = nil)
278
+ [:cancelled, task_id, reason, nil, nil, elapsed(started)]
279
+ end
280
+
281
+ def self.elapsed(started)
282
+ Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
283
+ end
284
+
285
+ def self.failure(task_id, error, duration)
286
+ original_class = error.class.name || error.class.to_s
287
+ [:error, task_id, original_class, error.message, error.backtrace, duration]
288
+ end
289
+ end
290
+
291
+ # Coordinates worker start permits, active contexts, and cancellation.
292
+ # @private
293
+ class ContextMonitor
294
+ attr_reader :port
295
+
296
+ def initialize
297
+ @port = Ractor::Port.new
298
+ @mutex = Mutex.new
299
+ @contexts = {}
300
+ @running = {}
301
+ @reason = nil
302
+ @thread = nil
303
+ end
304
+
305
+ def active_workers
306
+ @mutex.synchronize { @running.size }
307
+ end
308
+
309
+ def start
310
+ @thread = Thread.new { receive_messages }
311
+ end
312
+
313
+ def cancel(reason)
314
+ active, cancellation_reason = @mutex.synchronize do
315
+ @reason ||= reason
316
+ [@contexts.values.dup, @reason]
317
+ end
318
+ signal(active, cancellation_reason)
319
+ end
320
+
321
+ def stop
322
+ unless @thread
323
+ @port.close unless @port.closed?
324
+ return
325
+ end
326
+
327
+ @port << :shutdown unless @port.closed?
328
+ @thread.join
329
+ @port.close unless @port.closed?
330
+ @thread = nil
331
+ end
332
+
333
+ private
334
+
335
+ def receive_messages
336
+ loop do
337
+ message = @port.receive
338
+ break if message == :shutdown
339
+
340
+ handle(message)
341
+ end
342
+ rescue Ractor::ClosedError
343
+ nil
344
+ end
345
+
346
+ def handle(message)
347
+ type, task_id, worker_port, cancellation_port = message
348
+ case type
349
+ when :finished then handle_finished(task_id)
350
+ when :running then handle_running(task_id)
351
+ else handle_start(task_id, worker_port, cancellation_port)
352
+ end
353
+ rescue Ractor::ClosedError
354
+ nil
355
+ end
356
+
357
+ def handle_finished(task_id)
358
+ @mutex.synchronize do
359
+ @contexts.delete(task_id)
360
+ @running.delete(task_id)
361
+ end
362
+ end
363
+
364
+ def handle_running(task_id)
365
+ @mutex.synchronize { @running[task_id] = true if @contexts.key?(task_id) }
366
+ end
367
+
368
+ def handle_start(task_id, worker_port, cancellation_port)
369
+ directive = @mutex.synchronize do
370
+ if @reason
371
+ @reason
372
+ else
373
+ @contexts[task_id] = [worker_port, cancellation_port]
374
+ :run
375
+ end
376
+ end
377
+ worker_port << directive
378
+ end
379
+
380
+ def signal(active, reason)
381
+ active.each do |worker_port, cancellation_port|
382
+ cancellation_port.close unless cancellation_port.closed?
383
+ worker_port << reason
384
+ rescue Ractor::ClosedError
385
+ nil
386
+ end
387
+ end
388
+ end
389
+
390
+ # A handle for the eventual result of one submitted job.
391
+ #
392
+ # A future is returned by {Pool#submit}. Calling {#value} waits for its job
393
+ # to settle, while {#complete?} checks its state without blocking.
394
+ class Future
395
+ # @private
396
+ def initialize(pool, task_id, result_port, cancellation_port)
397
+ @pool = pool
398
+ @task_id = task_id
399
+ @result_port = result_port
400
+ @cancellation_port = cancellation_port
401
+ @mutex = Mutex.new
402
+ @condition = ConditionVariable.new
403
+ @complete = false
404
+ end
405
+
406
+ # Waits for this job to finish and returns its result.
407
+ #
408
+ # If the job raises, this method raises the corresponding
409
+ # {TaskError}. A cancelled job raises {CancelledError}. A timeout returns
410
+ # `nil` without cancelling or otherwise changing the job; when a job's
411
+ # actual result is `nil`, use {#complete?} to distinguish it from a
412
+ # timeout.
413
+ #
414
+ # @param timeout [Numeric, nil] maximum wait in seconds; `nil` waits
415
+ # without a deadline
416
+ # @return [Object, nil] job result, or `nil` when the timeout expires
417
+ # @raise [ArgumentError] if timeout is negative or not numeric
418
+ # @raise [TaskError] if the job raises a `StandardError` or its result
419
+ # cannot cross a Ractor boundary
420
+ # @raise [CancelledError] if the job is cancelled
421
+ # @raise [Error] if the pipeline fails before the job settles
422
+ def value(timeout: nil)
423
+ validate_timeout!(timeout)
424
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout if timeout
425
+
426
+ @mutex.synchronize do
427
+ until @complete
428
+ remaining = deadline && deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
429
+ return nil if remaining && remaining <= 0
430
+
431
+ @condition.wait(@mutex, remaining)
432
+ end
433
+
434
+ raise @error if @error
435
+
436
+ @result
437
+ end
438
+ end
439
+
440
+ # Whether this future has reached a terminal outcome.
441
+ #
442
+ # Completed, failed, and cancelled futures are all complete. This method
443
+ # does not wait for an unfinished job.
444
+ #
445
+ # @return [Boolean] `true` after the result or error has been recorded
446
+ def complete?
447
+ @mutex.synchronize { @complete }
448
+ end
449
+
450
+ private
451
+
452
+ def validate_timeout!(timeout)
453
+ return unless timeout
454
+
455
+ raise ArgumentError, "timeout must be a non-negative number" unless timeout.is_a?(Numeric) && timeout >= 0
456
+ end
457
+
458
+ def resolve(result, service_time:)
459
+ finish(:completed, service_time) { @result = result }
460
+ end
461
+
462
+ def reject(error, status: :failed, service_time: 0.0)
463
+ finish(status, service_time) do
464
+ @error = error
465
+ @result_port = nil
466
+ end
467
+ end
468
+
469
+ def receive_result
470
+ port = @result_port
471
+ @result_port = nil
472
+ port.receive
473
+ end
474
+
475
+ def signal_cancellation
476
+ @cancellation_port.close unless @cancellation_port.closed?
477
+ end
478
+
479
+ def finish(status, service_time)
480
+ @mutex.synchronize do
481
+ return if @complete
482
+
483
+ yield
484
+ @complete = true
485
+ @pool.__send__(:release, @task_id, status, service_time)
486
+ @condition.broadcast
487
+ end
488
+ end
489
+
490
+ class << self
491
+ private :new
492
+ end
493
+
494
+ private_class_method :new
495
+ end
496
+
497
+ # Admission and settlement methods shared by Pool's public API and Future.
498
+ # @private
499
+ module PoolAdmission
500
+ private
501
+
502
+ def validate_options!(size, capacity, on_error, work)
503
+ raise ArgumentError, "size must be a positive Integer" unless size.is_a?(Integer) && size.positive?
504
+ raise ArgumentError, "capacity must be a positive Integer" unless capacity.is_a?(Integer) && capacity.positive?
505
+ raise ArgumentError, "on_error must be :fail_fast or :continue" unless %i[fail_fast continue].include?(on_error)
506
+ raise ArgumentError, "no work block given" unless work
507
+ end
508
+
509
+ def validate_timeout!(timeout)
510
+ return unless timeout
511
+
512
+ raise ArgumentError, "timeout must be a non-negative number" unless timeout.is_a?(Numeric) && timeout >= 0
513
+ end
514
+
515
+ def register_future(deadline, input)
516
+ @mutex.synchronize do
517
+ wait_for_capacity(deadline)
518
+ expired = deadline && deadline <= Process.clock_gettime(Process::CLOCK_MONOTONIC)
519
+ return [nil, nil] if @futures.size >= @capacity && @state == :running && expired
520
+
521
+ ensure_running!
522
+ task_id = (@next_id += 1)
523
+ result_port = Ractor::Port.new
524
+ cancellation_port = Ractor::Port.new
525
+ future = Future.__send__(:new, self, task_id, result_port, cancellation_port)
526
+ @futures[task_id] = future
527
+ @metrics.submitted
528
+ @queue.push([task_id, input, result_port, cancellation_port])
529
+ [task_id, future]
530
+ end
531
+ end
532
+
533
+ def wait_for_capacity(deadline)
534
+ while @futures.size >= @capacity && @state == :running
535
+ remaining = deadline && deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
536
+ return if remaining && remaining <= 0
537
+
538
+ @capacity_condition.wait(@mutex, remaining)
539
+ end
540
+ end
541
+
542
+ def ensure_running!
543
+ raise StateError, "pool must be started before submit" if @state == :initialized
544
+ raise ClosedError, "pool is not accepting tasks (#{@state})" unless @state == :running
545
+ end
546
+
547
+ def release(task_id, status, service_time)
548
+ @mutex.synchronize do
549
+ @metrics.finish(status, service_time) if @futures.delete(task_id)
550
+ @capacity_condition.broadcast
551
+ end
552
+ end
553
+ end
554
+
555
+ # Cancellation API and future signaling shared by Pool.
556
+ # @private
557
+ module PoolCancellation
558
+ # Stops admission and requests cooperative cancellation of accepted work.
559
+ #
560
+ # All outstanding futures are settled as cancelled. Running jobs receive
561
+ # the reason through their {TaskContext}; they must call
562
+ # {TaskContext#checkpoint!} or otherwise observe cancellation to stop.
563
+ # This method waits for the worker pipeline to exit, so it can wait
564
+ # indefinitely if running work never cooperates or returns. Repeated
565
+ # calls are safe and preserve the first cancellation reason.
566
+ #
567
+ # Cancelling before {Pool#start} moves the pool directly to `:cancelled`.
568
+ #
569
+ # @param reason [Object] reason converted to a string and exposed by
570
+ # {CancelledError#reason} and {TaskContext#reason}
571
+ # @return [Pool] this pool
572
+ # @see TaskContext
573
+ def cancel(reason: "pool cancelled")
574
+ cancellation_reason = normalize_cancellation_reason(reason)
575
+ futures = prepare_cancellation(cancellation_reason)
576
+ if futures == :initialized
577
+ @context_monitor.stop
578
+ return self
579
+ end
580
+ return self unless futures
581
+
582
+ cancel_futures(futures, cancellation_reason)
583
+ @context_monitor.cancel(cancellation_reason)
584
+ @dispatcher&.join
585
+ self
586
+ end
587
+
588
+ private
589
+
590
+ def normalize_cancellation_reason(reason)
591
+ reason.to_s.dup.freeze
592
+ end
593
+
594
+ def cancel_futures(futures, reason)
595
+ futures.each do |future|
596
+ future.__send__(:signal_cancellation)
597
+ future.__send__(:reject, CancelledError.new(reason), status: :cancelled)
598
+ end
599
+ end
600
+
601
+ def signal_futures(futures)
602
+ futures.each { |future| future.__send__(:signal_cancellation) }
603
+ end
604
+
605
+ def prepare_cancellation(reason)
606
+ @mutex.synchronize do
607
+ return if %i[cancelling cancelled stopped failed].include?(@state)
608
+
609
+ @cancel_reason = reason
610
+ if @state == :initialized
611
+ @state = :cancelled
612
+ close_admission
613
+ return :initialized
614
+ end
615
+
616
+ @state = :cancelling
617
+ close_admission
618
+ @futures.values
619
+ end
620
+ end
621
+
622
+ def close_admission
623
+ @queue.clear
624
+ @queue.close
625
+ @capacity_condition.broadcast
626
+ end
627
+ end
628
+
629
+ # Resolves pipeline outcomes and applies the selected failure policy.
630
+ # @private
631
+ module PoolOutcome
632
+ private
633
+
634
+ def receive_outcome(outcome)
635
+ _, task_id = outcome
636
+ future = @mutex.synchronize { @futures[task_id] }
637
+ unless future
638
+ acknowledge_outcome
639
+ return
640
+ end
641
+
642
+ settle_outcome(future, outcome)
643
+ acknowledge_outcome
644
+ end
645
+
646
+ def settle_outcome(future, outcome)
647
+ status, task_id, value, detail, trace, duration = outcome
648
+ if status == :ok
649
+ future.__send__(:resolve, future.__send__(:receive_result), service_time: duration)
650
+ elsif status == :cancelled
651
+ future.__send__(:reject, CancelledError.new(value || "task cancelled"), status: :cancelled)
652
+ elsif @on_error == :fail_fast
653
+ fail_pool(TaskFailure.new(task_id, value, detail, trace, duration))
654
+ else
655
+ error = TaskError.new(task_id, value, detail, trace)
656
+ future.__send__(:reject, error, status: :failed, service_time: duration)
657
+ end
658
+ end
659
+
660
+ def acknowledge_outcome
661
+ @outcome_acks << true if @on_error == :fail_fast
662
+ end
663
+ end
664
+
665
+ # A bounded pool of persistent Ractor workers for independent CPU jobs.
666
+ #
667
+ # Constructing a pool configures it but does not start workers. Call
668
+ # {#start}, submit work, then call {#shutdown} to drain accepted jobs. Set
669
+ # `capacity` to control the maximum number of accepted jobs without a
670
+ # terminal outcome; submissions block at capacity unless given a timeout.
671
+ #
672
+ # Work executes in isolated Ractors. The block must be Ractor-shareable.
673
+ # Inputs and results cross Ractor boundaries using Ruby's normal copying
674
+ # rules, so all submitted inputs and returned results must be sendable.
675
+ # An optional second block parameter (or a rest parameter) receives a
676
+ # {TaskContext} for cooperative cancellation.
677
+ #
678
+ # By default, the first job failure fails the pool and cancels other
679
+ # outstanding futures. Use `on_error: :continue` to isolate each job's
680
+ # failure to its own future.
681
+ #
682
+ # The pool exposes these states through {#state}:
683
+ # `:initialized`, `:running`, `:stopping`, `:cancelling`, `:cancelled`,
684
+ # `:stopped`, and `:failed`.
685
+ #
686
+ # pool = Ractor::Forge::Pool.new(size: 4, capacity: 12,
687
+ # on_error: :continue) do |input|
688
+ # transform(input)
689
+ # end
690
+ # pool.start
691
+ # future = pool.submit(input, timeout: 0.25)
692
+ # result = future&.value(timeout: 5)
693
+ # pool.shutdown
694
+ #
695
+ # @see Future
696
+ # @see TaskContext
697
+ # @!method cancel(reason: "pool cancelled")
698
+ # Stops accepting work and requests cooperative cancellation of accepted
699
+ # jobs. All outstanding futures settle as cancelled immediately; running
700
+ # jobs receive a signal and must observe their {TaskContext} and return
701
+ # before this call finishes. The first reason is retained on repeated
702
+ # calls.
703
+ #
704
+ # @param reason [Object] value converted to a string and exposed on
705
+ # cancellation errors and task contexts
706
+ # @return [Pool] this pool after the pipeline exits
707
+ class Pool
708
+ include PoolAdmission
709
+ include PoolCancellation
710
+ include PoolOutcome
711
+
712
+ # Configured number of persistent worker Ractors.
713
+ #
714
+ # @return [Integer] worker count specified at construction
715
+ attr_reader :size
716
+
717
+ # Creates a configured pool without starting its worker pipeline.
718
+ #
719
+ # The work block must be shareable by Ractors. Declare one positional
720
+ # parameter for ordinary jobs, or a second parameter to receive a
721
+ # {TaskContext} and support cooperative cancellation.
722
+ #
723
+ # @param size [Integer] number of persistent worker Ractors; must be
724
+ # positive
725
+ # @param capacity [Integer] maximum accepted jobs with unsettled futures;
726
+ # defaults to twice `size` and must be positive
727
+ # @param on_error [Symbol] `:fail_fast` (default) to stop the pool after
728
+ # the first job error, or `:continue` to isolate job errors. Retries
729
+ # are never automatic.
730
+ # @yield [input] processes one input in a worker Ractor
731
+ # @yieldparam input [Object] sendable input submitted to the pool
732
+ # @yieldparam context [TaskContext] optional second or rest argument for
733
+ # cooperative cancellation
734
+ # @yieldreturn [Object] sendable result returned by {Future#value}
735
+ # @return [Pool] configured pool in the `:initialized` state
736
+ # @raise [ArgumentError] if size, capacity, or on_error is invalid, or no
737
+ # work block is provided
738
+ # @raise [Ractor::IsolationError] if the work block cannot be shared with
739
+ # worker Ractors
740
+ def initialize(size:, capacity: size * 2, on_error: :fail_fast, &work)
741
+ configure(size, capacity, on_error, work)
742
+ initialize_runtime(work)
743
+ end
744
+
745
+ def initialize_runtime(work)
746
+ @context_monitor = ContextMonitor.new
747
+ @worker = Worker.build_proc(
748
+ Ractor.shareable_proc(&work), @context_monitor, accepts_context?(work)
749
+ )
750
+ @queue = SizedQueue.new(@capacity)
751
+ initialize_lifecycle
752
+ @metrics = Metrics.new(@size)
753
+ @outcome_acks = Queue.new
754
+ @dispatcher = nil
755
+ end
756
+
757
+ def initialize_lifecycle
758
+ @mutex = Mutex.new
759
+ @capacity_condition = ConditionVariable.new
760
+ @startup_condition = ConditionVariable.new
761
+ @state = :initialized
762
+ @startup_result = :pending
763
+ @next_id = 0
764
+ @futures = {}
765
+ end
766
+ private :initialize_runtime
767
+ private :initialize_lifecycle
768
+
769
+ def configure(size, capacity, on_error, work)
770
+ validate_options!(size, capacity, on_error, work)
771
+ @size = size
772
+ @capacity = capacity
773
+ @on_error = on_error
774
+ end
775
+ private :configure
776
+
777
+ # Starts the worker pipeline and waits until it is ready for submissions.
778
+ #
779
+ # A pool can only be started once. Use {#shutdown} to drain work or
780
+ # {#cancel} to request cooperative cancellation.
781
+ #
782
+ # @return [Pool] this pool after worker startup succeeds
783
+ # @raise [StateError] if called outside the `:initialized` state
784
+ # @raise [StartupError] if worker startup fails; the original exception
785
+ # is available as `cause`
786
+ def start
787
+ @mutex.synchronize { start_dispatcher }
788
+
789
+ startup_error = wait_for_startup
790
+ if startup_error
791
+ @dispatcher&.join
792
+ raise StartupError, "pool startup failed: #{startup_error.message}", cause: startup_error
793
+ end
794
+
795
+ self
796
+ end
797
+
798
+ # Submits one input and returns a future for its result.
799
+ #
800
+ # Submission blocks while `capacity` accepted tasks are still
801
+ # outstanding. A finite timeout bounds that wait; returning `nil` means
802
+ # the input was not admitted. Inputs are copied or shared according to
803
+ # Ruby's Ractor message rules.
804
+ #
805
+ # @param input [Object] sendable job input
806
+ # @param timeout [Numeric, nil] maximum time in seconds to wait for an
807
+ # admission slot; `nil` waits without a deadline
808
+ # @return [Future, nil] future for an accepted input, or `nil` on timeout
809
+ # @raise [ArgumentError] if timeout is negative or not numeric
810
+ # @raise [StateError] if the pool has not been started
811
+ # @raise [ClosedError] if the pool no longer accepts submissions
812
+ def submit(input, timeout: nil)
813
+ validate_timeout!(timeout)
814
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout if timeout
815
+ _, future = register_future(deadline, input)
816
+ return nil unless future
817
+
818
+ future
819
+ end
820
+
821
+ # Stops accepting tasks, drains accepted work, and joins the pipeline.
822
+ #
823
+ # This is a graceful shutdown: jobs already accepted are allowed to
824
+ # finish. Calling shutdown more than once is safe. A pool shut down before
825
+ # it is started transitions directly from `:initialized` to `:stopped`.
826
+ # It waits for accepted work to return; use {#cancel} for cooperative
827
+ # cancellation instead of draining.
828
+ #
829
+ # @return [Pool] this pool after shutdown completes
830
+ # @see #close
831
+ def shutdown
832
+ @mutex.synchronize do
833
+ if @state == :initialized
834
+ @state = :stopped
835
+ @queue.close
836
+ @context_monitor.stop
837
+ @capacity_condition.broadcast
838
+ return self
839
+ end
840
+
841
+ unless %i[stopped failed cancelled cancelling].include?(@state)
842
+ @state = :stopping
843
+ @queue.close
844
+ @capacity_condition.broadcast
845
+ end
846
+ end
847
+ @dispatcher&.join
848
+ self
849
+ end
850
+
851
+ # Alias for {#shutdown}.
852
+ #
853
+ # @return [Pool] this pool after shutdown completes
854
+ alias close shutdown
855
+
856
+ # The current pool lifecycle state.
857
+ #
858
+ # Possible values are `:initialized`, `:running`, `:stopping`,
859
+ # `:cancelling`, `:cancelled`, `:stopped`, and `:failed`.
860
+ #
861
+ # @return [Symbol] current state
862
+ def state
863
+ @mutex.synchronize { @state }
864
+ end
865
+
866
+ # Returns an immutable snapshot of pool state and job metrics.
867
+ #
868
+ # The returned hash is frozen and contains scalar values from one
869
+ # pool-state snapshot. `submitted` counts admitted jobs, not timed-out
870
+ # submission attempts. `active_workers` is maintained by the lifecycle
871
+ # monitor and may briefly lag a worker transition. `queue_depth` counts
872
+ # tasks waiting in the Pool's input queue; `in_flight` counts every
873
+ # accepted task without a terminal outcome, including work in pipeline
874
+ # links and executing jobs.
875
+ #
876
+ # Counter invariant:
877
+ #
878
+ # submitted == completed + failed + cancelled + in_flight
879
+ #
880
+ # `completed` counts successful jobs only. Throughput is completed jobs
881
+ # per elapsed monotonic second since startup began. `average_service_time`
882
+ # is the mean worker-reported service duration for completed and failed
883
+ # jobs, in seconds; cancelled jobs are excluded. Before the pool starts,
884
+ # throughput and average service time are both zero.
885
+ #
886
+ # @return [Hash{Symbol => Object}] frozen snapshot with keys:
887
+ # `:state`, `:workers`, `:active_workers`, `:queue_depth`,
888
+ # `:submitted`, `:completed`, `:failed`, `:cancelled`, `:in_flight`,
889
+ # `:throughput_per_second`, and `:average_service_time`
890
+ def metrics
891
+ @mutex.synchronize do
892
+ @metrics.snapshot(
893
+ state: @state, queue_depth: @queue.size, in_flight: @futures.size,
894
+ active_workers: @context_monitor.active_workers
895
+ )
896
+ end
897
+ end
898
+
899
+ private
900
+
901
+ def start_dispatcher
902
+ raise StateError, "cannot start pool in #{@state} state" unless @state == :initialized
903
+
904
+ @state = :running
905
+ begin
906
+ @metrics.start
907
+ @context_monitor.start
908
+ @dispatcher = Thread.new { dispatch }
909
+ rescue Exception => e # rubocop:disable Lint/RescueException
910
+ @context_monitor.stop
911
+ @state = :failed
912
+ @startup_result = :failed
913
+ @startup_error = e
914
+ @capacity_condition.broadcast
915
+ @startup_condition.broadcast
916
+ raise StartupError, "pool startup failed: #{e.message}", cause: e
917
+ end
918
+ end
919
+
920
+ def wait_for_startup
921
+ @mutex.synchronize do
922
+ @startup_condition.wait(@mutex) while @startup_result == :pending
923
+ @startup_error if @startup_result == :failed
924
+ end
925
+ end
926
+
927
+ def accepts_context?(work)
928
+ positional = work.parameters.select { |kind, _| %i[req opt].include?(kind) }
929
+ positional.size > 1 || work.parameters.any? { |kind, _| kind == :rest }
930
+ end
931
+
932
+ def dispatch
933
+ source = QueueSource.for_pool(@queue, @size, @on_error, @outcome_acks) { mark_started }
934
+ Ractor::Pipeline.stream(source)
935
+ .pipe(lanes: @size, &@worker)
936
+ .each { |outcome| receive_outcome(outcome) }
937
+ @mutex.synchronize do
938
+ @state = :cancelled if @state == :cancelling
939
+ @state = :stopped unless %i[failed cancelled].include?(@state)
940
+ end
941
+ rescue Exception => e # rubocop:disable Lint/RescueException
942
+ mark_startup_failed(e)
943
+ fail_pool(e)
944
+ ensure
945
+ @context_monitor.stop
946
+ end
947
+
948
+ def mark_started
949
+ @mutex.synchronize do
950
+ return unless @startup_result == :pending
951
+
952
+ @startup_result = :started
953
+ @startup_condition.broadcast
954
+ end
955
+ end
956
+
957
+ def mark_startup_failed(error)
958
+ @mutex.synchronize do
959
+ return unless @startup_result == :pending
960
+
961
+ @startup_result = :failed
962
+ @startup_error = error
963
+ @startup_condition.broadcast
964
+ end
965
+ end
966
+
967
+ def fail_pool(error)
968
+ pending = @mutex.synchronize do
969
+ if @state == :cancelling
970
+ @state = :cancelled
971
+ else
972
+ @state = :failed
973
+ @cancel_reason = error.is_a?(TaskFailure) ? "task #{error.task_id} failed" : "pool failed"
974
+ end
975
+ @queue.clear
976
+ @queue.close
977
+ @capacity_condition.broadcast
978
+ @futures.to_a
979
+ end
980
+ futures = pending
981
+ signal_futures(futures.map(&:last))
982
+ @context_monitor.cancel(@cancel_reason)
983
+ futures.each { |task_id, future| reject_after_failure(task_id, future, error) }
984
+ end
985
+
986
+ def reject_after_failure(task_id, future, error)
987
+ if error.is_a?(TaskFailure) && error.task_id == task_id
988
+ task_error = TaskError.new(task_id, error.original_class, error.original_message, error.original_backtrace)
989
+ future.__send__(:reject, task_error, status: :failed, service_time: error.service_time)
990
+ elsif error.is_a?(TaskFailure)
991
+ reason = "task #{error.task_id} failed; pool stopped before this task completed"
992
+ future.__send__(:reject, CancelledError.new(reason), status: :cancelled)
993
+ else
994
+ failure = Error.new("pool failed: #{error.class}: #{error.message}")
995
+ failure.set_backtrace(error.backtrace)
996
+ future.__send__(:reject, failure, status: :failed)
997
+ end
998
+ end
999
+ end
1000
+
1001
+ # Adapts the bounded submission queue to the pipeline's Enumerable source.
1002
+ # @private
1003
+ class QueueSource
1004
+ def self.for_pool(queue, workers, on_error, acknowledgements, &on_start)
1005
+ fail_fast = on_error == :fail_fast
1006
+ window = workers if fail_fast
1007
+ acknowledgements = nil unless fail_fast
1008
+ new(queue, on_start:, window:, acknowledgements:)
1009
+ end
1010
+
1011
+ def initialize(queue, on_start: nil, window: nil, acknowledgements: nil)
1012
+ @queue = queue
1013
+ @on_start = on_start
1014
+ @window = window
1015
+ @acknowledgements = acknowledgements
1016
+ end
1017
+
1018
+ def each
1019
+ # The pipeline starts its feeder only after every worker Ractor has
1020
+ # been created and wired. This is the Pool's startup-ready boundary.
1021
+ @on_start&.call
1022
+ outstanding = 0
1023
+ loop do
1024
+ item = @queue.pop
1025
+ break if item.nil?
1026
+
1027
+ yield item
1028
+ next unless @window
1029
+
1030
+ outstanding += 1
1031
+ next unless outstanding >= @window
1032
+
1033
+ # In fail-fast mode, don't let accepted-but-unstarted work accumulate
1034
+ # in the pipeline's push links ahead of a possible task failure.
1035
+ @acknowledgements.pop
1036
+ outstanding -= 1
1037
+ end
1038
+ end
1039
+ end
1040
+ end
1041
+ end