Acme-Parataxis

 view release on metacpan or  search on metacpan

t/031_spawn_blocking_fork.t  view on Meta::CPAN

            return kill_blocking_fork($f);
        }
    );
    ok !$gone, 'kill_blocking_fork() on a finished child reports false rather than signalling a stranger';

    # Two children in flight at once: signalling one must leave the other running and its result intact. Note this is
    # a co-existence check, not a lookup oracle - a deliberately wrong lookup that just picked whichever pid the hash
    # yielded first still passed it (measured), because the doomed child happened to be the first inserted. What it
    # does catch is a lookup that returns a stale or unrelated pid, or a signal sent more broadly than one child.
    my $pair = run(
        sub {
            my $doomed = spawn_blocking_fork(
                sub {
                    my $end = time + 600;
                    my $s   = 0;
                    while ( time < $end ) { $s += $_ % 7 for 1 .. 50_000 }
                    $s;
                }
            );
            my $innocent = spawn_blocking_fork( sub { my $s = 0; $s += $_ % 7 for 1 .. 60_000; "survivor:$s" } );
            await_sleep(250);
            my $delivered    = kill_blocking_fork($doomed);
            my $survivor     = eval { $innocent->await };
            my $survivor_err = $@;
            my $doomed_r     = eval { $doomed->await };
            return { delivered => $delivered, survivor => $survivor, survivor_err => $survivor_err, doomed_err => $@ };
        }
    );
    ok $pair->{delivered}, 'the signal was delivered';
    like $pair->{survivor}, qr/^survivor:\d+$/, 'and the other child in flight finished normally, undisturbed';
    is $pair->{survivor_err}, '', 'with no error of its own';
    like $pair->{doomed_err}, qr/died on signal|never delivered/, 'while the signalled one resolved with an error';
};
subtest 'a result larger than the pipe buffer still arrives' => sub {
    my $rv = run(
        sub {
            return spawn_blocking_fork( sub { 'x' x 1_000_000 } )->await;
        }
    );
    is length($rv), 1_000_000, 'a 1MB payload crossed the pipe without deadlocking';
    ok $rv !~ /[^x]/, 'and arrived uncorrupted';
};
subtest 'the process pool is bounded by set_max_blocking_forks' => sub {
    my $rv = run(
        sub {
            # Time::HiRes::time() is named in full so the window each child reports is sub-second, and the comment
            # below the assertions says why the overlap test must not demand concurrency it cannot get everywhere.
            my @fs = map {
                spawn_blocking_fork( sub { my $t0 = Time::HiRes::time(); burn( 400_000, 'w' ); return [ $t0, Time::HiRes::time(), $$ ] } );
            } 1 .. 6;
            return [ map { $_->await } @fs ];
        }
    );

    # Concurrency cannot be counted with a shared integer here: the children are separate processes and a counter
    # they increment lands in their own copy, which is precisely the copy-in copy-out this test keeps asserting.
    # So each child reports the wall-clock window it was actually running in, and the depth is computed here.
    is scalar @$rv,                                       6, 'all six closures completed';
    is scalar( keys %{ { map { $_->[2] => 1 } @$rv } } ), 6, 'and each ran in its own process';

    # The cap is 2, so at no instant may three of them be running. Walk the endpoints and take the depth.
    #
    # What is deliberately NOT asserted is that the closures *did* overlap. The permit is taken in the parent at spawn
    # and released only once the parent's harvester has read the payload and reaped the child, so the real ceiling on
    # concurrency is parent-side teardown cost, not child work. On Linux fork and reap are cheap enough that two
    # children overlap; on a macOS x64 leg every child finished before the next one started, which reported zero
    # overlapping pairs and a peak depth of 1 while the pool was obeying its cap exactly as written. Asserting overlap
    # would have been asserting that macOS forks as fast as Linux's, which is a claim about the OS, not about this
    # code. Depth 1 is a legitimate outcome of a working cap: it means the batch serialised, which is slower and still
    # correct. The ceiling is the contract; how much of it gets used is the platform's business.
    my @events = map { ( [ $_->[0], +1 ], [ $_->[1], -1 ] ) } @$rv;
    my ( $depth, $high ) = ( 0, 0 );
    for my $e ( sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } @events ) {
        $depth += $e->[1];
        $high = $depth if $depth > $high;
    }
    cmp_ok $high, '<=', 2, "never more than the cap of 2 ran at once (peak depth $high)";
    like dies { set_max_blocking_forks(8); 1 }, qr[before the first spawn_blocking_fork], 'the cap cannot be changed once the pool is in use';
};
subtest 'croaks where the contract says it must' => sub {
    like dies { spawn_blocking_fork('nope'); 1 }, qr/spawn_blocking_fork/, 'without a CODE ref';
    like dies {
        spawn_blocking_fork( sub {1} );
        1;
    }    # genuinely outside any run
    , qr/inside a scheduled fiber/, 'outside a scheduled fiber';
    like dies {
        run(
            code => sub {
                spawn_blocking_fork( sub {1} );
            },
            virtual => 1
        );
        1;
    }, qr/wall-clock|mock clock/, 'under the mock clock of run(virtual => 1)';
    like dies {
        run( sub { kill_blocking_fork('not a future') } );
        1;
    }, qr/Future/, 'kill_blocking_fork() without a Future';
};
subtest 'composes with with_timeout, and under an attached driver' => sub {
    like run(
        sub {
            # with_timeout takes milliseconds, not seconds: a 5 would be a 5ms deadline for a 4ms closure, which
            # fails about one time in ten and looks exactly like a lost wakeup.
            return with_timeout(
                5000,
                sub {
                    spawn_blocking_fork( sub { burn( 120_000, 'timed' ) } )->await;
                }
            );
        }
        ),
        qr/^timed:\d+:/, 'the result came back under an enclosing with_timeout';
    subtest Mojo => sub {
        skip_all 2, 'Mojo::IOLoop not installed' unless eval { require Mojo::IOLoop; 1 };
        my ( $driver_rv, $ticked );
        Acme::Parataxis->attach_loop( Mojo::IOLoop->new );
        $driver_rv = run(
            sub {
                my $f = spawn_blocking_fork( sub { burn( 300_000, 'loop' ) } );



( run in 1.955 second using v1.01-cache-2.11-cpan-99fa8243a42 )