blib/lib/Acme/Parataxis/Blocking.pm untested

filter: Statementstmt 0.0% 0 / 210 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 67 MC/DCmcdc 0.0% 0 / 43 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 434 CC 40 SCAR 52.8
CC
40
Cov
0%
spawn_blocking_fork
506.0
spawn_blocking
72.0
kill_blocking_fork
20.0
CRAP 195.9
1 use v5.40;
2  
3 package Acme::Parataxis::Blocking v0.1.6 {
4 use Config;
5 use Exporter qw[import];
6 use Carp qw[croak];
7 use Acme::Parataxis qw[fiber await_sleep await_read];
8 use Acme::Parataxis::Future;
9 use Acme::Parataxis::Semaphore;
10 our %EXPORT_TAGS = (
11 all => [
12 our @EXPORT_OK
13 = qw[
14 spawn_blocking set_max_blocking_threads max_blocking_threads
15 spawn_blocking_fork set_max_blocking_forks max_blocking_forks kill_blocking_fork
16 ]
17 ]
18 );
19  
20 # spawn_blocking interpreter pool: at most $SB_MAX background interpreters run closures at once, bounded by an
21 # Acme::Parataxis::Semaphore created on first use (PARATAXIS_SB_THREADS overrides the default 4).
22 my $SB_MAX = do { my $e = $ENV{PARATAXIS_SB_THREADS}; ( defined $e && $e =~ /\A[1-9][0-9]*\z/ ) ? int($e) : 4 };
23 my $SB_PERMITS; # Acme::Parataxis::Semaphore, capacity $SB_MAX; down() before a thread spawn, up() at reap
24  
25 # spawn_blocking_fork process pool: a separate semaphore and a separate cap, because a forked child and a cloned
26 # interpreter are different resources and coupling them would make one starve the other silently.
27 my $SBF_MAX = do { my $e = $ENV{PARATAXIS_SBF_FORKS}; ( defined $e && $e =~ /\A[1-9][0-9]*\z/ ) ? int($e) : 4 };
28 my $SBF_PERMITS; # Acme::Parataxis::Semaphore, capacity $SBF_MAX; down() before a fork, up() at reap
29 my %SBF_CHILDREN; # Future address => the pid of the child that will resolve it, so kill_blocking_fork() can find it
30  
31 # Read exactly $want bytes off a pipe, parking between chunks, and return what arrived. Deliberately not built on
32 # await_read's return value: that is a readiness flag (1) rather than a byte count, and a closed write end reports
33 # readiness too, so 0 bytes off sysread here is the only honest EOF signal. A negative readiness means the child is
34 # simply still busy, which is not an error and never ends the read.
35 sub _fork_read_exactly ( $fh, $want, $timeout ) {
36 my $buf = '';
37 while ( length($buf) < $want ) {
38 my $ready = await_read( $fh, $timeout );
39  
40 # The deadline came round with the child still running: its own runtime is the only clock that matters here
41 next if $ready < 0;
42 my $n = sysread( $fh, my $chunk, $want - length($buf) );
43 last if !defined($n) || $n == 0; # write end closed, or the pipe broke
44 $buf .= $chunk;
45 }
46 return $buf;
47 }
48  
49 # Reap a child without blocking the run loop, and return its exit status as (exited, status, signal).
50 # WNOHANG in a park loop rather than a blocking waitpid: the loop's other fibers have to keep running.
51 sub _fork_reap ($pid) {
52 my $reaped = 0;
53 while ( ( $reaped = waitpid( $pid, POSIX::WNOHANG() ) ) == 0 ) { await_sleep(1) }
54 return ( 1, $? >> 8, $? & 127 ) if $reaped == $pid;
55 return ( 0, undef, undef ); # already reaped by something else, or not ours
56 }
57  
58 # Index at which user arguments start in @_: 0 when it is a plain call, 1 when $_[0] is a self (package name or
59 # blessed object). Mirrors the dance in Acme::Parataxis: read $_[0] instead of shifting, so calling this never
60 # reifies the caller's pad @_. A reified @_ left behind in a parked frame trips pp_entersub's invariants when a
61 # different fiber later enters the same sub at the same depth.
62 sub _arg_offset {
63 my $self = $_[0];
64 return ( defined $self && ( ( ref $self || $self ) eq __PACKAGE__ || ( builtin::blessed($self) && $self->isa(__PACKAGE__) ) ) ) ? 1 : 0;
65 }
66  
67 # Run a CPU-bound closure on a dedicated background Perl interpreter, with its result arriving as a normal Future.
68 #
69 # The C pool cannot do this: those workers execute C waits (sleep/read/write) only, so a real Perl closure needs a
70 # real ithread. Each call therefore clones the interpreter with threads->create (the whole point of Loom's
71 # worker_threads and the honest thread-per-task trade: the dense clone cost is paid per call, but the closure runs
72 # in complete isolation and the scheduler is never touched while it does). The bounds and the copy-in/copy-back
73 # rules are deliberate:
74 #
75 # * capacity - at most set_max_blocking_threads() interpreters run at once (default 4, PARATAXIS_SB_THREADS or a
76 # call before first use change it). Excess spawn_blocking calls park the *calling* fiber on a Semaphore until
77 # a slot frees, so the bound is a true concurrency cap like the C pool's.
78 # * copy-in - the closure sees only a snapshot of the caller's world taken at spawn: its args (threads->create
79 # args) and whatever its captured lexicals held at that instant. Threads share nothing, so in-place mutations
80 # and later writes to shared/holder state never leak back.
81 # * copy-back - the return value must survive threads::shared::shared_clone: plain scalars and nested
82 # arrays/hashes of them (blessed plain structures included) cross; an unshareable result (a CODE ref, a
83 # resource) becomes the Future's error instead. A die() in the closure likewise lands on the Future as its
84 # error.
85 # * no scheduler objects - the closure must not call back into Acme::Parataxis APIs (spawn_blocking or any
86 # blocking await) while it runs; the worker's interpreter is a copy and its scheduler state is read-only.
87 #
88 # The returned Future composes with await / with_timeout / with_cancel / wait_all exactly like any other, because
89 # the harvest is a plain scheduler fiber resolving an Acme::Parataxis::Future. Cancelling the *await* does not
90 # stop the closure (a real OS thread cannot be yanked); it only withdraws the waiter, and the slot is released
91 # when the closure actually finishes. Wall-clock only: spawn_blocking croaks inside run(virtual => 1), since real
92 # OS work cannot be fast-forwarded by the mock clock.
93 sub spawn_blocking {
94 my $o = _arg_offset( $_[0] );
95 my $code = $_[$o];
96 my @args = @_[ $o + 1 .. $#_ ];
97 @_ = ();
98 croak 'spawn_blocking() requires a CODE ref' unless ref $code eq 'CODE';
99 croak 'spawn_blocking() requires a Perl built with thread support (useithreads)'
100 unless defined $Config{useithreads} && $Config{useithreads} eq 'define';
101 croak 'spawn_blocking() must be called from inside a scheduled fiber (inside run())' if Acme::Parataxis->current_fid < 0;
102 croak 'spawn_blocking() is wall-clock only and cannot be driven by the mock clock of run(virtual => 1)'
103 if defined Acme::Parataxis->virtual_now;
104 state $loaded = do {
105 require threads;
106 require threads::shared;
107 require Thread::Queue;
108 1;
109 };
110 $SB_PERMITS //= Acme::Parataxis::Semaphore->new( count => $SB_MAX );
111 my $fut = Acme::Parataxis::Future->new;
112 my $q = Thread::Queue->new;
113 $SB_PERMITS->down('spawn_blocking capacity');
114 my $thr = eval {
115 threads->create(
116  
117 # The worker's whole world is the closure: run it, marshall the return value (or capture a die() as the
118 # error) with shared_clone, and push one payload back. Anything unshareable fails the eval and comes
119 # back as the error, never a crash in the caller.
120 sub {
121 my ( $c, $a, $oq ) = @_;
122 my $payload = eval { [ 1, threads::shared::shared_clone( $c->(@$a) ), undef ] };
123 $payload = [ 0, undef, threads::shared::shared_clone($@) ] unless $payload;
124 $oq->enqueue($payload);
125 1;
126 },
127 $code,
128 \@args,
129 $q
130 );
131 };
132 if ( !$thr ) {
133 my $err = $@ || 'thread creation failed';
134 $SB_PERMITS->up;
135 $fut->set_error($err);
136 return $fut;
137 }
138  
139 # The harvester keeps the run loop awake with a 1ms poll sleep (await_sleep rides the matching wall-clock path
140 # - loop timers when a driver is attached, the worker poll otherwise - and the loop therefore never idles or
141 # false-deadlocks while an interpreter is out), then reaps the payload, resolves the Future and hands the
142 # capacity slot to the next waiting spawn_blocking caller. Independent of the caller's cancellation scopes, so
143 # an abandoned await never strands a slot beyond the closure's own runtime. The payload is enqueued as the
144 # worker's last act, so reaping it with $thr->join (instead of detach) returns immediately AND retires the
145 # interpreter before global destruction - a detached thread still registered at exit trips threads.pm's
146 # "Can't undef active subroutine during global destruction" on some builds and corrupts the exit status.
147 eval {
148 fiber {
149 while ( $q->pending == 0 ) { await_sleep(1) }
150 my $payload = $q->dequeue_nb; # the one queued item: the [ok, result, error] payload
151 $thr->join;
152 $SB_PERMITS->up;
153 if ( $payload->[0] ) { $fut->set_result( $payload->[1] ) }
154 else { $fut->set_error( $payload->[2] ) }
155 1;
156 };
157 1;
158 } or
159 do {
160 my $err = $@;
161 $thr->join;
162 $SB_PERMITS->up;
163 $fut->set_error($err);
164 };
165 return $fut;
166 }
167  
168 # Run a CPU-bound closure in a forked child process and return its result as a normal Future.
169 #
170 # This is the same promise spawn_blocking makes, for a perl with no thread support. It is a separate entry point
171 # rather than a backend switch inside spawn_blocking on purpose: the two have genuinely different limits, and a
172 # caller should be able to see them at the call site instead of inheriting a silent per-build difference.
173 #
174 # * no threads at all - the point. Nothing here requires threads, threads::shared or Thread::Queue, so a plain
175 # perl gets CPU offload and keeps the property that loading this distribution acquires no threads association.
176 # * copy-in by fork, copy-out by Storable - the child starts as a copy of the whole parent address space, so the
177 # closure sees the caller's world as it was at the fork: its args, and whatever its captured lexicals held
178 # then. Nothing the child does to memory comes back; the only thing that travels is the frozen result. A
179 # result Storable cannot store (a CODE ref, a resource) becomes the Future's error, as does a die().
180 # * the closure must not call back into Acme::Parataxis - the child's interpreter is a copy whose scheduler state
181 # is meaningless, and it holds copies of the parent's descriptors (including any attached driver's sockets), so
182 # a closure that reads or writes through one of those would act on a copy of a descriptor, not the original.
183 # Inherited descriptors also keep their ports busy until the child exits, which is worth knowing when a closure
184 # is short but a run is long.
185 # * cancellation kills - unlike the thread pool, this one can actually stop the work. Cancelling the *await*
186 # still only withdraws the waiter, exactly as with spawn_blocking, so nothing changes by accident; when you do
187 # want the work to stop, call kill_blocking_fork($future) and the child is signalled (TERM by default).
188 # * a harvester fiber always runs - it is scheduled independently of whether anyone awaits the Future, so the
189 # pipe is drained and the child reaped even if the caller never looks at the result. That is also what keeps a
190 # large result from deadlocking: a closure whose payload exceeds the pipe buffer blocks in write until the
191 # harvester's next chunk, which is the design working, not a hang.
192 # * wall-clock only, like spawn_blocking: real processes cannot be fast-forwarded, so this croaks under
193 # run( virtual => 1 ).
194 sub spawn_blocking_fork {
195 my $o = _arg_offset( $_[0] );
196 my $code = $_[$o];
197 my @args = @_[ $o + 1 .. $#_ ];
198 @_ = ();
199 croak 'spawn_blocking_fork() requires a CODE ref' unless ref $code eq 'CODE';
200 croak 'spawn_blocking_fork() is not available on this platform (no fork(2); d_fork is ' .
201 ( defined $Config{d_fork} ? $Config{d_fork} : 'undef' ) . ')'
202 unless $Config{d_fork} && $Config{d_fork} eq 'define';
203 croak 'spawn_blocking_fork() is not available on MSWin32, where perl\'s fork() is a threads.pm emulation' if $^O eq 'MSWin32';
204  
205 # Cygwin's fork() cannot be called from a fiber stack. It fails with "can't commit memory for stack"
206 # (Win32 error 87), and forks attempted from the main stack leave the child unable to resume the
207 # suspended ucontext. The whole process then exits 0 with no diagnostic, which is far worse than a
208 # clear refusal. Cygwin perls are built with ithreads, so spawn_blocking() is the supported offload
209 # path there; this entry point exists for perls that cannot use it.
210 croak 'spawn_blocking_fork() is not available on Cygwin (fork() cannot be called from a fiber stack); use spawn_blocking() instead'
211 if $^O eq 'cygwin';
212 croak 'spawn_blocking_fork() must be called from inside a scheduled fiber (inside run())' if Acme::Parataxis->current_fid < 0;
213 croak 'spawn_blocking_fork() is wall-clock only and cannot be driven by the mock clock of run(virtual => 1)'
214 if defined Acme::Parataxis->virtual_now;
215 state $have_marshal = do { require POSIX; require Storable; 1 };
216 my $fut = Acme::Parataxis::Future->new;
217 pipe( my $rd, my $wr ) or do {
218 $fut->set_error("spawn_blocking_fork() could not create a pipe: $!");
219 return $fut;
220 };
221 $SBF_PERMITS //= Acme::Parataxis::Semaphore->new( count => $SBF_MAX );
222 $SBF_PERMITS->down('spawn_blocking_fork capacity');
223  
224 # The fork itself. The child shares nothing with the parent but this pipe, and it must leave through
225 # POSIX::_exit rather than exit: a normal exit would run END blocks and global destruction over a heap it only
226 # borrowed, letting the child's destructors touch a copy of the parent's objects. _exit also means the child's
227 # copy of the parent's buffered STDOUT is never flushed a second time.
228 my $pid = CORE::fork();
229 if ( !defined $pid ) {
230 my $err = "spawn_blocking_fork() could not fork: $!";
231 close $rd;
232 close $wr;
233 $SBF_PERMITS->up;
234 $fut->set_error($err);
235 return $fut;
236 }
237 if ( !$pid ) { # child
238 close $rd;
239  
240 # One tagged frame on the wire: a 1-byte tag, then a length-prefixed body. The tag is what tells the
241 # parent which of three things it is looking at, so the body is always a single string and exactly one
242 # length is ever transmitted - framing an array by its element count instead of its byte count is the
243 # kind of mistake that only shows up as a mystifying "Storable binary image v24.4 more recent than I am".
244 my ( $tag, $body );
245 my $image = eval { Storable::freeze( [ 1, $code->(@args) ] ) };
246 if ( defined $image ) { ( $tag, $body ) = ( 'R', $image ) }
247 else {
248 my $err = $@;
249 my $image = eval { Storable::freeze( [ 0, "$err" ] ) };
250 if ( defined $image ) { ( $tag, $body ) = ( 'E', $image ) }
251  
252 # Even the error string would not freeze. Say so in plain text rather than dying in silence.
253 else { ( $tag, $body ) = ( 'X', "the closure failed and its error could not be marshalled: $err" ) }
254 }
255 my $frame = $tag . pack( 'Q>', length $body ) . $body;
256 while ( length $frame ) {
257 my $n = syswrite( $wr, $frame );
258 last if !defined($n) || $n == 0; # the parent is gone; there is nothing left to report to
259 substr( $frame, 0, $n, '' );
260 }
261 close $wr;
262 POSIX::_exit(0);
263 }
264  
265 # parent: its own copy of the write end would keep the read end from ever seeing EOF
266 close $wr;
267 $SBF_CHILDREN{ builtin::refaddr($fut) } = $pid;
268  
269 # The permit is released exactly once. The body below runs in its own fiber, so the eval only ever catches a
270 # fiber that could not be created at all - in which case the body never ran and its up never happened.
271 eval {
272 fiber {
273 my $header = _fork_read_exactly( $rd, 9, 5000 ); # 1 tag byte + an 8-byte length
274 my $tag = length($header) ? substr( $header, 0, 1 ) : '';
275 my $len = length($header) == 9 ? unpack( 'Q>', substr( $header, 1 ) ) : 0;
276 my $body = $len ? _fork_read_exactly( $rd, $len, 5000 ) : '';
277 close $rd;
278 my ( $reaped, $status, $sig ) = _fork_reap($pid);
279 delete $SBF_CHILDREN{ builtin::refaddr($fut) };
280 $SBF_PERMITS->up;
281  
282 if ( length($header) != 9 || length($body) != $len ) {
283 $fut->set_error(
284 "the forked child never delivered a result (" . (
285 !$reaped ? 'its status is unknown, it may already have been reaped elsewhere' :
286 $sig ? "it died on signal $sig" :
287 sprintf( 'it exited with status %d', $status )
288 ) .
289 ')'
290 );
291 }
292 elsif ( $tag eq 'X' ) { $fut->set_error($body) }
293 else {
294 my $thawed = eval { Storable::thaw($body) };
295 if ( !defined $thawed || ref($thawed) ne 'ARRAY' ) {
296 $fut->set_error( "the forked child's result could not be read back: " . ( $@ || 'the thawed payload was not an array ref' ) );
297 }
298 elsif ( $thawed->[0] ) { $fut->set_result( $thawed->[1] ) }
299 else { $fut->set_error( $thawed->[1] ) }
300 }
301 1;
302 };
303 1;
304 } or
305 do {
306 my $err = $@;
307 close $rd;
308 kill 'KILL', $pid;
309 _fork_reap($pid);
310 delete $SBF_CHILDREN{ builtin::refaddr($fut) };
311 $SBF_PERMITS->up;
312 $fut->set_error($err);
313 };
314 return $fut;
315 }
316  
317 # Signal a running spawn_blocking_fork child. Returns true if a signal was delivered, false if the child was
318 # already gone. Deliberately takes the Future rather than a pid: the caller holds a Future, and a pid it would have
319 # to be told separately is a pid it can get wrong.
320 sub kill_blocking_fork {
321 my $o = _arg_offset( $_[0] );
322 my ( $fut, $sig ) = @_[ $o, $o + 1 ];
323 @_ = ();
324 croak 'kill_blocking_fork() requires an Acme::Parataxis::Future'
325 unless defined $fut && builtin::blessed($fut) && $fut->isa('Acme::Parataxis::Future');
326 $sig = 'TERM' unless defined $sig;
327 my $pid = $SBF_CHILDREN{ builtin::refaddr($fut) };
328 return false if !defined $pid;
329 return kill $sig, $pid;
330 }
331  
332 # Raise (or lower) the spawn_blocking_fork concurrency cap. Only meaningful before the pool has been used, and
333 # separate from the thread cap because a forked child and a cloned interpreter are not the same resource.
334 sub set_max_blocking_forks {
335 my $o = _arg_offset( $_[0] );
336 my $max = $_[$o];
337 @_ = ();
338 croak 'set_max_blocking_forks() requires a positive integer' unless defined $max && $max =~ /\A[1-9][0-9]*\z/;
339 croak 'set_max_blocking_forks() must be called before the first spawn_blocking_fork() (the process pool is ' . 'already in use)'
340 if $SBF_PERMITS;
341 $SBF_MAX = int($max);
342 return $SBF_MAX;
343 }
344  
345 # The configured spawn_blocking_fork capacity (the default 4, PARATAXIS_SBF_FORKS, or set_max_blocking_forks).
346 sub max_blocking_forks () {$SBF_MAX}
347  
348 # Raise (or lower) the spawn_blocking concurrency cap. Only meaningful before the pool has been used - once a
349 # Semaphore exists its capacity is live and this croaks rather than silently stealing slots from in-flight
350 # closures. Mirrors set_max_threads() for the C pool.
351 sub set_max_blocking_threads {
352 my $o = _arg_offset( $_[0] );
353 my $max = $_[$o];
354 @_ = ();
355 croak 'set_max_blocking_threads() requires a positive integer' unless defined $max && $max =~ /\A[1-9][0-9]*\z/;
356 croak 'set_max_blocking_threads() must be called before the first spawn_blocking() (the interpreter pool is already in use)' if $SB_PERMITS;
357 $SB_MAX = int($max);
358 return $SB_MAX;
359 }
360  
361 # The configured spawn_blocking capacity (the default 4, PARATAXIS_SB_THREADS, or set_max_blocking_threads).
362 sub max_blocking_threads () {$SB_MAX}
363 };
364 #
365 1;