blib/lib/Acme/Parataxis.pm untested

filter: Statementstmt 0.0% 0 / 1157 Branchbran 0.0% 0 / 584 Conditioncond 0.0% 0 / 340 MC/DCmcdc 0.0% 0 / 203 Subroutinesub 0.0% 0 / 112 Podpod 0.0% 0 / 83 totaltotal 0.0% 0 / 2479 CC 289 SCAR 62.4
CC
289
Cov
0%
run
2450.0
_park
1332.0
with_timeout
812.0
CRAP 512.4
1 use v5.40;
2 no warnings 'recursion'; # fibers run on separate heap stacks; Perl's C-stack-depth heuristic misfires there
3 use experimental qw[class try];
4  
5 package Acme::Parataxis v0.1.6 {
6 use Affix qw[affix :types];
7 use Config;
8 use File::Spec;
9 use File::Basename qw[dirname];
10 use Time::HiRes qw[usleep];
11 use Exporter qw[import];
12 use Carp qw[croak];
13 use builtin qw[refaddr];
14 use Acme::Parataxis::Error;
15 our %EXPORT_TAGS = (
16 all => [
17 our @EXPORT_OK
18 = qw[
19 run spawn yield await stop async fiber
20 await_sleep await_read await_write await_core_id
21 current_fid tid root maybe_yield on_wake with_timeout with_cancel nursery pmap wait_all wait_any
22 set_max_threads max_threads set_max_fibers max_fibers dump_fibers fd_setsize
23 backtrace_depth
24 atomically retry
25 set_preempt_threshold
26 ]
27 ]
28 );
29 #
30 our @IPC_BUFFER;
31 my $lib;
32 my @SCHEDULER_QUEUE;
33 my %SCHEDULER_QUEUED;
34 my $IS_RUNNING = 0;
35 my $DRIVER; # the attached Acme::Parataxis::Driver (undef = the worker-pool fallback path), see attach_loop
36 my %PARKED; # fid => true, while the fiber is suspended in a blocking wait (see _park / _resume_hooks)
37 my %PARK_REGS; # fid => coderef that removes a parked fiber from its waiter list when its park is interrupted
38 our %FIBER_LOCALS; # fiber-object refaddr => { local-id => value }; stashes for Acme::Parataxis::Local
39 our @INHERIT_LOCAL_IDS; # ids of Acme::Parataxis::Local objects created with inherit => 1; spawn seeds these from parent to child
40 our %ACTOR_REGISTRY; # registered actor names => Acme::Parataxis::Actor handles; the actor(name)/whereis table
41 my $BACKTRACE_DEPTH = 6; # max user-side caller frames captured at each park (0 disables the capture)
42 my $VIRTUAL_CLOCK; # undef = wall clock; a running virtual run sets this to the current virtual ms
43 my %VIRTUAL_DEADLINES; # fid => absolute virtual-ms deadline of that fiber's one armed virtual timer
44 my @VIRTUAL_TIMERS; # [deadline_ms, fid] ascending; lazy deletion via %VIRTUAL_DEADLINES
45  
46 # Fiber object layout: a flat arrayref of slots rather than perlclass objects (array access is much cheaper than
47 # classes and even hash lookup on the hot spawn/await path).
48 use constant {
49 F_CODE => 0,
50 F_IS_DONE => 1,
51 F_ERROR => 2,
52 F_RESULT => 3,
53 F_FID => 4,
54 F_IS_READY => 5,
55 F_CALLBACKS => 6,
56 F_WAITER => 7,
57 F_LAST_STATUS => 8,
58 F_PRIORITY => 9,
59 F_WAIT_REASON => 10,
60 F_WAKE_HOOKS => 11,
61 F_INTERRUPT => 12,
62 F_CANCEL_SCOPES => 13,
63 F_DEADLINE_SCOPES => 14,
64 F_DEADLINE_ARMED => 15
65 };
66  
67 # Scheduler run queue. Kept sorted by descending priority (stable for equal priorities, so a group of same-priority fibers stays FIFO).
68 sub _enqueue ($fiber) {
69 my $fid = $fiber->[F_FID];
70 return if $SCHEDULER_QUEUED{$fid};
71 $SCHEDULER_QUEUED{$fid} = 1;
72 my $prio = $fiber->[F_PRIORITY] // 0;
73 my $i = 0;
74 $i++ while $i < @SCHEDULER_QUEUE && ( $SCHEDULER_QUEUE[$i]->[F_PRIORITY] // 0 ) >= $prio;
75 splice @SCHEDULER_QUEUE, $i, 0, $fiber;
76 }
77  
78 # All C fiber ids that are currently live. Used by run() to snapshot the fibers that predate a run so its
79 # deadlock detector only considers fibers the run actually created (fibers leaked by a prior deadlocked run stay
80 # parked forever and would otherwise poison every later run).
81 sub _live_fiber_ids () {
82 my @ids;
83 my $cap = Acme::Parataxis::get_fiber_capacity();
84 for ( my $fid = 0; $fid < $cap; $fid++ ) {
85 my $obj = Acme::Parataxis::get_fiber_by_id($fid);
86 push @ids, $fid if defined $obj && ( ref $obj || '' ) ne '';
87 }
88 return @ids;
89 }
90  
91 # Diagnostics: a snapshot of every live fiber, riding entirely on wait_reason: _park records
92 # [reason, file, line] on the fiber before it yields and _resume_hooks clears it on a natural wake, so a
93 # live fiber that still carries a reason (or is in %PARKED) is blocked, not merely preempted. WAITING =
94 # parked on a wait; READY = in the scheduler run queue; RUNNING = the fiber calling the snapshot (only
95 # when taken from inside a run); RUNNABLE = live but neither parked nor queued (e.g. a generator's body
96 # or a fiber surrendered mid-quantum). Each record also carries the bounded user-side caller
97 # chain (its fourth element) captured at the park; the top site is still the wait_reason site (the user's
98 # call for direct waits like await_sleep, the wait's own method for Sync/Channel waits whose level
99 # targeting is tuned for their error messages).
100 sub _fiber_snapshot () {
101 my $current = get_current_parataxis_id();
102 my @rows;
103 for my $fid ( _live_fiber_ids() ) {
104 my $fiber = Acme::Parataxis::get_fiber_by_id($fid);
105 next unless $fiber && ref $fiber;
106 my $reason = $fiber->[F_WAIT_REASON]; # undef once the fiber is woken normally
107 my $state
108 = ( defined $reason || $PARKED{$fid} ) ? 'WAITING' :
109 $SCHEDULER_QUEUED{$fid} ? 'READY' :
110 ( $current >= 0 && $fid == $current ) ? 'RUNNING' :
111 'RUNNABLE';
112 push @rows, { fid => $fid, state => $state, reason => $reason };
113 }
114 return [ sort { $a->{fid} <=> $b->{fid} } @rows ];
115 }
116  
117 # Dumps every live fiber. Returns the arrayref of { fid, state, reason (wait_reason site; its fourth element is
118 # the backtrace arrayref of [pkg, file, line, sub] user-side frames, [] when the capture is off or empty) }
119 # records and, when called with a filehandle, also prints a human-readable report there (dump_fibers() with no
120 # argument only returns the data). Safe to call from anywhere: top-level (outside a run) reports fibers leaked by
121 # an earlier deadlocked run, inside a run it classifies each live fiber exactly.
122 sub dump_fibers {
123 my $invocant = shift;
124 if ( !defined $invocant ||
125 ( ( ref $invocant || $invocant ) ne __PACKAGE__ && !( builtin::blessed($invocant) && $invocant->isa(__PACKAGE__) ) ) ) {
126 unshift @_, $invocant if defined $invocant;
127 $invocant = __PACKAGE__;
128 }
129 my $fh = shift;
130 my $rows = _fiber_snapshot();
131 return $rows unless $fh;
132 say $fh 'Acme::Parataxis live fiber dump';
133 say $fh ' fid state wait reason where';
134 for my $r (@$rows) {
135 my ( $file, $line ) = $r->{reason} ? @{ $r->{reason} }[ 1, 2 ] : ( '-', '-' );
136 say $fh sprintf ' %-4d %-8s %-17s %s:%s', $r->{fid}, $r->{state}, ( $r->{reason} && $r->{reason}[0] ) // '-', $file, $line;
137 for my $bt ( @{ $r->{reason}[3] // [] } ) {
138 say $fh sprintf ' at %s:%d %s', @$bt[ 1, 2, 3 ];
139 }
140 }
141 return $rows;
142 }
143  
144 sub _bind_functions ($l) {
145 affix $l, 'init_system', [], Int;
146 affix $l, 'create_fiber', [ Pointer [SV], Pointer [SV] ], Int;
147 affix $l, 'spawn_fiber', [ Pointer [SV], Pointer [SV] ], Pointer [SV];
148 affix $l, 'coro_call', [ Int, Pointer [SV] ], Pointer [SV];
149 affix $l, 'run_fiber_checked', [ Int, Pointer [SV] ], Int;
150 affix $l, 'coro_transfer', [ Int, Pointer [SV] ], Pointer [SV];
151 affix $l, 'coro_yield', [ Pointer [SV] ], Pointer [SV];
152 affix $l, 'is_finished', [Int], Int;
153 affix $l, 'get_fiber_by_id', [Int], Pointer [SV];
154 affix $l, 'get_live_fiber_count', [], Int;
155 affix $l, 'get_fiber_capacity', [], Int;
156 affix $l, 'destroy_coro', [Int], Void;
157 affix $l, 'para_release_cv_depth', [ Pointer [SV] ], Void;
158 affix $l, 'para_cvreg_purge_fiber', [Int], Void;
159 affix $l, 'force_depth_zero', [ Pointer [SV] ], Void;
160 affix $l, 'cleanup', [], Void;
161 affix $l, 'get_os_thread_id_export', [], Int;
162 affix $l, 'get_current_parataxis_id', [], Int;
163 affix $l, 'submit_c_job', [ Int, LongLong, Int ], Int;
164 affix $l, 'drain_jobs', [ Pointer [SV] ], Void;
165 affix $l, 'check_for_completion', [], Int;
166 affix $l, 'get_outstanding_jobs', [], Int;
167 affix $l, 'recall_sleep_jobs_for_fiber', [Int], Int;
168 affix $l, 'get_job_result', [Int], Pointer [SV];
169 affix $l, 'get_job_coro_id', [Int], Int;
170 affix $l, 'free_job_slot', [Int], Void;
171 affix $l, 'get_thread_pool_size', [], Int;
172 affix $l, 'get_max_thread_pool_size', [], Int;
173 affix $l, 'get_fd_setsize', [], Int;
174 affix $l, 'set_max_threads', [Int], Void;
175 affix $l, 'get_max_fibers', [], Int;
176 affix $l, 'set_max_fibers', [Int], Void;
177 affix $l, [ 'set_preempt_threshold' => '_set_preempt_threshold' ], [LongLong], Void;
178 affix $l, [ 'maybe_yield' => '_maybe_yield' ], [], Pointer [SV];
179 affix $l, 'get_preempt_count', [], LongLong;
180  
181 # Capture the main interpreter context
182 init_system();
183 if ( $^O eq 'MSWin32' ) {
184 my $perl_dll = $Config{libperl};
185 $perl_dll =~ s/^lib//;
186 $perl_dll =~ s/\.a$//;
187 $perl_dll .= '.' . $Config{so};
188 my $p = Affix::load_library($perl_dll);
189 affix $p, 'win32_get_osfhandle', [Int], LongLong;
190 }
191 }
192  
193 BEGIN {
194 my $lib_name = ( $^O eq 'MSWin32' ? '' : 'lib' ) . 'parataxis.' . $Config{so};
195 my @paths;
196 push @paths, File::Spec->catfile( dirname(__FILE__), $lib_name );
197 push @paths, File::Spec->catfile( dirname(__FILE__), '..', 'arch', 'auto', 'Acme', 'Parataxis', $lib_name );
198 push @paths, File::Spec->catfile( dirname(__FILE__), '..', '..', 'arch', 'auto', 'Acme', 'Parataxis', $lib_name );
199 push @paths, File::Spec->catfile( dirname(__FILE__), 'auto', 'Acme', 'Parataxis', $lib_name );
200 for my $inc (@INC) {
201 next if ref $inc;
202 push @paths, File::Spec->catfile( $inc, 'auto', 'Acme', 'Parataxis', $lib_name );
203 }
204 for my $path (@paths) {
205 if ( -e $path ) {
206 $lib = Affix::load_library($path);
207 last if $lib;
208 }
209 }
210 if ( !$lib ) {
211 my $why = eval { Affix::get_last_error_message() };
212 $why = '' unless defined $why;
213 $why =~ s/\s+\z//;
214 die 'Could not find or load ' . $lib_name . ( length $why ? ": $why" : '' ) . ' (tried ' . scalar(@paths) . ' paths)';
215 }
216 _bind_functions($lib);
217 }
218  
219 # API aliases and wrappers
220 sub fiber : prototype(&) ($code) { spawn( __PACKAGE__, $code ) }
221 sub async : prototype(&) ($code) { return run($code) }
222  
223 # Index at which user arguments start in @_: 0 when it is a plain call, 1 when $_[0] is a self (package name or
224 # blessed object). This mirrors the shift/unshift invocant dance used elsewhere, but reads $_[0] instead of
225 # shifting, so calling it never reifies the caller's pad @_. A reified @_ left behind in a parked frame trips
226 # pp_entersub's assert(!AvREAL(av))/assert(AvFILLp(av) == -1) when a different fiber later enters the same sub at
227 # the same depth.
228 sub _arg_offset {
229 my $self = $_[0];
230 return ( defined $self && ( ( ref $self || $self ) eq __PACKAGE__ || ( builtin::blessed($self) && $self->isa(__PACKAGE__) ) ) ) ? 1 : 0;
231 }
232  
233 # Aggregate a list of futures into one that resolves when every input has: the result is an arrayref of each
234 # input's result, in input order, or the stored error of the first input to fail (reject-fast, Promise.all style).
235 # Inputs are not cancelled on a rejection; they are independent and keep running, and their later results are
236 # discarded. Zero futures resolve immediately with [] (matching Promise.all([])). An already-resolved input
237 # fires its on_ready callback inline, so a wait_all of ready inputs resolves inline (no fiber needed) and any
238 # mixed ready/pending input resolves the moment the last straggler lands. Inputs must be Acme::Parataxis::Future
239 # objects else croaks. Also callable as Acme::Parataxis->wait_all(...).
240 sub wait_all {
241 my $o = _arg_offset( $_[0] );
242 my @futures = @_[ $o .. $#_ ];
243 @_ = ();
244 croak 'wait_all() requires Acme::Parataxis::Future inputs'
245 if grep { !( defined $_ && ref $_ && $_->isa('Acme::Parataxis::Future') ) } @futures;
246 require Acme::Parataxis::Future;
247 my $all = Acme::Parataxis::Future->new;
248 if ( @futures == 0 ) {
249 $all->set_result( [] );
250 return $all;
251 }
252 my @results;
253 my $pending = scalar @futures;
254 for my $i ( 0 .. $#futures ) {
255 my $idx = $i;
256 my $fut = $futures[$i];
257 $fut->on_ready(
258 sub ($f) {
259 return if $all->is_ready;
260 if ( defined $f->error ) {
261 $all->set_error( $f->error ); # reject-fast: the first failure wins, copied wholesale
262 return;
263 }
264 $results[$idx] = $f->result;
265 $all->set_result( \@results ) if --$pending == 0;
266 }
267 );
268 }
269 return $all;
270 }
271  
272 # Aggregate a list of futures into one that settles with a wholesale copy of the first input to settle - success
273 # or failure (Promise.race). The losers are untouched and keep running; their eventual results are dropped by the
274 # is_ready guard. An already-ready input settles the aggregate inline. At least one input is required (an empty
275 # race would never settle) and each input must be an Acme::Parataxis::Future else croaks. Also callable as
276 # Acme::Parataxis->wait_any(...).
277 sub wait_any {
278 my $o = _arg_offset( $_[0] );
279 my @futures = @_[ $o .. $#_ ];
280 @_ = ();
281 croak 'wait_any() requires at least one Acme::Parataxis::Future input' unless @futures;
282 croak 'wait_any() requires Acme::Parataxis::Future inputs'
283 if grep { !( defined $_ && ref $_ && $_->isa('Acme::Parataxis::Future') ) } @futures;
284 require Acme::Parataxis::Future;
285 my $any = Acme::Parataxis::Future->new;
286 for my $f (@futures) {
287 $f->on_ready(
288 sub ($f) {
289 return if $any->is_ready;
290 if ( defined $f->error ) { $any->set_error( $f->error ) } # wholesale copy of the failure
291 else { $any->set_result( $f->result ) }
292 }
293 );
294 }
295 return $any;
296 }
297  
298 sub yield {
299 my $is_self = _arg_offset( $_[0] );
300 my @deposit = ();
301 push @deposit, $_[$_] for ( $is_self ? 1 : 0 ) .. $#_;
302 if ( !$is_self && @deposit && !defined $deposit[0] ) {
303 shift @deposit;
304 }
305 @_ = ();
306 my $result = coro_yield( \@deposit );
307 return unless defined $result;
308 return ( ref $result eq 'ARRAY' ) ? ( wantarray ? @$result : $result->[-1] ) : $result;
309 }
310  
311 # Park the current fiber in a blocking wait, recording why and where (for diagnostics and cancellation).
312 # $level is the caller stack depth (relative to _park) of the *user* frame whose location should be attributed:
313 # 1 for direct wait sites, 2 for a Semaphore down(), 3 for a Channel get()/put().
314 #
315 # The wait-reason record is [reason, file, line] plus a fourth element, a bounded backtrace of the
316 # user-side callchain (caller frames from just below the recorded site back to the fiber body). Capturing it
317 # is a short caller() loop (~100ns per frame), so it runs unconditionally; backtrace_depth(0) disables it.
318 # On the *re-entry* after the yield returns, a pending interrupt (set by _interrupt) is consumed and thrown, so a
319 # cancelled wait unwinds with Acme::Parataxis::Error::Cancelled (or ::Timeout) right here the caller of the wait
320 # sees the parked wait's own reason in the error's wait_reason.
321 #
322 # $dereg, when given, is a coderef that removes the *parking* fiber from whatever waiter list it is parked on
323 # (Semaphore/Signal/Future/child-await). It runs only when this park is interrupted, before the error is thrown, so
324 # a cancelled fiber never leaves a stale id behind that a later wake could fire at a reused fiber.
325 sub backtrace_depth {
326 my $invocant = shift;
327 if ( !defined $invocant ||
328 ( ( ref $invocant || $invocant ) ne __PACKAGE__ && !( builtin::blessed($invocant) && $invocant->isa(__PACKAGE__) ) ) ) {
329 unshift @_, $invocant if defined $invocant;
330 $invocant = __PACKAGE__;
331 }
332 return $BACKTRACE_DEPTH unless @_;
333 my ($depth) = @_;
334 croak 'backtrace_depth must be a non-negative integer' if !defined $depth || $depth !~ /^\d+$/;
335 $BACKTRACE_DEPTH = $depth;
336 return $BACKTRACE_DEPTH;
337 }
338  
339 sub _park ( $reason, $level = 1, $dereg = undef, $nodl = 0 ) {
340 my $fid = Acme::Parataxis->current_fid;
341 croak '_park() must be called from inside a scheduled fiber' if $fid < 0;
342 my $fiber = Acme::Parataxis->by_id($fid);
343 return unless $fiber; # already finished; nothing to park
344  
345 # Fail fast: a fiber that was interrupted while it was running (not parked), then reached a wait point, throws
346 # at the park entry instead of parking, so a cancellation never gets stranded until some unrelated wake. The
347 # C job table may still have armed the sleep/read this wait was about to submit, so the run can stay alive
348 # until those fire - but no wait is entered after its cancellation.
349 if ( defined( my $pre = $fiber->[F_INTERRUPT] ) ) {
350 my ( $pfile, $pline ) = ( caller($level) )[ 1, 2 ];
351 my $pre_site = [ $pre, $pfile, $pline ];
352 warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d ENTRY failfast pre=%s site=%s\n", ( time - $^T ) * 1000, $fid, $pre, "$pfile:$pline"
353 if $ENV{PARATAXIS_TRACE};
354 $fiber->[F_INTERRUPT] = undef;
355 delete $PARKED{$fid};
356 if ( my $dereg = delete $PARK_REGS{$fid} ) { $dereg->() }
357 warn "PARATAXIS_TRACE park RE-ENTRY fail-fast fid=$fid reason=$reason pre=$pre\n" if $ENV{PARATAXIS_TRACE};
358 my $err = $pre eq 'timeout' ? Acme::Parataxis::Error::Timeout->new( wait_reason => $pre_site ) :
359 Acme::Parataxis::Error::Cancelled->new( wait_reason => $pre_site );
360 die $err;
361 }
362  
363 # A cancellation scope whose token already fired makes every further wait fail fast too: once the fiber's
364 # pending marker has been consumed (a park threw Error::Cancelled and the user caught it), a re-park inside
365 # the still-active scope must not wait in vain. Same shape as the entry fail-fast above, but keyed off the
366 # innermost scope token's own cancelled flag instead of the fiber's interrupt slot.
367 if ( my $scopes = $fiber->[F_CANCEL_SCOPES] ) {
368 my $scope = $scopes->[-1];
369 if ( $scope && $scope->cancelled ) {
370 my ( $pfile, $pline ) = ( caller($level) )[ 1, 2 ];
371 delete $PARKED{$fid};
372 if ( my $old = delete $PARK_REGS{$fid} ) { $old->() }
373 $dereg->() if $dereg; # this park's waiter entry (pushed before _park) is stale: remove it too
374 die Acme::Parataxis::Error::Cancelled->new( wait_reason => [ 'cancel', $pfile, $pline ] );
375 }
376 }
377  
378 # Enclosing with_timeout deadlines bound this park. Every with_timeout whose execution this fiber is
379 # inside pushed an absolute deadline (in ms) onto F_DEADLINE_SCOPES; the innermost/soonest one wins as the
380 # effective bound and the outermost is the backstop. Three consequences, in order:
381 # (a) an already-passed effective bound makes a fresh wait fail fast with Error::Timeout instead of parking
382 # forever - without this, a caught Timeout followed by a re-park under the same fired deadline deadlocked
383 # (nothing was left to interrupt the wait); the check is the bound's own cancellable token being set, not
384 # just the arithmetic (left <= 0), because the deadline helper's timer may fire marginally before the wall
385 # clock reaches abs - a re-park landing in that window would otherwise be missed by the arithmetic and
386 # (since the bound is armed already) would park with nothing left to interrupt it;
387 # (b) exactly one deadline helper is armed per fiber for its effective bound and reused across re-parks
388 # (F_DEADLINE_ARMED), so a re-park never stacks a second timer for the same bound; the helper cancels the
389 # bound's token, which interrupts the registered fiber via the usual _interrupt path and recalls its jobs;
390 # (c) a helper is only armed for a bound the fiber itself owns (own => 1). An *inherited* bound (an enclosing
391 # ancestor's with_timeout, whose token this fiber is not registered on) is always enforced by that
392 # ancestor's own await-park, so arming it here would be redundant - though its absolute deadline still
393 # participates in (a), so an inherited scope whose time has already come fails fast too.
394 # $nodl (now the reap re-park and other transient non-user waits) opts out: a wait whose only job is to reap a
395 # dying child must not fail fast nor arm, since it must linger until the child's death is observed.
396 if ( !$nodl && $fiber->[F_DEADLINE_SCOPES] ) {
397 my $eff;
398 for my $sc ( @{ $fiber->[F_DEADLINE_SCOPES] } ) {
399 next unless defined $sc->{abs};
400 $eff = $sc if !defined $eff || $sc->{abs} < $eff->{abs};
401 }
402 if ( defined $eff ) {
403 my $now = _now_ms();
404 my $left = $eff->{abs} - $now;
405 if ( $left <= 0 || $eff->{tok}->cancelled ) {
406  
407 # This bound is being delivered to this fiber right now. Remember that so with_timeout's boundary
408 # backstop does not synthesise a second Timeout after the user catches this one and the block
409 # returns normally.
410 $eff->{served} = 1;
411 my ( $pfile, $pline ) = ( caller($level) )[ 1, 2 ];
412 delete $PARKED{$fid};
413 if ( my $old = delete $PARK_REGS{$fid} ) { $old->() }
414 $dereg->() if $dereg; # as above: this park's own waiter entry is stale too
415 warn "PARATAXIS_TRACE park DEADLINE fail-fast fid=$fid reason=$reason abs=" . $eff->{abs} . " now=$now\n"
416 if $ENV{PARATAXIS_TRACE};
417 die Acme::Parataxis::Error::Timeout->new( wait_reason => [ 'timeout', $pfile, $pline ] );
418 }
419 if ( $eff->{own} ) {
420 my $already = $fiber->[F_DEADLINE_ARMED];
421 if ( defined $already && $already == $eff->{abs} ) {
422 warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d park DEADLINE reuse abs=%.0f (already armed)\n", ( time - $^T ) * 1000, $fid,
423 $eff->{abs}
424 if $ENV{PARATAXIS_TRACE};
425 }
426 else {
427 my $tok = $eff->{tok};
428 warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d park DEADLINE arm abs=%.0f left=%.0f was=%s\n", ( time - $^T ) * 1000, $fid,
429 $eff->{abs}, $left, defined $already ? $already : 'undef'
430 if $ENV{PARATAXIS_TRACE};
431 fiber {
432 $tok->register;
433 try { await_sleep($left); $tok->cancel } catch ($e) {
434 }
435 };
436 $fiber->[F_DEADLINE_ARMED] = $eff->{abs};
437 }
438 }
439 }
440 }
441 my ( $file, $line ) = ( caller($level) )[ 1, 2 ];
442 my $bt = [];
443 if ($BACKTRACE_DEPTH) {
444 for ( my $i = 1; $i <= $BACKTRACE_DEPTH; $i++ ) {
445 my @c = caller( $level + $i );
446 last unless defined $c[0];
447 next if index( $c[0], 'Acme::Parataxis' ) == 0; # user-side frames only
448 push @$bt, [ $c[0], $c[1], $c[2], $c[3] ];
449 }
450 }
451 my $site = [ $reason, $file, $line, $bt ];
452 $fiber->[F_WAIT_REASON] = $site;
453 $PARKED{$fid} = 1;
454 $PARK_REGS{$fid} = $dereg if defined $dereg;
455 my $res = yield('WAITING');
456 if ( defined( my $kind = $fiber->[F_INTERRUPT] ) ) {
457 if ( $kind eq 'timeout' ) {
458  
459 # The timer cancelled its bound token before waking us. Mark every fired deadline scope on this fiber
460 # as served: if the block catches this Timeout and keeps going, the boundary check must not fire again.
461 for my $sc ( @{ $fiber->[F_DEADLINE_SCOPES] // [] } ) {
462 $sc->{served} = 1 if $sc->{tok} && $sc->{tok}->cancelled;
463 }
464 }
465 my $wsite = $fiber->[F_WAIT_REASON] // [ 'undef', 'undef', 'undef' ];
466 warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d re-entry interrupt consumed kind=%s wait_reason=%s wait_site=%s park_site=%s\n",
467 ( time - $^T ) * 1000, $fid, $kind, $wsite->[0] // 'undef', $wsite->[1] . ':' . $wsite->[2],
468 ( defined $site ? $site->[1] . ':' . $site->[2] : 'n/a' )
469 if $ENV{PARATAXIS_TRACE};
470 $fiber->[F_INTERRUPT] = undef;
471 delete $PARKED{$fid};
472 if ( my $dereg = delete $PARK_REGS{$fid} ) { $dereg->() }
473 my $err = $kind eq 'timeout' ? Acme::Parataxis::Error::Timeout->new( wait_reason => $site ) :
474 Acme::Parataxis::Error::Cancelled->new( wait_reason => $site );
475 die $err;
476 }
477 return $res;
478 }
479  
480 # Marks a fiber as interrupted and, if it is currently parked, wakes it so the interrupt is observed at the park's
481 # re-entry. A fiber that is not parked keeps the marker and the first park it (re)enters afterwards throws. $kind is
482 # 'cancel' or 'timeout' and selects which error the fiber throws.
483 sub _interrupt ( $fid, $kind ) {
484 my $fiber = Acme::Parataxis->by_id($fid);
485 return unless $fiber;
486 return if $fiber->[F_IS_DONE];
487 $fiber->[F_INTERRUPT] = $kind if $kind eq 'cancel' || $kind eq 'timeout';
488 recall_sleep_jobs_for_fiber($fid);
489 _recall_virtual_timer($fid); # a virtual timer has no C job; drop it so a recalled fiber is never re-woken
490 _scheduler_enqueue_by_id($fid) if $PARKED{$fid};
491 return $fiber;
492 }
493  
494 # On a natural wake the park's deregistrations are dropped (the park is over); on an interrupt wake they are kept
495 # for the throw in _park, which runs them before the fiber unwinds.
496 sub _resume_hooks ($fiber) {
497 return unless delete $PARKED{ $fiber->[F_FID] };
498 $fiber->[F_WAIT_REASON] = undef;
499 delete $PARK_REGS{ $fiber->[F_FID] } unless defined $fiber->[F_INTERRUPT];
500 my $hooks = $fiber->[F_WAKE_HOOKS];
501 $fiber->[F_WAKE_HOOKS] = undef;
502 if ($hooks) { $_->($fiber) for @$hooks }
503 }
504  
505 # -- deterministic mock time. Inside run( virtual => 1, ... ) every timer-based wait (await_sleep,
506 # -- with_timeout deadlines, Channel bounds, select, Ticker/RateLimiter) and every wall-clock read consulted
507 # -- through the helpers below rides the virtual clock a test drives with advance(); outside such a run they all
508 # -- fall back to the real wall clock, so real runs are untouched. A virtual run never submits a TASK_SLEEP job:
509 # -- the armed virtual timer parks the fiber in-process and the scheduler idle path fast-forwards the clock to the
510 # -- earliest outstanding deadline instead of sleeping, so an hour-long timeout costs microseconds.
511 sub virtual_now {
512 my $o = _arg_offset( $_[0] );
513 @_ = ();
514 return $VIRTUAL_CLOCK; # undef when not inside a virtual run, else current virtual ms
515 }
516  
517 sub mock_time {
518 my $o = _arg_offset( $_[0] );
519 @_ = ();
520 return defined $VIRTUAL_CLOCK ? $VIRTUAL_CLOCK / 1000 : Time::HiRes::time();
521 }
522 sub _now_ms { return defined $VIRTUAL_CLOCK ? $VIRTUAL_CLOCK : Time::HiRes::time() * 1000 }
523  
524 # Arm a virtual-timer deadline for $fid, $ms from the current virtual clock. A fiber only ever parks in one
525 # timer-backed wait at a time (a wait never returns until its wake), so one deadline per fiber suffices.
526 sub _arm_virtual_timer ( $fid, $ms ) {
527 return if $fid < 0;
528 my $dl = $VIRTUAL_CLOCK + $ms;
529 $VIRTUAL_DEADLINES{$fid} = $dl;
530 push @VIRTUAL_TIMERS, [ $dl, $fid ];
531 @VIRTUAL_TIMERS = sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } @VIRTUAL_TIMERS;
532 return $dl;
533 }
534  
535 # Drop a fiber's armed virtual timer (interrupt, completion, or fiber teardown). Lazy: the sorted array entry
536 # stays until the next fire, where the deadline-hash mismatch skips it.
537 sub _recall_virtual_timer ($fid) { delete $VIRTUAL_DEADLINES{$fid} }
538  
539 # Wake every fiber whose virtual deadline is at or before $now. Returns how many were actually woken (recalled
540 # timers are popped and skipped, never woken).
541 sub _fire_virtual ($now) {
542 my $fired = 0;
543 while ( @VIRTUAL_TIMERS && $VIRTUAL_TIMERS[0][0] <= $now ) {
544 my ( $dl, $fid ) = @{ shift @VIRTUAL_TIMERS };
545 next unless exists $VIRTUAL_DEADLINES{$fid} && $VIRTUAL_DEADLINES{$fid} == $dl;
546 delete $VIRTUAL_DEADLINES{$fid};
547 Acme::Parataxis::_scheduler_enqueue_by_id($fid);
548 $fired++;
549 }
550 return $fired;
551 }
552  
553 # The per-fiber stash behind Acme::Parataxis::Local, created lazily. Keyed by the fiber OBJECT (not its fid):
554 # a spawned fiber that finishes inline has its fid recycled in C with no Perl-side completion hook, so a fid key
555 # would survive into the recycled id and leak state into the next fiber. The object is the fiber's identity for
556 # as long as it lives; entries are pruned where the object's fid is released (_mark_done, is_done) and on DESTROY.
557 sub _fiber_locals ($fiber) { return $FIBER_LOCALS{ refaddr($fiber) } //= {} }
558  
559 sub on_wake {
560 my $invocant = shift;
561 if ( !defined $invocant ||
562 ( ( ref $invocant || $invocant ) ne __PACKAGE__ && !( builtin::blessed($invocant) && $invocant->isa(__PACKAGE__) ) ) ) {
563 unshift @_, $invocant if defined $invocant;
564 $invocant = __PACKAGE__;
565 }
566 my $code = shift;
567 croak 'on_wake() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
568 croak 'on_wake() requires a CODE ref' unless ref $code eq 'CODE';
569 my $fiber = Acme::Parataxis->by_id( Acme::Parataxis->current_fid );
570 push @{ $fiber->[F_WAKE_HOOKS] }, $code;
571 return $code;
572 }
573  
574 # Runs $code as a child fiber with a deadline of $ms milliseconds and returns its value, or throws
575 # Acme::Parataxis::Error::Timeout when the deadline fires first. An optional Acme::Parataxis::CancellationToken
576 # before $code cancels the block like an external deadline. A 0 or undef $ms means no deadline.
577 #
578 # The block runs as a child fiber in the same scheduler, so cooperative waits inside it (await_sleep, ->await,
579 # ->wait, semaphore/signal/channel ops) suspend only the block's fiber. When a token fires, the child's parked wait
580 # is interrupted at its park re-entry and the child unwinds (unregistering from the tokens as it goes);
581 # with_timeout rethrows the resulting error (::Timeout or ::Cancelled) in this fiber, so it can be caught with
582 # eval/try.
583 #
584 # The deadline is enforced per-park by _park from a per-fiber scope stack (F_DEADLINE_SCOPES). This
585 # child pushes its bound onto that stack (inheriting the enclosing with_timeouts of the spawning fiber, so a
586 # nested block's parks are bounded by the whole chain, innermost/soonest first and the outermost as the backstop)
587 # and _park derives the effective bound, fails fast when it has already passed (a caught Timeout followed by a
588 # re-park under the same fired deadline throws again instead of deadlocking), and arms exactly one deadline helper
589 # per fiber for its bound - reused across re-parks, so no second timer is ever stacked for the same bound. When
590 # the block finishes (or is itself interrupted) teardown's token cancel recalls the helper's armed sleep and the
591 # worker is freed instead of staying occupied for the whole bound; no helper is armed at all when the block never
592 # parks or when $ms is 0.
593 sub with_timeout {
594 my $o = _arg_offset( $_[0] );
595 $o++ if $o == 0 && !defined $_[0];
596 my $ms = $_[$o];
597 croak 'with_timeout() requires a duration in milliseconds' unless defined $ms && $ms >= 0;
598 my $tok;
599 my $code;
600 if ( ref $_[ $o + 1 ] eq 'Acme::Parataxis::CancellationToken' ) {
601 $tok = $_[ $o + 1 ];
602 $code = $_[ $o + 2 ];
603 }
604 else {
605 $code = $_[ $o + 1 ];
606 }
607 croak 'with_timeout() requires a CODE ref' unless ref $code eq 'CODE';
608 croak 'with_timeout() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
609 @_ = ();
610 if ( $tok && $tok->cancelled ) { # the user already cancelled: fail without running the block
611 die Acme::Parataxis::Error::Cancelled->new;
612 }
613 state $have_token = do { require Acme::Parataxis::CancellationToken; 1; };
614 my $deadline = Acme::Parataxis::CancellationToken->new( kind => 'timeout' );
615 $tok = $deadline unless $tok; # no explicit token: the deadline alone governs the block
616  
617 # The absolute (ms-clock) bound this block's parks must respect, and a shallow copy of the spawning fiber's
618 # enclosing scopes to seed the child's stack with (marked as inherited so the child never arms a helper for a
619 # token it is not registered on - the owning ancestor enforces those).
620 my $scope_abs = $ms > 0 ? _now_ms() + $ms : undef;
621 my $scope = defined $scope_abs ? { abs => $scope_abs, tok => $deadline, own => 1, served => 0 } : undef;
622 my $inherited = do {
623 my $pfid = Acme::Parataxis->current_fid;
624 my $pf = $pfid >= 0 ? Acme::Parataxis->by_id($pfid) : undef;
625 my $stk = $pf && $pf->[F_DEADLINE_SCOPES] ? $pf->[F_DEADLINE_SCOPES] : undef;
626 $stk ?
627 [
628 map {
629 { %$_, own => 0 }
630 } @$stk
631 ] :
632 [];
633 };
634 my $child = fiber {
635 my $cf = Acme::Parataxis->by_id( Acme::Parataxis->current_fid );
636 $cf->[F_DEADLINE_SCOPES] = $scope ? [ @$inherited, $scope ] : $inherited;
637 $deadline->register;
638 $tok->register if $tok ne $deadline;
639 my $val;
640 my $err;
641 my $done_at;
642 try {
643 $val = $code->();
644 $done_at = defined $scope_abs ? _now_ms() : undef;
645 }
646 catch ($e) {
647 $err = $e
648 }
649  
650 # A deadline helper can fire late on a busy host (or the awaited result can land just after the bound
651 # without any park being re-entered). Record the completion time at the boundary so an overdue block still
652 # fails, rather than reporting success merely because its timer had not woken us yet. A bound already
653 # delivered at a park (and therefore catchable inside the block) is not overdue here: rethrowing would
654 # turn a handled timeout into a second, uncatchable one at with_timeout's own boundary.
655 my $overdue = $scope && defined $done_at && $done_at > $scope->{abs} && !$scope->{served};
656 $deadline->unregister;
657 $tok->unregister if $tok ne $deadline;
658 pop @{ $cf->[F_DEADLINE_SCOPES] } if defined $scope_abs; # leave the stack for any enclosing scope
659 die $err if $err; # the ::Timeout/::Cancelled throw (or any real error) unwinds out of the child
660 die Acme::Parataxis::Error::Timeout->new if $overdue;
661 return $val;
662 };
663  
664 # The block finished synchronously: the value (or an inline error, already rethrown by spawn) is final. Skipping
665 # the deadline also means a quick inlined block never pins its run.
666 if ( $child->is_done ) {
667 die $child->error if defined $child->error;
668 return $child->result;
669 }
670 my $rv;
671 my $ok = 1;
672 my $err;
673 try { $rv = $child->await } catch ($e) {
674 $ok = 0;
675 $err = $e
676 }
677 warn "with_timeout teardown: ok=$ok child_done=" .
678 $child->is_done .
679 " child_error=" .
680 ( defined $child->error ? ref( $child->error || '' ) || 'plain:' . $child->error : 'undef' ) .
681 " deadline_cancelled=" .
682 $deadline->cancelled .
683 " deadline_waiters=" .
684 $deadline->waiters .
685 " tok_waiters=" .
686 ( $tok->waiters // 'undef' ) . " err=" .
687 ( ref( $err || '' ) || 'plain:' . $err ) . "\n"
688 if $ENV{PARATAXIS_TRACE};
689  
690 # The child is final, so nothing else may keep waiting under these tokens. Even if *this* fiber was just
691 # cancelled out from under the await (an enclosing nursery/with_timeout interrupted us, or a user token fired):
692 # cancel the deadline now so a still-registered grandchild (a nested block, or the deadline helper _park armed
693 # for our bound) is itself interrupted instead of outliving its parent and running to completion. The recall
694 # now wakes the helper immediately, so its abandoned sleep job aborts in sub-millisecond time and no live work
695 # continues past its parent.
696 # A grandchild woken this way dies observer-gated (its parent's await had registered _wake_waiter on it), so it
697 # unwinds silently rather than killing the run.
698 $deadline->cancel;
699 $tok->cancel if $tok ne $deadline;
700 warn sprintf "with_timeout re-park branch: fid=%d child_done=%d err=%s\n", Acme::Parataxis->current_fid, $child->is_done,
701 ref( $err || '' ) || 'plain:' . $err
702 if $ENV{PARATAXIS_TRACE};
703 if ( !$ok && !$child->is_done ) {
704  
705 # We were cancelled out of the await while the child is still parked. It is interrupted and will die on its
706 # next resume. Re-park here, registered for the child's death, so the scheduler lets the child run its own
707 # unwind (unregistering from its tokens and running destructors) and reaps it before this frame unwinds and
708 # frees $child. Freeing the child mid-park no longer crashes (a C-level coroutine-lifecycle fix), so this
709 # branch is no longer load-bearing for safety - it is kept so an abandoned child dies by unwinding rather
710 # than being yanked. The interrupt marker on this fiber was consumed by the throwing await, so returning
711 # from this park (rather than throwing again) is certain. $nodl is set: this is a transient reap wait, not
712 # a user wait, so it must neither fail fast on an already-passed deadline nor arm a deadline helper.
713 my $fid = Acme::Parataxis->current_fid;
714 $child->on_ready( sub { Acme::Parataxis::_scheduler_enqueue_by_id($fid) } );
715 Acme::Parataxis::_park( 'fiber await', 1, undef, 1 );
716 $child->is_done; # reap the coroutine now that its death has been observed
717 }
718 die $err unless $ok;
719 return $rv;
720 }
721  
722 # Runs $code as a cancellation *scope* on the current fiber: while the block is active, every wait it enters is
723 # interruptible by one token - the scope token returned here - without the caller having to thread that token
724 # into each primitive. Unlike with_timeout, no child fiber is spawned; the block runs on this fiber, so interior
725 # awaits and parks suspend only the normal way. The token registers this fiber for the block's whole duration
726 # (a register/unregister pair, not a per-park one), so an outer cancel() both interrupts a wait parked now and
727 # stamps the fiber so the *next* wait entered inside the scope fails fast. Scopes stack LIFO in a per-fiber slot
728 # (_park reads the innermost one); nesting with_timeout or nursery tokens shares the park, and whichever token
729 # fires first ends the wait while teardown drops the others' registrations.
730 #
731 # Return convention (context aware): the scope token alone in scalar/void context, the token prepended to the
732 # block's value(s) in list context (my ($tok, @vals) = with_cancel sub { ... }). On failure the block's own
733 # error propagates unchanged (the real error wins over a concurrently arriving cancel); if the scope itself was
734 # cancelled by an outer token while the block ran to completion, Error::Cancelled (or Timeout for a deadline)
735 # is thrown at the scope boundary instead of swallowing the interrupt.
736 sub with_cancel {
737 my $o = _arg_offset( $_[0] );
738 my $code = $_[$o];
739 @_ = ();
740 croak 'with_cancel() requires a CODE ref' unless ref $code eq 'CODE';
741 croak 'with_cancel() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
742 state $have_token = do { require Acme::Parataxis::CancellationToken; 1 };
743 my $tok = Acme::Parataxis::CancellationToken->new( kind => 'cancel' );
744 my $fiber = Acme::Parataxis->by_id( Acme::Parataxis->current_fid );
745 push @{ $fiber->[F_CANCEL_SCOPES] }, $tok;
746 $tok->register; # block-wide: this fiber stays registered while the scope is open
747 my @val;
748 my $err;
749  
750 if (wantarray) {
751 try { @val = $code->($tok) } catch ($e) {
752 $err = $e
753 }
754 }
755 else {
756 try { $val[0] = $code->($tok) } catch ($e) {
757 $err = $e
758 }
759 }
760 $tok->unregister;
761 pop @{ $fiber->[F_CANCEL_SCOPES] };
762 if ($err) {
763  
764 # The block's own error wins: drop any interrupt still pending so it cannot resurface at an outer scope
765 # after this one has already reported the real failure.
766 $fiber->[F_INTERRUPT] = undef;
767 die $err;
768 }
769 if ( my $kind = $fiber->[F_INTERRUPT] ) {
770  
771 # The block returned normally but an outer token/deadline fired while it ran: consume the marker and
772 # convert it to the matching error so the cancellation is never silently swallowed at this boundary.
773 $fiber->[F_INTERRUPT] = undef;
774 die $kind eq 'timeout' ? Acme::Parataxis::Error::Timeout->new : Acme::Parataxis::Error::Cancelled->new;
775 }
776 return wantarray ? ( $tok, @val ) : $tok;
777 }
778  
779 # STM (software transactional memory). atomically() runs $code as one transaction on the calling fiber: reads are
780 # journaled, writes stay in a write set until the outermost atomically commits (validating
781 # every read first, re-running on conflict), and retry() parks the fiber until a TVar it
782 # read changes. The block may run many times - no irreversible side effects inside it.
783 # See Acme::Parataxis::TVar for the semantics and the SIDE EFFECTS warning.
784 sub atomically : prototype(&) {
785 my $o = _arg_offset( $_[0] );
786 my $code = $_[$o];
787 croak 'atomically() requires a CODE ref' unless ref $code eq 'CODE';
788 croak 'atomically() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
789 @_ = ();
790 require Acme::Parataxis::TVar;
791 return Acme::Parataxis::TVar::_atomically($code);
792 }
793  
794 # STM. Aborts the enclosing atomically block and re-runs it once a TVar the
795 # transaction has read changes; croaks anywhere else.
796 sub retry {
797 my $o = _arg_offset( $_[0] );
798 croak 'retry() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
799 @_ = ();
800 require Acme::Parataxis::TVar;
801 Acme::Parataxis::TVar::_retry();
802 }
803  
804 # Structured concurrency. $code runs in the calling fiber with an Acme::Parataxis::Nursery
805 # as its argument; every child spawned through $n->spawn is guaranteed to finish before nursery()
806 # returns, and the first child that dies cancels all of its siblings. Children never run inline
807 # into the block (Nursery::spawn parks each at birth), so a child failure always surfaces through
808 # the scheduler and is aggregated as Acme::Parataxis::Error::Nursery rather than thrown here.
809 # If $code itself dies, its children are cancelled and drained before its error is rethrown.
810 sub nursery {
811 my $o = _arg_offset( $_[0] );
812 $o++ if $o == 0 && !defined $_[0];
813 my $code = $_[$o];
814 croak 'nursery() requires a CODE ref' unless ref $code eq 'CODE';
815 croak 'nursery() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
816 @_ = ();
817 state $have_nursery = do { require Acme::Parataxis::Nursery; 1 };
818 my $nursery = Acme::Parataxis::Nursery->new;
819 my $rv;
820 my $ok = 1;
821 my $err;
822 try { $rv = $code->($nursery) } catch ($e) {
823 $ok = 0;
824 $err = $e
825 }
826  
827 # The block died: its children must not be orphaned, so cancel them and drain below.
828 $nursery->token->cancel unless $ok;
829  
830 # All-children-join. A child failure has already cancelled the rest via the observer,
831 # so the drain is fast; it unwinds every sibling before control returns to the parent.
832 my @failures = $nursery->_join;
833 die $err if !$ok; # the block's own error wins over its children's
834 if (@failures) {
835 die Acme::Parataxis::Error::Nursery->new( failures => \@failures );
836 }
837 return $rv;
838 }
839  
840 # Parallel map over a bounded fiber pool. $code runs once per item, each call in its own worker fiber (so a
841 # mapper may await, park, or use any primitive), with at most $opts{concurrency} workers in flight at once
842 # (default: one fiber per item). The caller parks while the pool works and the results come back in input order
843 # even when items finish out of order. A mapper that dies cancels the pool (the sibling workers stop at their
844 # next item boundary) and its error is rethrown once every worker has drained; later results are discarded.
845 # Must be called from inside a scheduled fiber, like nursery; an empty item list returns immediately; the
846 # concurrency option must be a positive integer.
847 sub pmap {
848 my $origin = _arg_offset( $_[0] );
849 my %opts;
850 my $i = $origin;
851 if ( ref $_[$i] eq 'HASH' ) {
852 %opts = %{ $_[ $i++ ] };
853 }
854 my $code = $_[ $i++ ];
855 my @items = @_[ $i .. $#_ ];
856 @_ = ();
857 croak 'pmap() requires a CODE ref' unless ref $code eq 'CODE';
858 croak 'pmap() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
859 return unless @items;
860 my $concurrency = $opts{concurrency} // scalar @items;
861 croak 'pmap() concurrency must be a positive integer' unless defined $concurrency && $concurrency =~ /\A[1-9]\d*\z/;
862 $concurrency = @items if $concurrency > @items;
863 require Acme::Parataxis::Channel;
864 require Acme::Parataxis::Sync::WaitGroup;
865 require Acme::Parataxis::CancellationToken;
866 my $jobs = Acme::Parataxis::Channel->new( capacity => $concurrency );
867 my $wg = Acme::Parataxis::Sync::WaitGroup->new;
868 my $tok = Acme::Parataxis::CancellationToken->new;
869 my ( @results, $first_error );
870  
871 # One unit for the feeder plus one per worker; the call parks below until they all land.
872 $wg->add( $concurrency + 1 );
873  
874 # Workers pull one job envelope per iteration. A job carries its input index so the results land back in
875 # input order; a job whose index is negative is the worker's STOP marker (one per worker, so every worker
876 # terminates even when mappers fail). A cancelled pool skips further work instead of mapping it but keeps
877 # draining to its STOP, so no worker is ever left parked on an empty channel by a sibling's failure.
878 for ( 1 .. $concurrency ) {
879 fiber {
880 while (1) {
881 my $job = $jobs->get;
882 my ( $i, $val ) = @$job;
883 last if $i < 0;
884 next if $tok->cancelled;
885 my $rv;
886 my $map_err;
887 try { $rv = $code->($val) } catch ($e) {
888 $map_err = $e
889 }
890 if ($map_err) {
891 $first_error //= $map_err; # the first mapper error wins
892 $tok->cancel; # fail fast: siblings stop at their next item boundary
893 last;
894 }
895 $results[$i] = $rv;
896 }
897 $wg->done;
898 };
899 }
900  
901 # The feeder delivers every envelope (the items, then the STOP markers) without ever parking on the
902 # channel: a full channel is drained by the workers, so try_put + yield makes progress and finishes.
903 fiber {
904 my $idx = 0;
905 my @envelopes = map { [ $idx++, $_ ] } @items;
906 push @envelopes, ( [-1] ) x $concurrency;
907 for my $env (@envelopes) {
908 while ( !$jobs->try_put($env) ) {
909 yield;
910 }
911 }
912 $wg->done;
913 };
914 my $ok = 1;
915 my $err;
916 try { $wg->wait } catch ($e) {
917 $ok = 0;
918 $err = $e
919 }
920 unless ($ok) {
921  
922 # The caller was interrupted while parked (an enclosing nursery/with_timeout): cancel the pool and
923 # drain it so no worker outlives the caller, then rethrow the caller's own error.
924 $tok->cancel;
925  
926 # A separate variable on purpose: $err is the caller's own error and is rethrown below.
927 try { $wg->wait } catch ($drain_err) {
928 }
929 die $err;
930 }
931 die $first_error if defined $first_error;
932 return wantarray ? @results : \@results;
933 }
934  
935 sub spawn {
936 my $class = $_[0];
937 my $code;
938 if ( ref $class eq 'CODE' ) {
939 $code = $class;
940 $class = __PACKAGE__;
941 }
942 else {
943 $code = $_[1];
944 }
945 @_ = ();
946  
947 # Trace propagation: Local slots created with inherit => 1 have their current value copied
948 # from the spawning fiber (the one resolving the spawn args - our caller, even after a nursery or actor
949 # birth park) into the child before the child's body first reads it. The seed is captured here, before
950 # spawn_fiber eagerly runs the body, and applied by a wrapper that runs in the child's own context, so
951 # the child's stash is seeded before any get in the body. The parent's stash is untouched: the child
952 # owns a shallow copy of each seeded value, so later set()s never cross either direction, exactly
953 # today's per-fiber isolation, only seeded. With no inherit slots (or no values set) nothing is captured
954 # and no wrapper is built, so the common spawn path is unchanged.
955 my @seed;
956 if (@INHERIT_LOCAL_IDS) {
957 my $fid = current_fid();
958 my $parent = $fid >= 0 ? Acme::Parataxis->by_id($fid) : undef;
959 if ($parent) {
960 my $stash = _fiber_locals($parent);
961 for my $id (@INHERIT_LOCAL_IDS) {
962 push @seed, [ $id, $stash->{$id} ] if exists $stash->{$id};
963 }
964 }
965 }
966 if (@seed) {
967 my $orig = $code;
968 $code = sub {
969 my $child = Acme::Parataxis->by_id( current_fid() );
970 if ($child) {
971 my $stash = _fiber_locals($child);
972 $stash->{ $_->[0] } = $_->[1] for @seed;
973 }
974 return $orig->(@_);
975 };
976 }
977 my $fiber = Acme::Parataxis::spawn_fiber( $code, $class );
978 if ( !ref $fiber ) {
979 croak defined $fiber &&
980 $fiber == -3 ?
981 'could not allocate a fiber: this platform has no MAP_NORESERVE and the process has hit its address-space / data-segment budget (raise RLIMIT_DATA or lower set_max_fibers)'
982 :
983 'could not allocate a fiber: the fiber table is full (destroy some fibers first, or raise the limit with set_max_fibers)';
984 }
985 my $status = $fiber->[F_LAST_STATUS];
986 if ( $status == 1 ) {
987 my $err = $fiber->[F_ERROR];
988 die $err if defined $err;
989 }
990 elsif ( $status == 0 ) {
991 $fiber->[F_PRIORITY] //= 0;
992 _enqueue($fiber);
993 }
994 return $fiber;
995 }
996  
997 sub _submit_job ( $type, $arg, $timeout ) {
998 my $rc = submit_c_job( $type, $arg, $timeout );
999 if ( $rc < 0 ) {
1000  
1001 # The 1024-slot job queue is full. Yield once so the scheduler can drain completed jobs, then retry.
1002 Acme::Parataxis->yield;
1003 $rc = submit_c_job( $type, $arg, $timeout );
1004 croak "job queue full: could not submit the job after a scheduler tick (submit_c_job returned $rc)" if $rc < 0;
1005 }
1006 return 0;
1007 }
1008  
1009 # -- event-loop driver. When an event loop is attached (attach_loop), await_read / await_write /
1010 # -- await_sleep stop submitting blocking OS-thread-pool jobs per filehandle/sleep and instead register watches
1011 # -- and timers on the loop; run() hands control to the loop whenever every fiber is parked. The public contract
1012 # -- is unchanged (readiness with the pool path's result values; timeout resumes -1; an enclosing with_timeout /
1013 # -- nursery interrupt still throws), only the backing mechanism differs.
1014 sub attach_loop {
1015 my $o = _arg_offset( $_[0] );
1016 my $thing = $_[$o];
1017 croak 'attach_loop() requires an event-loop object (Mojo::IOLoop, Mojo::Reactor or IO::Async::Loop)' unless defined $thing && ref $thing;
1018 @_ = ();
1019 croak 'attach_loop() cannot run while a run is already active' if $IS_RUNNING;
1020 require Acme::Parataxis::Driver;
1021 my $driver = Acme::Parataxis::Driver::wrap($thing);
1022 my $old = $DRIVER;
1023 $DRIVER = $driver;
1024 return $old;
1025 }
1026  
1027 # Detach the event-loop driver, returning it and unwinding every watch/timer it still held (loops attached to a
1028 # shared scheduler are racy at best, so a driver session is always short: attach, run, detach).
1029 sub detach_loop {
1030 my $o = _arg_offset( $_[0] );
1031 @_ = ();
1032 croak 'detach_loop() cannot run while a run is already active' if $IS_RUNNING;
1033 my $old = $DRIVER;
1034 $old->reset if $old;
1035 $DRIVER = undef;
1036 return $old;
1037 }
1038  
1039 # The currently attached driver (undef when the pool path is in effect). Mostly for diagnostics.
1040 sub loop {
1041 my $o = _arg_offset( $_[0] );
1042 @_ = ();
1043 return $DRIVER;
1044 }
1045  
1046 # -- transparent unblocking (CORE::GLOBAL overrides). Opt-in only: never
1047 # -- installed by default. enable_transparent_unblocking() makes sleep/read/sysread
1048 # -- cooperative inside scheduled fibers (sleep -> await_sleep, read/sysread framed
1049 # -- on await_read) and delegates to the raw builtin outside one, so synchronous
1050 # -- CPAN modules become cooperative once they are compiled after installation.
1051 # -- Full coverage table and caveats live in Acme::Parataxis::Compat.
1052 sub enable_transparent_unblocking {
1053 my $o = _arg_offset( $_[0] );
1054 @_ = ();
1055 require Acme::Parataxis::Compat;
1056 Acme::Parataxis::Compat->install;
1057 return 1;
1058 }
1059  
1060 sub disable_transparent_unblocking {
1061 my $o = _arg_offset( $_[0] );
1062 @_ = ();
1063 require Acme::Parataxis::Compat;
1064 Acme::Parataxis::Compat->disable;
1065 return 1;
1066 }
1067  
1068 sub transparent_unblocking {
1069 my $o = _arg_offset( $_[0] );
1070 @_ = ();
1071 return 0 unless $INC{'Acme/Parataxis/Compat.pm'};
1072 return Acme::Parataxis::Compat->installed ? 1 : 0;
1073 }
1074  
1075 sub _driver_sleep ( $driver, $ms ) {
1076 my $fid = Acme::Parataxis->current_fid;
1077 croak 'await_sleep() must be called from inside a scheduled fiber' if $fid < 0;
1078 my $fired = 0;
1079 my $id = $driver->timer( $ms, sub { $fired = 1; Acme::Parataxis::_scheduler_enqueue_by_id($fid) } );
1080 my $dereg = sub { $driver->cancel_timer($id) unless $fired };
1081 return _park( 'await_sleep', 1, $dereg );
1082 }
1083  
1084 # Register a read/write watch on the attached loop, arm the wait's own deadline timer, and park. Natural wake
1085 # returns 1; the wait's own deadline swallows its ::Timeout and returns -1 like the pool path does; an *enclosing*
1086 # with_timeout / nursery interrupt did not cancel our deadline token, so it propagates by dying.
1087 #
1088 my $WARNED_FD_SETSIZE = 0;
1089  
1090 sub _driver_wait ( $driver, $fh, $dir, $timeout, $reason ) {
1091 my $fid = Acme::Parataxis->current_fid;
1092 croak "$reason() must be called from inside a scheduled fiber" if $fid < 0;
1093  
1094 # A loop whose readiness comes from select() cannot name a descriptor at or past the platform's
1095 # FD_SETSIZE - 256 on NetBSD, 64 for winsock, 1024 on Linux - and the fd_set in that case belongs to
1096 # the loop library rather than to us, so there is nothing here to widen. Registering the watch anyway
1097 # would either never fire or corrupt the loop's own stack, so refuse it. The worker-pool path answers
1098 # the same way for the same reason (see worker_thread in Parataxis.c), and -1 is what a deadline
1099 # produces too, so a caller already knows how to read it. Worth saying out loud once, because the
1100 # limit is the platform's and a workload sized on another OS can sail past it unnoticed.
1101 #
1102 # fileno croaks on something that is not a handle at all, and whatever the driver says about that is a
1103 # better message than anything invented here, so an answer of undef means "no descriptor to check" and
1104 # the handle goes on to the driver as it always did. An in-memory file answers -1, which is under any
1105 # ceiling, and needs no watch anyway.
1106 my $fd;
1107 try { $fd = fileno $fh } catch ($e) {
1108 } # not a handle at all: no descriptor to check
1109 if ( defined $fd && $fd >= Acme::Parataxis::fd_setsize() ) {
1110 warn "Acme::Parataxis: $reason() refused: descriptor $fd is at or past this platform's FD_SETSIZE (" .
1111 Acme::Parataxis::fd_setsize() .
1112 "), which a select()-based readiness stack cannot name. Further refusals will not be reported.\n"
1113 unless $WARNED_FD_SETSIZE++;
1114 return -1;
1115 }
1116 my $wake = sub { Acme::Parataxis::_scheduler_enqueue_by_id($fid) };
1117 if ( $dir eq 'read' ) { $driver->watch_read( $fh, $wake ) }
1118 else { $driver->watch_write( $fh, $wake ) }
1119 my $deadline;
1120 my $timer_id;
1121 $timeout //= 5000; # match the worker-pool default, which also maps 0/negative to 5000
1122 $timeout = 5000 if $timeout <= 0;
1123  
1124 if ( $timeout > 0 ) {
1125 my $have_ct = do { require Acme::Parataxis::CancellationToken; 1 };
1126 $deadline = Acme::Parataxis::CancellationToken->new( kind => 'timeout' ) if $have_ct;
1127 $deadline->register;
1128 $timer_id = $driver->timer( $timeout, sub { $deadline->cancel } );
1129 }
1130 my $out = 1;
1131 my $dying;
1132 my $dereg = sub {
1133 $driver->unwatch($fh);
1134 $driver->cancel_timer($timer_id) if defined $timer_id;
1135 $deadline->unregister if defined $deadline;
1136 };
1137 my $ok = 1;
1138 my $err;
1139 try { Acme::Parataxis::_park( $reason, 1, $dereg ) }
1140 catch ($e) { $ok = 0; $err = $e }
1141 finally { $dereg->() } # idempotent: on an interrupt _park already ran it, on a natural wake this is the cleanup
1142 if ( !$ok ) {
1143 if ( defined $deadline && $deadline->cancelled && ref($err) && $err->isa('Acme::Parataxis::Error::Timeout') ) {
1144 $out = -1; # this wait's own deadline expired; the pool path resumes (not throws) on timeout
1145 }
1146 else { $dying = $err }
1147 }
1148 $deadline->unregister if defined $deadline;
1149 $deadline->cancel if defined $deadline;
1150 die $dying if defined $dying;
1151 return $out;
1152 }
1153  
1154 # Acme::Parataxis->advance($ms): inside a virtual run, jump the virtual clock forward $ms and wake everything that
1155 # fires as of the new time. A nudge, not a wait: the calling fiber keeps running (woken fibers run on the next
1156 # scheduler pass), so the "advance, then yield/return, then observe" test choreography in the docs is the idiom.
1157 # Returns the new virtual time in ms. Croaks outside a virtual run - the wall clock cannot be wound forward.
1158 sub advance {
1159 my $o = _arg_offset( $_[0] );
1160 my $ms = $_[$o] // 0;
1161 @_ = ();
1162 croak 'advance() only makes sense inside run( virtual => 1, ... )' unless defined $VIRTUAL_CLOCK;
1163 croak 'advance() requires a non-negative number of milliseconds' if $ms < 0;
1164 $VIRTUAL_CLOCK += $ms;
1165 _fire_virtual($VIRTUAL_CLOCK);
1166 return $VIRTUAL_CLOCK;
1167 }
1168  
1169 sub await_sleep {
1170 my $o = _arg_offset( $_[0] );
1171 $o++ if $o == 0 && !defined $_[0];
1172 my $ms = $_[$o] // 0;
1173 @_ = ();
1174 if ( defined $VIRTUAL_CLOCK && $ms > 0 ) {
1175 my $fid = Acme::Parataxis->current_fid;
1176 croak 'await_sleep() must be called from inside a scheduled fiber' if $fid < 0;
1177 _arm_virtual_timer( $fid, $ms );
1178 return _park('await_sleep');
1179 }
1180 if ( $DRIVER && $ms > 0 ) {
1181 return _driver_sleep( $DRIVER, $ms );
1182 }
1183 _submit_job( 0, $ms, 0 );
1184 return _park('await_sleep');
1185 }
1186  
1187 sub await_core_id {
1188 @_ = ();
1189 _submit_job( 1, 0, 0 );
1190 return _park('await_core_id');
1191 }
1192  
1193 sub await_read {
1194 my $o = _arg_offset( $_[0] );
1195 $o++ if $o == 0 && !defined $_[0];
1196 my $fh = $_[$o];
1197 my $timeout = $_[ $o + 1 ] // 5000;
1198 @_ = ();
1199 my $fileno = fileno($fh);
1200 die 'Not a valid filehandle' unless defined $fileno;
1201 if ($DRIVER) {
1202 return _driver_wait( $DRIVER, $fh, 'read', $timeout, 'await_read' );
1203 }
1204 my $handle = $^O eq 'MSWin32' ? win32_get_osfhandle($fileno) : $fileno;
1205 _submit_job( 2, $handle, $timeout );
1206 return _park('await_read');
1207 }
1208  
1209 sub await_write {
1210 my $o = _arg_offset( $_[0] );
1211 $o++ if $o == 0 && !defined $_[0];
1212 my $fh = $_[$o];
1213 my $timeout = $_[ $o + 1 ] // 5000;
1214 @_ = ();
1215 my $fileno = fileno($fh);
1216 die 'Not a valid filehandle' unless defined $fileno;
1217 if ($DRIVER) {
1218 return _driver_wait( $DRIVER, $fh, 'write', $timeout, 'await_write' );
1219 }
1220 my $handle = $^O eq 'MSWin32' ? win32_get_osfhandle($fileno) : $fileno;
1221 _submit_job( 3, $handle, $timeout );
1222 return _park('await_write');
1223 }
1224  
1225 sub maybe_yield {
1226 @_ = ();
1227 my $result = Acme::Parataxis::_maybe_yield();
1228 return unless defined $result;
1229 return wantarray ? @$result : $result->[-1];
1230 }
1231  
1232 sub set_preempt_threshold {
1233 my $o = _arg_offset( $_[0] );
1234 croak 'set_preempt_threshold() expects a threshold value' unless @_ > $o;
1235 Acme::Parataxis::_set_preempt_threshold( $_[$o] // 0 );
1236 }
1237 sub tid { get_os_thread_id_export() }
1238 sub current_fid { get_current_parataxis_id() }
1239 sub root { state $root //= Acme::Parataxis::Root->new() }
1240 sub max_threads () { Acme::Parataxis::get_max_thread_pool_size() }
1241 sub max_fibers () { Acme::Parataxis::get_max_fibers() }
1242  
1243 # The highest descriptor number an fd_set can name on this platform: 1024 on Linux, macOS and FreeBSD,
1244 # 256 on NetBSD, 64 for winsock. It is a property of the C library rather than a constant, and it bounds
1245 # the descriptor NUMBER, not the number of handles - so size a workload of N watched sockets against it
1246 # and not against N. Read it from C because nothing in perl can: `getconf FD_SETSIZE` is not a valid
1247 # symbol and answers 20, and Fcntl::FD_SETSIZE() dies at runtime.
1248 sub fd_setsize () { Acme::Parataxis::get_fd_setsize() }
1249  
1250 # Scheduler internals
1251 sub _scheduler_enqueue_by_id ($fid) {
1252 return if $SCHEDULER_QUEUED{$fid};
1253 if ( my $fiber = Acme::Parataxis->by_id($fid) ) {
1254 _enqueue($fiber);
1255 }
1256 }
1257  
1258 sub poll_io {
1259 my @ready;
1260 while (1) {
1261 my $job_idx = check_for_completion();
1262 last if $job_idx == -1;
1263 my $fid = get_job_coro_id($job_idx);
1264 my $res = get_job_result($job_idx);
1265 push @ready, [ $fid, $res ];
1266 free_job_slot($job_idx);
1267 }
1268 return @ready;
1269 }
1270  
1271 sub _handle_run ( $fiber, $status ) {
1272 if ( $status == 1 ) {
1273 Acme::Parataxis::_mark_done($fiber);
1274 my $err = $fiber->[F_ERROR];
1275  
1276 # A scheduled fiber that dies unwinds the whole run *unless* it has an observer (an awaiting parent, an
1277 # on_ready callback). With an observer the error is deliberately left for the observer to rethrow at the
1278 # await/call site, which lets a cancelled wait surface to its own awaiter without killing the block.
1279 die $err if defined $err && !@{ $fiber->[F_CALLBACKS] || [] };
1280 $fiber->[F_CALLBACKS] = []; # one-shot, already fired by set_result/set_error; dropping the refs lets
1281 return 1; # a callback that captured the fiber (e.g. a nursery observer) cycle out
1282 }
1283 if ( $status == 0 ) {
1284 $fiber->[F_PRIORITY] //= 0;
1285 _enqueue($fiber);
1286 }
1287 return $status;
1288 }
1289  
1290 sub run (@raw) {
1291 my $o = _arg_offset( $raw[0] );
1292 my @a = @raw[ $o .. $#raw ];
1293 my ( $code, $virtual, $on_shutdown );
1294 if ( @a == 1 && ref $a[0] eq 'CODE' ) {
1295 $code = $a[0];
1296 }
1297 elsif ( @a >= 2 && @a % 2 == 0 ) {
1298 my %opt = @a;
1299 my @bad = grep { $_ ne 'code' && $_ ne 'virtual' && $_ ne 'on_shutdown' } keys %opt;
1300 croak 'run() unknown option(s): ' . join( ', ', @bad ) if @bad;
1301 croak 'run() needs the code option' unless ref $opt{code} eq 'CODE';
1302 $code = $opt{code};
1303 $virtual = $opt{virtual} ? 1 : 0;
1304 $on_shutdown = $opt{on_shutdown};
1305 if ( defined $on_shutdown && ref $on_shutdown ) {
1306 require Acme::Parataxis::CancellationToken;
1307 my $is_tok = 0;
1308 if ( ref $on_shutdown ne 'CODE' ) {
1309 try { $is_tok = $on_shutdown->isa('Acme::Parataxis::CancellationToken') || 0 } catch ($e) {
1310 $is_tok = 0
1311 }
1312 }
1313 croak 'run() on_shutdown must be a true value, a code ref, or a CancellationToken' unless ref $on_shutdown eq 'CODE' || $is_tok;
1314 }
1315 }
1316 croak 'run() needs a CODE ref: run( $code ), or run( code => $code, ... )' unless ref $code eq 'CODE';
1317 if ($IS_RUNNING) {
1318  
1319 # Nested run/async inside a shared global scheduler. Queue a fresh fiber for the block and park the current
1320 # fiber until it completes. The on_shutdown option is only for the outermost run: an inner run must not
1321 # touch %SIG (the global handler table belongs to the top-level process lifecycle).
1322 my $fiber = __PACKAGE__->new( code => $code );
1323 _enqueue($fiber);
1324 return $fiber->await;
1325 }
1326 @SCHEDULER_QUEUE = ();
1327 %SCHEDULER_QUEUED = ();
1328 $IS_RUNNING = 1;
1329  
1330 # run( virtual => 1 ) turns on the virtual clock for the whole run. Everything the scheduler waits
1331 # on (and every mock_time read) then rides $VIRTUAL_CLOCK, and the idle path fast-forwards it instead of
1332 # sleeping, so timeouts can be exercised in microseconds. Saved/restored so a non-virtual run after a virtual
1333 # one (or vice versa) is exactly wall-clock behavior again.
1334 my $saved_clock = $VIRTUAL_CLOCK;
1335 if ($virtual) {
1336 $VIRTUAL_CLOCK = 0;
1337 %VIRTUAL_DEADLINES = ();
1338 @VIRTUAL_TIMERS = ();
1339 }
1340  
1341 # Snapshot the fibers that were already alive before this run. A fiber parked by a *previous* deadlocked run
1342 # can never be woken again, but the C table still counts it as live; the deadlock detector below must only
1343 # consider fibers that actually belong to this run, otherwise any run after a deadlock would be misread as
1344 # another deadlock. (Leaked fibers keep their C slot occupied, so their fids cannot be reused in between.)
1345 my %PRESET_FIBERS = map { $_ => 1 } _live_fiber_ids();
1346 my $main_fiber = __PACKAGE__->new( code => $code );
1347  
1348 # on_shutdown => opts the OUTERMOST run into installing SIGINT/SIGTERM handlers for the run's lifetime
1349 # (the previous handlers are restored when it ends). The first signal - or, when the option is a pre-made
1350 # CancellationToken, its cancel() from anywhere - fires the shutdown token and interrupts every fiber this run
1351 # created (the run's root fiber included), so they unwind, run their own cleanup (defers/DESTROYs), and the
1352 # loop drains them; run() then returns the conventional interrupted status (130 for INT, 143 for TERM) instead
1353 # of rethrowing their Error::Cancelled. A second signal restores the previous handlers and re-raises the signal
1354 # so the default disposition kills the process - the handler never blocks a second Ctrl+C. A code ref passed as
1355 # the option receives the token (already fired) so a process can flush logs or stop servers before run() reports
1356 # the status; passing a CancellationToken means the caller owns the token and can begin the shutdown
1357 # programmatically (a health port, a parent process, a test) as well as from a signal.
1358 my ( $shutdown_token, $shutdown_status, $shutdown_fired, $shutdown_cb );
1359 my ( $old_int, $old_term );
1360 my ( $fire, $sig_pending );
1361 my $interrupt_run_fibers = sub {
1362 for my $fid ( _live_fiber_ids() ) {
1363 next if $PRESET_FIBERS{$fid};
1364 my $fiber = __PACKAGE__->by_id($fid);
1365 _interrupt( $fid, 'cancel' ) if $fiber && !$fiber->is_done;
1366 }
1367 };
1368 if ($on_shutdown) {
1369 require Acme::Parataxis::CancellationToken;
1370 my $is_shutdown_token = 0;
1371 if ( ref $on_shutdown ne 'CODE' ) {
1372 try { $is_shutdown_token = $on_shutdown->isa('Acme::Parataxis::CancellationToken') || 0 } catch ($e) {
1373 $is_shutdown_token = 0
1374 }
1375 }
1376 $shutdown_token = $is_shutdown_token ? $on_shutdown : Acme::Parataxis::CancellationToken->new;
1377 $shutdown_cb = ref $on_shutdown eq 'CODE' ? $on_shutdown : undef;
1378 $shutdown_status = 130;
1379 $old_int = $SIG{INT};
1380 $old_term = $SIG{TERM};
1381 $fire = sub ($sig) {
1382 if ($shutdown_fired) { # second signal: stop catching it; the restored default kills the process
1383 $SIG{INT} = $old_int;
1384 $SIG{TERM} = $old_term;
1385 kill $sig => $$;
1386 return;
1387 }
1388 $shutdown_fired = 1;
1389 $shutdown_status = $sig eq 'TERM' ? 143 : 130;
1390 $shutdown_token->cancel;
1391 $interrupt_run_fibers->();
1392 };
1393  
1394 # The async handlers only record a pending signal. $fire - the token cancel, the run-fiber interrupt sweep,
1395 # the scheduler queueing - runs at run()'s own checkpoint atop the scheduler loop instead: from inside the
1396 # handler it would execute at an arbitrary point mid-iteration, possibly while the loop is draining jobs /
1397 # resuming @ready fibers / mutating @SCHEDULER_QUEUE, where its effects on those fibers can be lost and the
1398 # run stalls until an outstanding C job finishes on its own schedule (a sleeping fiber rides out its full
1399 # deadline, so a Ctrl-C or kill can fire tens of seconds late). The checkpoint is the same place the
1400 # programmatic token-cancel sweep runs, which is what keeps the two paths deterministic under load.
1401 $SIG{INT} = sub { $sig_pending ||= 'INT' };
1402 $SIG{TERM} = sub { $sig_pending ||= 'TERM' };
1403 }
1404 _enqueue($main_fiber);
1405 my $run_ok = 1;
1406 my $run_failure;
1407 try {
1408 while ($IS_RUNNING) {
1409  
1410 # Process a deferred signal at (and only at) this checkpoint - the one place in the loop
1411 # where no drain/@ready/@SCHEDULER_QUEUE manipulation is in flight, so the shutdown sweep below
1412 # cannot race the fibers it interrupts. See the comment at the $SIG{...} installs above.
1413 if ($sig_pending) {
1414 ( my $sig, $sig_pending ) = ( $sig_pending, undef );
1415 $fire->($sig);
1416 }
1417  
1418 # A shutdown token cancelled from inside the run (not just by a signal handler) begins the
1419 # graceful drain too. The token's own cancel() already interrupted whatever was registered against it;
1420 # this pass interrupts the rest of the run's fibers so every fiber winds down together.
1421 if ( $on_shutdown && !$shutdown_fired && $shutdown_token->cancelled ) {
1422 $shutdown_fired = 1;
1423 $interrupt_run_fibers->();
1424 }
1425 my @ready;
1426 if ( get_outstanding_jobs() ) {
1427 my $out = [];
1428 drain_jobs($out);
1429 @ready = @$out;
1430 }
1431 for my $ready (@ready) {
1432 my ( $fid, $res ) = @$ready;
1433 my $fiber = __PACKAGE__->by_id($fid);
1434 next unless $fiber;
1435 _resume_hooks($fiber);
1436 my $yield_val = $fiber->call($res);
1437 if ( defined $fiber && !$fiber->is_done ) {
1438 _enqueue($fiber) unless defined $yield_val && $yield_val eq 'WAITING';
1439 }
1440 }
1441 if (@SCHEDULER_QUEUE) {
1442 my @work = @SCHEDULER_QUEUE;
1443 @SCHEDULER_QUEUE = ();
1444 %SCHEDULER_QUEUED = ();
1445 for my $current (@work) {
1446 next unless $current;
1447 _resume_hooks($current);
1448 _handle_run( $current, run_fiber_checked( $current->fid, undef ) );
1449 }
1450 }
1451 my $active_count = get_live_fiber_count();
1452 if ( $IS_RUNNING && !@SCHEDULER_QUEUE && !@ready ) {
1453 if ( get_outstanding_jobs() ) {
1454 $DRIVER->poll_ready() if $DRIVER; # fire any already-live driver events, best effort
1455 usleep(1000); # Wait for background jobs to finish
1456 }
1457 elsif ( $DRIVER && $DRIVER->pending ) {
1458  
1459 # Every fiber is parked and the attached event loop still has live watches/timers: hand the
1460 # processor to the loop. Its readiness callbacks only ever enqueue fibers (_scheduler_enqueue_by_id),
1461 # never run them, so no re-entrancy into the scheduler is possible; the outer loop runs them back
1462 # on the next iteration.
1463 $DRIVER->drive();
1464 }
1465 else {
1466 # Virtual clock: the scheduler has no runnable work and no real jobs (real I/O never
1467 # reaches here), but fibers are parked on virtual timers. Instead of sleeping on the wall clock
1468 # (or declaring a deadlock), wind the virtual clock up to the earliest outstanding deadline and
1469 # fire anything due, then re-loop to run the woken fibers. The clock never moves while any fiber
1470 # is runnable or any real job is in flight, so only real waiting is accelerated.
1471 if ( defined $VIRTUAL_CLOCK && @VIRTUAL_TIMERS ) {
1472 my $earliest = $VIRTUAL_TIMERS[0][0];
1473 $VIRTUAL_CLOCK = $earliest if $VIRTUAL_CLOCK < $earliest;
1474 if ( _fire_virtual($VIRTUAL_CLOCK) ) {next}
1475 }
1476 if ( $active_count > scalar( keys %PRESET_FIBERS ) ) {
1477  
1478 # A live fiber is stuck with nothing to do and no one to wake it and no timer to fire: this
1479 # run is deadlocked. Leave the scheduler in a clean, reusable state: stop this run, clear the
1480 # queues, and do NOT treat it as a nested inner run (that path requires an enclosing scheduled
1481 # fiber). Preset (leaked) fibers from a previously deadlocked run are excluded from the count
1482 # above so they cannot make a later healthy run look deadlocked; they stay parked forever in
1483 # the C table but are harmless because the count below only ever triggers on fibers created
1484 # by this run.
1485 $IS_RUNNING = 0;
1486 @SCHEDULER_QUEUE = ();
1487 %SCHEDULER_QUEUED = ();
1488 my $rows = _fiber_snapshot();
1489 my @mine = grep { !$PRESET_FIBERS{ $_->{fid} } } @$rows;
1490 my $body = '';
1491 for my $r (@mine) {
1492 $body .= sprintf(
1493 " fiber #%-3d %-8s %-17s %s\n",
1494 $r->{fid}, $r->{state},
1495 $r->{reason} ? $r->{reason}[0] : '-',
1496 $r->{reason} ? sprintf( '%s:%d', @{ $r->{reason} }[ 1, 2 ] ) : '-'
1497 );
1498 for my $bt ( @{ $r->{reason}[3] // [] } ) {
1499 $body .= sprintf( " at %s:%d %s\n", @$bt[ 1, 2, 3 ] );
1500 }
1501 }
1502 $body .= " (no live fibers from this run)\n" unless @mine;
1503 my $leaked = @$rows - @mine;
1504 $body .= " ($leaked previously leaked fiber(s) from an older deadlocked run, omitted)\n" if $leaked;
1505  
1506 # Tear the deadlocked run's own parked fibers out of the depth registry -- destroy_coro-equivalent
1507 # purging at the moment this run's torn-down stack is detected. They are parked and nothing will
1508 # ever resume them (this run is ending and the records stay leaked so their fids cannot be reused),
1509 # so their parked claims must leave now: left in place they pin CvDEPTH above depths no live frame
1510 # occupies, and every later park of the same CV enters one level high ("poisoned depth"). With the
1511 # claims gone and the frames unwound (si_cxix = -1), the next swap's Pass 1c releases any pinned level.
1512 para_cvreg_purge_fiber($_) for map { $_->{fid} } @mine;
1513 die 'FATAL: deadlock detected: no runnable work and no outstanding jobs, but ' .
1514 $active_count .
1515 " live fiber(s). Parked in this run:\n" .
1516 $body;
1517 }
1518 $IS_RUNNING = 0 if defined $main_fiber && $main_fiber->is_done;
1519 }
1520 }
1521 }
1522  
1523 # No success marker is needed here, and deliberately so. This used to be an eval whose return
1524 # value was read as the success flag, so a *clean* exit whose last expression happened to be
1525 # false produced a defined-but-empty $@ that was then rethrown -- every normal run ended in
1526 # die '' ("Died at ..."). The catch below is the only thing that can set $run_failure.
1527 }
1528 catch ($e) { $run_ok = 0; $run_failure = $e }
1529  
1530 # An abort (an unobserved fiber death unwound the whole loop) ends the run with its remaining
1531 # fibers parked, abandoned exactly like a deadlocked run's. Nothing resumes them now, so purge
1532 # their parked claims the same way the deadlock branch does, before the next run can re-park in
1533 # a shared CV ("poisoned depth"). The fiber records stay leaked, so only this run's OWN fibers
1534 # are touched -- fibers from an older deadlocked run were already purged when their run died.
1535 # A clean stop must NOT purge: its parked leftovers are still resumable (their own jobs/waits will
1536 # fire), and the next run drains them -- tearing them down here would leak unusable records that
1537 # pin get_live_fiber_count() forever, which the cross-run stress tests assert against.
1538 if ( !$run_ok ) {
1539 para_cvreg_purge_fiber($_) for grep { !$PRESET_FIBERS{$_} } _live_fiber_ids();
1540 }
1541 $IS_RUNNING = 0; # always leave the scheduler reusable, even when a fiber blew up
1542 $DRIVER->reset if $DRIVER; # unwind every watch/timer this run left on the attached loop
1543 if ($on_shutdown) { # the handler table is global: restore it no matter how the run ended
1544 $SIG{INT} = $old_int;
1545 $SIG{TERM} = $old_term;
1546 }
1547 %VIRTUAL_DEADLINES = ();
1548 @VIRTUAL_TIMERS = (); # a virtual run's timers die with the run
1549 $VIRTUAL_CLOCK = $saved_clock; # whatever the next run does, the wall clock is the default
1550 if ( $on_shutdown && $shutdown_fired ) {
1551 $shutdown_cb->($shutdown_token) if $shutdown_cb;
1552  
1553 # The shutdown interrupt makes the run's fibers die with Error::Cancelled, which is the expected, drained
1554 # outcome of a signal, not a failure: run() reports the conventional interrupted status instead of
1555 # rethrowing it. Any other error still propagates.
1556 if ( defined $run_failure && ref $run_failure && $run_failure->isa('Acme::Parataxis::Error::Cancelled') ) {
1557 $run_failure = undef;
1558 }
1559 die $run_failure if defined $run_failure;
1560 return $shutdown_status;
1561 }
1562 die $run_failure if defined $run_failure; # rethrow a fiber's uncaught error only after cleaning up
1563 return $main_fiber->[F_RESULT];
1564 }
1565 sub stop () { $IS_RUNNING = 0 }
1566  
1567 sub new ( $class, %args ) {
1568 my $self = bless [ $args{code}, 0, undef, undef, undef, 0, [], undef, undef, 0, undef, undef, undef, [] ], $class;
1569 my $fid = Acme::Parataxis::create_fiber( $args{code}, $self );
1570 croak 'could not allocate a fiber: ' .
1571 ( $fid == -3 ?
1572 'this platform has no MAP_NORESERVE and the process has hit its address-space / data-segment budget (raise RLIMIT_DATA or lower set_max_fibers)'
1573 :
1574 'the fiber table is full (destroy some fibers first, or raise the limit with set_max_fibers)' )
1575 if $fid < 0;
1576 $self->[F_FID] = $fid;
1577 return $self;
1578 }
1579 sub fid ($self) { $self->[F_FID] }
1580 sub code ($self) { $self->[F_CODE] }
1581 sub error ($self) { $self->[F_ERROR] }
1582  
1583 # Higher numbers run first; ties are broken in the FIFO order they were enqueued in. The default is 0.
1584 sub priority {
1585 my $self = shift;
1586 my $prio = $self->[F_PRIORITY] // 0;
1587 return $prio unless @_;
1588 my $n = shift;
1589 $self->[F_PRIORITY] = $n;
1590 my $fid = $self->[F_FID];
1591 if ( delete $SCHEDULER_QUEUED{$fid} ) {
1592 @SCHEDULER_QUEUE = grep { $_->[F_FID] != $fid } @SCHEDULER_QUEUE;
1593 _enqueue($self);
1594 }
1595 return $n;
1596 }
1597 sub is_ready ($self) { $self->[F_IS_READY] }
1598  
1599 sub set_result {
1600 my ( $self, $val ) = @_;
1601 return if $self->[F_IS_READY];
1602 $self->[F_RESULT] = $val;
1603 $self->[F_IS_READY] = 1;
1604 $_->($self) for @{ $self->[F_CALLBACKS] };
1605 }
1606  
1607 sub set_error ( $self, $err ) {
1608 return if $self->[F_IS_READY];
1609 $self->[F_ERROR] = $err;
1610 $self->[F_IS_READY] = 1;
1611 $_->($self) for @{ $self->[F_CALLBACKS] };
1612 }
1613  
1614 sub _result ($self) {
1615 croak 'Future not ready' unless $self->[F_IS_READY];
1616 return $self->[F_RESULT];
1617 }
1618 sub result ($self) { return _result($self) }
1619  
1620 sub _clear_result ($self) {
1621 $self->[F_RESULT] = undef;
1622 $self->[F_ERROR] = undef;
1623 }
1624  
1625 sub _mark_done ($self) {
1626 return if $self->[F_IS_DONE];
1627 $self->[F_IS_DONE] = 1;
1628 if ( defined $self->[F_FID] && $self->[F_FID] >= 0 ) {
1629 delete $PARKED{ $self->[F_FID] };
1630 delete $PARK_REGS{ $self->[F_FID] };
1631 _recall_virtual_timer( $self->[F_FID] ); # a finished fiber must not leave a virtual timer behind
1632 delete $FIBER_LOCALS{ refaddr($self) };
1633 $self->[F_FID] = -1;
1634 }
1635 }
1636  
1637 sub call ( $self, @args ) {
1638 croak 'Cannot call a finished fiber' if $self->[F_IS_DONE];
1639 my $rv = Acme::Parataxis::coro_call( $self->[F_FID], \@args );
1640 return unless defined $self;
1641 if ( $self->is_done ) {
1642 my $err = $self->[F_ERROR];
1643  
1644 # Observer-gated rethrow, like _handle_run: a fiber that died while watched (an awaiting parent or an
1645 # on_ready callback) keeps its error for the observer to rethrow at its await/call site instead of
1646 # killing the run loop. This is the wake-by-job-completion path (@ready), whose deaths are the one
1647 # observer-gated hole left open: a child that dies right after its own sleep job must not kill run().
1648 die $err if defined $err && !@{ $self->[F_CALLBACKS] || [] };
1649 }
1650 return unless defined $rv;
1651 return ( ref $rv eq 'ARRAY' ) ? ( wantarray ? @$rv : $rv->[-1] ) : $rv;
1652 }
1653  
1654 sub transfer ( $self, @args ) {
1655 croak 'Cannot transfer to a finished fiber' if $self->is_done;
1656 my $rv = Acme::Parataxis::coro_transfer( $self->[F_FID], \@args );
1657 if ( $self->is_done ) {
1658 my $err = $self->[F_ERROR];
1659 die $err if defined $err;
1660 }
1661 return unless defined $rv;
1662 return ( ref $rv eq 'ARRAY' ) ? ( wantarray ? @$rv : $rv->[-1] ) : $rv;
1663 }
1664  
1665 sub is_done ($self) {
1666 if ( $self->[F_IS_DONE] ) {
1667 delete $FIBER_LOCALS{ refaddr($self) };
1668 return 1;
1669 }
1670 if ( defined $self->[F_FID] && $self->[F_FID] >= 0 && Acme::Parataxis::is_finished( $self->[F_FID] ) ) {
1671 $self->[F_IS_DONE] = 1;
1672 my $old_fid = $self->[F_FID];
1673 delete $PARKED{$old_fid};
1674 delete $PARK_REGS{$old_fid};
1675 delete $FIBER_LOCALS{ refaddr($self) };
1676 $self->[F_FID] = -1;
1677 Acme::Parataxis::destroy_coro($old_fid);
1678 return 1;
1679 }
1680 return 0;
1681 }
1682 sub wait_reason ($self) { $self->[F_WAIT_REASON] } # [reason, file, line, backtrace] while parked, undef otherwise
1683  
1684 sub wait ($self) {
1685 if ( !$self->is_done && Acme::Parataxis->current_fid < 0 ) {
1686 croak 'wait() must be called from inside the scheduler, or the fiber must already be done';
1687 }
1688 my $fid = Acme::Parataxis->current_fid;
1689 my $waiter = $fid >= 0 ? Acme::Parataxis->by_id($fid) : undef; # the fiber doing the busy-wait
1690 $waiter->[F_WAIT_REASON] = [ 'fiber wait', (caller)[ 1, 2 ] ] if $waiter;
1691 Acme::Parataxis->yield('WAITING_FOR_CHILD') until $self->is_done;
1692 $waiter->[F_WAIT_REASON] = undef if $waiter;
1693 return _result($self);
1694 }
1695  
1696 sub on_ready ( $self, $cb ) {
1697 if ( $self->[F_IS_READY] ) { $cb->($self) }
1698 else { push @{ $self->[F_CALLBACKS] }, $cb }
1699 }
1700  
1701 sub await ($target) {
1702  
1703 # await() is exported as a plain function; await($fut) must delegate to the await-capable receiver's own
1704 # method (e.g. Future), while fiber objects (which ARE Acme::Parataxis) keep the arrayref-slot path.
1705 # The signature keeps @_ unreified here: await() parks and is resumed on this same pad.
1706 if ( builtin::blessed($target) && $target->can('await') && !$target->isa(__PACKAGE__) ) {
1707 return $target->await;
1708 }
1709 my $self = $target;
1710 my $ready = $self->[F_IS_READY];
1711 if ( !$ready ) {
1712 croak 'await() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
1713 my $fid = Acme::Parataxis->current_fid;
1714 $self->[F_WAITER] = $fid;
1715 $self->on_ready( \&_wake_waiter );
1716 _park( 'fiber await', 1, sub { $self->[F_WAITER] = undef if defined $self->[F_WAITER] && $self->[F_WAITER] == $fid } );
1717 $ready = $self->[F_IS_READY];
1718 }
1719 croak 'Future not ready' unless $ready;
1720 delete $FIBER_LOCALS{ refaddr($self) }; # the fiber is done now; its locals die with it (no-op for Futures)
1721 die $self->[F_ERROR] if defined $self->[F_ERROR];
1722 $self->[F_RESULT];
1723 }
1724  
1725 sub _wake_waiter ($self) {
1726 return unless defined $self->[F_WAITER];
1727 Acme::Parataxis::_scheduler_enqueue_by_id( $self->[F_WAITER] );
1728 $self->[F_WAITER] = undef;
1729 }
1730  
1731 sub DESTROY($self) {
1732 return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
1733 delete $FIBER_LOCALS{ refaddr($self) };
1734 if ( defined $self->[F_FID] && $self->[F_FID] >= 0 ) {
1735 delete $PARKED{ $self->[F_FID] };
1736 delete $PARK_REGS{ $self->[F_FID] };
1737 Acme::Parataxis::destroy_coro( $self->[F_FID] );
1738 $self->[F_FID] = -1;
1739 }
1740 }
1741 sub by_id ( $class, $fid ) { Acme::Parataxis::get_fiber_by_id($fid) }
1742  
1743 # Registered-actor lookup (the whereis table). Returns the handle of the actor spawned with that name, or undef
1744 # when nothing (or nobody alive) answers to it. Registration is removed when an actor stops, dies, or is
1745 # destroyed, so a dead actor never answers a lookup. Works as a plain function (Acme::Parataxis::actor('x')) or
1746 # a class method (Acme::Parataxis->actor('x')); whereis is an alias.
1747 sub actor {
1748 my $o = _arg_offset( $_[0] );
1749 my $name = $_[$o];
1750 @_ = ();
1751 return undef unless defined $name;
1752 return $ACTOR_REGISTRY{$name};
1753 }
1754  
1755 sub whereis {
1756 my $o = _arg_offset( $_[0] );
1757 my $name = $_[$o];
1758 @_ = ();
1759 return actor($name);
1760 }
1761  
1762 sub _dispatch_callbacks ($self) {
1763 $_->($self) for @{ $self->[F_CALLBACKS] };
1764 }
1765 class #
1766 Acme::Parataxis::Root {
1767 field $fid : reader = -1; # For now
1768  
1769 method transfer (@args) {
1770 my $rv = Acme::Parataxis::coro_transfer( -1, \@args );
1771 return unless defined $rv;
1772 return ( ref $rv eq 'ARRAY' ) ? ( wantarray ? @$rv : $rv->[-1] ) : $rv;
1773 }
1774 }
1775 END { cleanup() unless ${^GLOBAL_PHASE} eq 'DESTRUCT' }
1776 }
1777 1;