Acme-Parataxis

 view release on metacpan or  search on metacpan

Changes.md  view on Meta::CPAN

- Software Transactional Memory (STM): `Acme::Parataxis::TVar` cells and `atomically` transactions with conflict detection and `retry()`.
- Future combinators: `wait_all` and `wait_any`.
- Event loop & OS integration:
  - Event loop drivers: `Acme::Parataxis::Driver::Mojo` and `Acme::Parataxis::Driver::IOAsync`.
  - Transparent unblocking (`Acme::Parataxis::Compat`): Opt-in cooperative `CORE::GLOBAL` overrides for `sleep`, `read`, and `sysread`.
  - Deterministic virtual clock via `run( virtual => 1 )` and `advance( $ms )`.
  - Graceful shutdown handlers via `run( on_shutdown => ... )` for `SIGINT`/`SIGTERM`.
  - `fd_setsize()` introspection helper.
- Diagnostics & Introspection:
  - `dump_fibers()` and backtrace-rich deadlock diagnostics.
  - New exceptions: `Acme::Parataxis::Error`, `Error::Cancelled`, and `Error::Timeout`.
  - Verified Perl `defer` compatibility within fiber scopes.

### Fixed

- Event loop drivers now key watches by handle identity rather than recycled file descriptor numbers, eliminating lost wakeups and orphaned slots.
- Fixed non-numeric string values being silently accepted in `Supervisor->new( within => ... )`.
- Fiber jump environments (`PL_top_env`) are now preserved across context switches, preventing crashes (`0xC0000005`) when completion callbacks throw.
- Blessed exceptions stringifying to empty strings (e.g. `Error::Timeout`) are no longer misidentified as clean exits.
- Fixed bare `Died at ...` rethrows in `run()` and `Channel->get` when evaluated blocks or messages return falsey values (`0`, `''`).
- Deadlock detection now resets scheduler run queues and state so subsequent runs remain usable.
- Awaited fiber crashes are now caught and rethrown by `await` rather than killing the entire scheduler loop.
- `await_sleep` now uses native condition variable timed waits (`pthread_cond_timedwait`, `SleepConditionVariableCS`) instead of 4ms polling.
- Context switches now strictly maintain canonical `AvREIFY_only` state on argument pads, fixing `Perl_pp_entersub` assertions on `DEBUGGING` builds.
- Fiber-parking primitives now clean up `@_` landing pads before parking to avoid cross-fiber pad pollution.
- `submit_c_job` now broadcasts condition variables to prevent queued jobs from stalling behind unrelated worker sleeps.
- Enforced platform `FD_SETSIZE` bounds checks on worker pool read/write jobs and event-loop watches to prevent stack buffer overflows.
- Prevented uninitialized memory bugs in BSD `get_cpu_count` sysctl lookups.
- `exit()` from inside yielded fibers is now safely trapped and re-raised across all platforms.

META.json  view on Meta::CPAN

         "version" : "v0.1.3"
      },
      "Acme::Parataxis::Error::STM_Retry" : {
         "file" : "lib/Acme/Parataxis/Error.pm",
         "version" : "v0.1.3"
      },
      "Acme::Parataxis::Error::Supervisor" : {
         "file" : "lib/Acme/Parataxis/Error.pm",
         "version" : "v0.1.3"
      },
      "Acme::Parataxis::Error::Timeout" : {
         "file" : "lib/Acme/Parataxis/Error.pm",
         "version" : "v0.1.3"
      },
      "Acme::Parataxis::Future" : {
         "file" : "lib/Acme/Parataxis/Future.pm",
         "version" : "v0.1.3"
      },
      "Acme::Parataxis::Generator" : {
         "file" : "lib/Acme/Parataxis/Generator.pm",
         "version" : "v0.1.3"

META.yml  view on Meta::CPAN

    version: v0.1.3
  Acme::Parataxis::Error::Nursery:
    file: lib/Acme/Parataxis/Error.pm
    version: v0.1.3
  Acme::Parataxis::Error::STM_Retry:
    file: lib/Acme/Parataxis/Error.pm
    version: v0.1.3
  Acme::Parataxis::Error::Supervisor:
    file: lib/Acme/Parataxis/Error.pm
    version: v0.1.3
  Acme::Parataxis::Error::Timeout:
    file: lib/Acme/Parataxis/Error.pm
    version: v0.1.3
  Acme::Parataxis::Future:
    file: lib/Acme/Parataxis/Future.pm
    version: v0.1.3
  Acme::Parataxis::Generator:
    file: lib/Acme/Parataxis/Generator.pm
    version: v0.1.3
  Acme::Parataxis::Local:
    file: lib/Acme/Parataxis/Local.pm

README.md  view on Meta::CPAN


## `with_timeout( $ms, [$token,] $code )`

```perl
my $val = with_timeout( 1000, sub {
    return fetch_data();
} );
```

Runs `$code` under a strict deadline. If execution does not complete within `$ms` milliseconds, any parked wait
aborts and throws [Acme::Parataxis::Error::Timeout](https://metacpan.org/pod/Acme%3A%3AParataxis%3A%3AError%3A%3ATimeout). If an optional [Acme::Parataxis::CancellationToken](https://metacpan.org/pod/Acme%3A%3AParataxis%3A%3ACancellationToken) is pro...
cancelling the token interrupts the block early with [Acme::Parataxis::Error::Cancelled](https://metacpan.org/pod/Acme%3A%3AParataxis%3A%3AError%3A%3ACancelled).

## `with_cancel( sub ($token) { ... } )`

```perl
my ($token, @res) = with_cancel( sub ($t) {
    fiber { await_sleep(100); $t->cancel };
    await_sleep(10_000);
} );
```

lib/Acme/Parataxis.c  view on Meta::CPAN

/**
 * @struct job_t
 * @brief Represents a task in the background thread pool queue.
 */
typedef struct {
    int fiber_id;      /**< ID of the Fiber that submitted this task */
    int target_thread; /**< Index of the assigned worker thread */
    int type;          /**< Type of task to perform (TASK_*) */
    value_t input;     /**< Input data for the task */
    value_t output;    /**< Result data populated by the worker */
    int timeout_ms;    /**< Timeout duration for I/O tasks */
    int status;        /**< Current lifecycle state (JOB_*) */
    volatile int recall; /**< Set to 1 when the owner fiber wants an armed sleep abandoned early */
} job_t;

// Global Registry and State

/** @brief Size of the fiber table when it is first allocated: big enough that an ordinary program never has to
 *  reallocate it, small enough that the four per-slot arrays cost a few tens of kilobytes. */
#define DEFAULT_FIBER_TABLE 1024
/** @brief Default limit on how many fibers may exist at once. Generous on purpose: the table grows up to it on

lib/Acme/Parataxis.c  view on Meta::CPAN

    _spawn_workers(2);

    threads_initialized = 1;
}

/**
 * @brief Submits a C-level task to the background pool.
 *
 * @param type The task type constant (TASK_*).
 * @param arg Input integer or pointer data.
 * @param timeout_ms Timeout for I/O operations.
 * @return int The index of the submitted job, or -1 if the queue is full.
 */
DLLEXPORT int submit_c_job(int type, int64_t arg, int timeout_ms) {
    if (!threads_initialized)
        init_threads();
    int idx = -1;
    LOCK(queue_lock);

    for (int i = 0; i < MAX_JOBS; i++) {
        if (job_slots[i].status == JOB_FREE) {

lib/Acme/Parataxis.c  view on Meta::CPAN

     *
     * The object is a blessed flat arrayref; slot layout mirrors the Perl-side constants F_ERROR=2, F_RESULT=3,
     * F_IS_READY=5, F_CALLBACKS=6. Writing the result/error slots directly avoids a method dispatch per fiber
     * completion; the callback dispatch sub is only invoked when callbacks were actually registered. */
    if (c->self_ref && SvROK(c->self_ref)) {
        AV * obj = (AV *)SvRV(c->self_ref);
        SV ** ready = av_fetch(obj, 5, 0);
        if (!(ready && *ready && SvTRUE(*ready))) {
            int died;
            if (SvROK(ERRSV) && SvOBJECT(SvRV(ERRSV)))
                died = 1;    /* blessed exceptions are always errors; e.g. Error::Timeout with an overloaded "" */
            else
                died = SvTRUE(ERRSV);
            if (died) {
                av_store(obj, 2, newSVsv(ERRSV));
                av_store(obj, 5, &PL_sv_yes);
            }
            else {
                if (ret_val != &PL_sv_undef)
                    av_store(obj, 3, SvREFCNT_inc(ret_val));
                av_store(obj, 5, &PL_sv_yes);

lib/Acme/Parataxis.pm  view on Meta::CPAN

    }

    # Park the current fiber in a blocking wait, recording why and where (for diagnostics and cancellation).
    # $level is the caller stack depth (relative to _park) of the *user* frame whose location should be attributed:
    # 1 for direct wait sites, 2 for a Semaphore down(), 3 for a Channel get()/put().
    #
    # The wait-reason record is [reason, file, line] plus a fourth element, a bounded backtrace of the
    # user-side callchain (caller frames from just below the recorded site back to the fiber body). Capturing it
    # is a short caller() loop (~100ns per frame), so it runs unconditionally; backtrace_depth(0) disables it.
    # On the *re-entry* after the yield returns, a pending interrupt (set by _interrupt) is consumed and thrown, so a
    # cancelled wait unwinds with Acme::Parataxis::Error::Cancelled (or ::Timeout) right here the caller of the wait
    # sees the parked wait's own reason in the error's wait_reason.
    #
    # $dereg, when given, is a coderef that removes the *parking* fiber from whatever waiter list it is parked on
    # (Semaphore/Signal/Future/child-await). It runs only when this park is interrupted, before the error is thrown, so
    # a cancelled fiber never leaves a stale id behind that a later wake could fire at a reused fiber.
    sub backtrace_depth {
        my $invocant = shift;
        if ( !defined $invocant ||
            ( ( ref $invocant || $invocant ) ne __PACKAGE__ && !( builtin::blessed($invocant) && $invocant->isa(__PACKAGE__) ) ) ) {
            unshift @_, $invocant if defined $invocant;

lib/Acme/Parataxis.pm  view on Meta::CPAN

        # until those fire - but no wait is entered after its cancellation.
        if ( defined( my $pre = $fiber->[F_INTERRUPT] ) ) {
            my ( $pfile, $pline ) = ( caller($level) )[ 1, 2 ];
            my $pre_site = [ $pre, $pfile, $pline ];
            warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d ENTRY failfast pre=%s site=%s\n", ( time - $^T ) * 1000, $fid, $pre, "$pfile:$pline"
                if $ENV{PARATAXIS_TRACE};
            $fiber->[F_INTERRUPT] = undef;
            delete $PARKED{$fid};
            if ( my $dereg = delete $PARK_REGS{$fid} ) { $dereg->() }
            warn "PARATAXIS_TRACE park RE-ENTRY fail-fast fid=$fid reason=$reason pre=$pre\n" if $ENV{PARATAXIS_TRACE};
            my $err = $pre eq 'timeout' ? Acme::Parataxis::Error::Timeout->new( wait_reason => $pre_site ) :
                Acme::Parataxis::Error::Cancelled->new( wait_reason => $pre_site );
            die $err;
        }

        # A cancellation scope whose token already fired makes every further wait fail fast too: once the fiber's
        # pending marker has been consumed (a park threw Error::Cancelled and the user caught it), a re-park inside
        # the still-active scope must not wait in vain. Same shape as the entry fail-fast above, but keyed off the
        # innermost scope token's own cancelled flag instead of the fiber's interrupt slot.
        if ( my $scopes = $fiber->[F_CANCEL_SCOPES] ) {
            my $scope = $scopes->[-1];

lib/Acme/Parataxis.pm  view on Meta::CPAN

                delete $PARKED{$fid};
                if ( my $old = delete $PARK_REGS{$fid} ) { $old->() }
                $dereg->() if $dereg;    # this park's waiter entry (pushed before _park) is stale: remove it too
                die Acme::Parataxis::Error::Cancelled->new( wait_reason => [ 'cancel', $pfile, $pline ] );
            }
        }

        # Enclosing with_timeout deadlines bound this park. Every with_timeout whose execution this fiber is
        # inside pushed an absolute deadline (in ms) onto F_DEADLINE_SCOPES; the innermost/soonest one wins as the
        # effective bound and the outermost is the backstop. Three consequences, in order:
        #   (a) an already-passed effective bound makes a fresh wait fail fast with Error::Timeout instead of parking
        #       forever - without this, a caught Timeout followed by a re-park under the same fired deadline deadlocked
        #       (nothing was left to interrupt the wait); the check is the bound's own cancellable token being set, not
        #       just the arithmetic (left <= 0), because the deadline helper's timer may fire marginally before the wall
        #       clock reaches abs - a re-park landing in that window would otherwise be missed by the arithmetic and
        #       (since the bound is armed already) would park with nothing left to interrupt it;
        #   (b) exactly one deadline helper is armed per fiber for its effective bound and reused across re-parks
        #       (F_DEADLINE_ARMED), so a re-park never stacks a second timer for the same bound; the helper cancels the
        #       bound's token, which interrupts the registered fiber via the usual _interrupt path and recalls its jobs;
        #   (c) a helper is only armed for a bound the fiber itself owns (own => 1). An *inherited* bound (an enclosing
        #       ancestor's with_timeout, whose token this fiber is not registered on) is always enforced by that
        #       ancestor's own await-park, so arming it here would be redundant - though its absolute deadline still

lib/Acme/Parataxis.pm  view on Meta::CPAN

            if ( defined $eff ) {
                my $now  = _now_ms();
                my $left = $eff->{abs} - $now;
                if ( $left <= 0 || $eff->{tok}->cancelled ) {
                    my ( $pfile, $pline ) = ( caller($level) )[ 1, 2 ];
                    delete $PARKED{$fid};
                    if ( my $old = delete $PARK_REGS{$fid} ) { $old->() }
                    $dereg->() if $dereg;    # as above: this park's own waiter entry is stale too
                    warn "PARATAXIS_TRACE park DEADLINE fail-fast fid=$fid reason=$reason abs=" . $eff->{abs} . " now=$now\n"
                        if $ENV{PARATAXIS_TRACE};
                    die Acme::Parataxis::Error::Timeout->new( wait_reason => [ 'timeout', $pfile, $pline ] );
                }
                if ( $eff->{own} ) {
                    my $already = $fiber->[F_DEADLINE_ARMED];
                    if ( defined $already && $already == $eff->{abs} ) {
                        warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d park DEADLINE reuse abs=%.0f (already armed)\n", ( time - $^T ) * 1000, $fid,
                            $eff->{abs}
                            if $ENV{PARATAXIS_TRACE};
                    }
                    else {
                        my $tok = $eff->{tok};

lib/Acme/Parataxis.pm  view on Meta::CPAN

        my $res = yield('WAITING');
        if ( defined( my $kind = $fiber->[F_INTERRUPT] ) ) {
            my $wsite = $fiber->[F_WAIT_REASON] // [ 'undef', 'undef', 'undef' ];
            warn sprintf "PARATAXIS_TRACE t=%.0fms fid=%d re-entry interrupt consumed kind=%s wait_reason=%s wait_site=%s park_site=%s\n",
                ( time - $^T ) * 1000, $fid, $kind, $wsite->[0] // 'undef', $wsite->[1] . ':' . $wsite->[2],
                ( defined $site ? $site->[1] . ':' . $site->[2] : 'n/a' )
                if $ENV{PARATAXIS_TRACE};
            $fiber->[F_INTERRUPT] = undef;
            delete $PARKED{$fid};
            if ( my $dereg = delete $PARK_REGS{$fid} ) { $dereg->() }
            my $err = $kind eq 'timeout' ? Acme::Parataxis::Error::Timeout->new( wait_reason => $site ) :
                Acme::Parataxis::Error::Cancelled->new( wait_reason => $site );
            die $err;
        }
        return $res;
    }

    # Marks a fiber as interrupted and, if it is currently parked, wakes it so the interrupt is observed at the park's
    # re-entry. A fiber that is not parked keeps the marker and the first park it (re)enters afterwards throws. $kind is
    # 'cancel' or 'timeout' and selects which error the fiber throws.
    sub _interrupt ( $fid, $kind ) {

lib/Acme/Parataxis.pm  view on Meta::CPAN

        }
        my $code = shift;
        croak 'on_wake() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
        croak 'on_wake() requires a CODE ref' unless ref $code eq 'CODE';
        my $fiber = Acme::Parataxis->by_id( Acme::Parataxis->current_fid );
        push @{ $fiber->[F_WAKE_HOOKS] }, $code;
        return $code;
    }

    # Runs $code as a child fiber with a deadline of $ms milliseconds and returns its value, or throws
    # Acme::Parataxis::Error::Timeout when the deadline fires first. An optional Acme::Parataxis::CancellationToken
    # before $code cancels the block like an external deadline. A 0 or undef $ms means no deadline.
    #
    # The block runs as a child fiber in the same scheduler, so cooperative waits inside it (await_sleep, ->await,
    # ->wait, semaphore/signal/channel ops) suspend only the block's fiber. When a token fires, the child's parked wait
    # is interrupted at its park re-entry and the child unwinds (unregistering from the tokens as it goes);
    # with_timeout rethrows the resulting error (::Timeout or ::Cancelled) in this fiber, so it can be caught with
    # eval/try.
    #
    # The deadline is enforced per-park by _park from a per-fiber scope stack (F_DEADLINE_SCOPES). This
    # child pushes its bound onto that stack (inheriting the enclosing with_timeouts of the spawning fiber, so a
    # nested block's parks are bounded by the whole chain, innermost/soonest first and the outermost as the backstop)
    # and _park derives the effective bound, fails fast when it has already passed (a caught Timeout followed by a
    # re-park under the same fired deadline throws again instead of deadlocking), and arms exactly one deadline helper
    # per fiber for its bound - reused across re-parks, so no second timer is ever stacked for the same bound. When
    # the block finishes (or is itself interrupted) teardown's token cancel recalls the helper's armed sleep and the
    # worker is freed instead of staying occupied for the whole bound; no helper is armed at all when the block never
    # parks or when $ms is 0.
    sub with_timeout {
        my $o = _arg_offset( $_[0] );
        $o++ if $o == 0 && !defined $_[0];
        my $ms = $_[$o];
        croak 'with_timeout() requires a duration in milliseconds' unless defined $ms && $ms >= 0;

lib/Acme/Parataxis.pm  view on Meta::CPAN

            $deadline->register;
            $tok->register if $tok ne $deadline;
            my $val;
            my $err;
            try { $val = $code->() } catch ($e) {
                $err = $e
            }
            $deadline->unregister;
            $tok->unregister                  if $tok ne $deadline;
            pop @{ $cf->[F_DEADLINE_SCOPES] } if defined $scope_abs;    # leave the stack for any enclosing scope
            die $err                          if $err;                  # the ::Timeout/::Cancelled throw (or any real error) unwinds out of the child
            return $val;
        };

        # The block finished synchronously: the value (or an inline error, already rethrown by spawn) is final. Skipping
        # the deadline also means a quick inlined block never pins its run.
        if ( $child->is_done ) {
            die $child->error if defined $child->error;
            return $child->result;
        }
        my $rv;

lib/Acme/Parataxis.pm  view on Meta::CPAN

    # into each primitive. Unlike with_timeout, no child fiber is spawned; the block runs on this fiber, so interior
    # awaits and parks suspend only the normal way. The token registers this fiber for the block's whole duration
    # (a register/unregister pair, not a per-park one), so an outer cancel() both interrupts a wait parked now and
    # stamps the fiber so the *next* wait entered inside the scope fails fast. Scopes stack LIFO in a per-fiber slot
    # (_park reads the innermost one); nesting with_timeout or nursery tokens shares the park, and whichever token
    # fires first ends the wait while teardown drops the others' registrations.
    #
    # Return convention (context aware): the scope token alone in scalar/void context, the token prepended to the
    # block's value(s) in list context (my ($tok, @vals) = with_cancel sub { ... }). On failure the block's own
    # error propagates unchanged (the real error wins over a concurrently arriving cancel); if the scope itself was
    # cancelled by an outer token while the block ran to completion, Error::Cancelled (or Timeout for a deadline)
    # is thrown at the scope boundary instead of swallowing the interrupt.
    sub with_cancel {
        my $o    = _arg_offset( $_[0] );
        my $code = $_[$o];
        @_ = ();
        croak 'with_cancel() requires a CODE ref' unless ref $code eq 'CODE';
        croak 'with_cancel() must be called from inside a scheduled fiber' if Acme::Parataxis->current_fid < 0;
        state $have_token = do { require Acme::Parataxis::CancellationToken; 1 };
        my $tok   = Acme::Parataxis::CancellationToken->new( kind => 'cancel' );
        my $fiber = Acme::Parataxis->by_id( Acme::Parataxis->current_fid );

lib/Acme/Parataxis.pm  view on Meta::CPAN

            # The block's own error wins: drop any interrupt still pending so it cannot resurface at an outer scope
            # after this one has already reported the real failure.
            $fiber->[F_INTERRUPT] = undef;
            die $err;
        }
        if ( my $kind = $fiber->[F_INTERRUPT] ) {

            # The block returned normally but an outer token/deadline fired while it ran: consume the marker and
            # convert it to the matching error so the cancellation is never silently swallowed at this boundary.
            $fiber->[F_INTERRUPT] = undef;
            die $kind eq 'timeout' ? Acme::Parataxis::Error::Timeout->new : Acme::Parataxis::Error::Cancelled->new;
        }
        return wantarray ? ( $tok, @val ) : $tok;
    }

    # STM (software transactional memory). atomically() runs $code as one transaction on the calling fiber: reads are
    # journaled, writes stay in a write set until the outermost atomically commits (validating
    # every read first, re-running on conflict), and retry() parks the fiber until a TVar it
    # read changes. The block may run many times - no irreversible side effects inside it.
    # See Acme::Parataxis::TVar for the semantics and the SIDE EFFECTS warning.
    sub atomically : prototype(&) {

lib/Acme/Parataxis.pm  view on Meta::CPAN

    sub _driver_sleep ( $driver, $ms ) {
        my $fid = Acme::Parataxis->current_fid;
        croak 'await_sleep() must be called from inside a scheduled fiber' if $fid < 0;
        my $fired = 0;
        my $id    = $driver->timer( $ms, sub { $fired = 1; Acme::Parataxis::_scheduler_enqueue_by_id($fid) } );
        my $dereg = sub { $driver->cancel_timer($id) unless $fired };
        return _park( 'await_sleep', 1, $dereg );
    }

    # Register a read/write watch on the attached loop, arm the wait's own deadline timer, and park. Natural wake
    # returns 1; the wait's own deadline swallows its ::Timeout and returns -1 like the pool path does; an *enclosing*
    # with_timeout / nursery interrupt did not cancel our deadline token, so it propagates by dying.
    #
    my $WARNED_FD_SETSIZE = 0;

    sub _driver_wait ( $driver, $fh, $dir, $timeout, $reason ) {
        my $fid = Acme::Parataxis->current_fid;
        croak "$reason() must be called from inside a scheduled fiber" if $fid < 0;

        # A loop whose readiness comes from select() cannot name a descriptor at or past the platform's
        # FD_SETSIZE - 256 on NetBSD, 64 for winsock, 1024 on Linux - and the fd_set in that case belongs to

lib/Acme/Parataxis.pm  view on Meta::CPAN

            $driver->unwatch($fh);
            $driver->cancel_timer($timer_id) if defined $timer_id;
            $deadline->unregister            if defined $deadline;
        };
        my $ok = 1;
        my $err;
        try { Acme::Parataxis::_park( $reason, 1, $dereg ) }
        catch ($e) { $ok = 0; $err = $e }
        finally { $dereg->() }    # idempotent: on an interrupt _park already ran it, on a natural wake this is the cleanup
        if ( !$ok ) {
            if ( defined $deadline && $deadline->cancelled && ref($err) && $err->isa('Acme::Parataxis::Error::Timeout') ) {
                $out = -1;        # this wait's own deadline expired; the pool path resumes (not throws) on timeout
            }
            else { $dying = $err }
        }
        $deadline->unregister if defined $deadline;
        $deadline->cancel     if defined $deadline;
        die $dying            if defined $dying;
        return $out;
    }

lib/Acme/Parataxis.pod  view on Meta::CPAN


Suspends the current fiber until C<$fh> is ready to accept writes. Returns C<1> on readiness, C<-1> on timeout.

=head2 C<with_timeout( $ms, [$token,] $code )>

    my $val = with_timeout( 1000, sub {
        return fetch_data();
    } );

Runs C<$code> under a strict deadline. If execution does not complete within C<$ms> milliseconds, any parked wait
aborts and throws L<Acme::Parataxis::Error::Timeout>. If an optional L<Acme::Parataxis::CancellationToken> is provided,
cancelling the token interrupts the block early with L<Acme::Parataxis::Error::Cancelled>.

=head2 C<with_cancel( sub ($token) { ... } )>

    my ($token, @res) = with_cancel( sub ($t) {
        fiber { await_sleep(100); $t->cancel };
        await_sleep(10_000);
    } );

Executes C<$code> within a scoped cancellation context. The block receives a fresh C<CancellationToken>. Any wait

lib/Acme/Parataxis/CancellationToken.pm  view on Meta::CPAN

use v5.40;
no warnings 'experimental::class', 'recursion';
use feature 'class';
#
class Acme::Parataxis::CancellationToken v0.1.3 {
    use Acme::Parataxis;
    use Carp        qw[croak];
    use Time::HiRes qw[time];

    # $kind selects which error an interrupted waiter throws. Public tokens use 'cancel'; with_timeout's internal
    # deadline token uses 'timeout' so the same mechanism raises Timeout instead of Cancelled.
    field $cancelled : reader : param = false;
    field $kind      : reader : param = 'cancel';
    field $t0        : reader = time;    # token birth, for elapsed-time tracing

    # Fiber ids currently parked under this token, in registration order. cancel() wakes them; unregister()/the
    # on_wake( { ... } ) cleanup removes them when their wait finishes normally.
    field @registered;

    method register () {
        my $fid = Acme::Parataxis->current_fid;

lib/Acme/Parataxis/CancellationToken.pod  view on Meta::CPAN

    my $cancel   = Acme::Parataxis::CancellationToken->new;
    my $deadline = Acme::Parataxis::CancellationToken->new( kind => 'timeout' );

Constructs a fresh, uncancelled token.

=over

=item * C<kind =E<gt> $str>

Picks the exception class thrown by interrupted waits: C<'cancel'> (the default) throws
L<Acme::Parataxis::Error::Cancelled>, while C<'timeout'> throws L<Acme::Parataxis::Error::Timeout>. Any string is
accepted and passed down to the diagnostic error object. Internal deadlines use C<'timeout'> so the scheduler raises
timeout diagnostics through the unified cancellation path.

=back

Arguments are keyword-only.

=head2 C<cancel( )>

    $cancel->cancel;    # returns true the first time, undef thereafter

lib/Acme/Parataxis/CancellationToken.pod  view on Meta::CPAN

        $n->spawn( sub { await_sleep(5000); $abort->cancel } );
    } );

=head2 Relocating or extending a deadline

    my $deadline = Acme::Parataxis::CancellationToken->new( kind => 'timeout' );

    my $job = fiber {
        $deadline->register;
        defer { $deadline->unregister };
        my $res = eval { $work->await };    # throws Error::Timeout, not Error::Cancelled
        return $res;
    };

    # The deadline is just another fiber that can be extended or rescheduled:
    fiber {
        await_sleep(250);
        $deadline->cancel if $need_to_abort;
    };

=head1 Behavior Notes

lib/Acme/Parataxis/CancellationToken.pod  view on Meta::CPAN

=item * After catching a cancellation

Inside a L<with_cancel|Acme::Parataxis/with_cancel> scope, any subsequent wait also fails fast because the scope's
token remains cancelled. Treat a caught cancellation as an instruction to exit the scope. In contrast, with a manual
C<register> call, the immediate interrupt flag is cleared once thrown; a subsequent wait will park normally unless the
token is re-checked or re-registered.

=item * Error hierarchy

Default tokens throw L<Acme::Parataxis::Error::Cancelled>; C<kind =E<gt> 'timeout'> tokens throw
L<Acme::Parataxis::Error::Timeout>. Both inherit from L<Acme::Parataxis::Error>. A timeout is B<not> a subclass of
cancellation; check C<< $err->kind >> (which returns C<'cancelled'> or C<'timeout'>) rather than testing inheritance.

C<< $err->wait_reason >> returns C<[ $reason, $file, $line, $backtrace ]> describing the wait that was interrupted. On
a fast-fail path (where the token was already cancelled before entering the wait), C<$reason> is set to C<'cancel'> or
C<'timeout'> and the backtrace array is empty.

=item * A leaked registration arms the next fiber

Fiber IDs are recycled once a completed fiber is reaped. If a fiber registers on a token, finishes its work, and exits
without calling C<unregister>, its ID remains in the token's list. If a subsequent, unrelated fiber is later allocated

lib/Acme/Parataxis/Channel.pm  view on Meta::CPAN

    field @select_waiters;                                # [fid, op] pairs parked here by select(); op is 'get' or 'put'
    ADJUST {
        $capacity >= 1                    or die "Channel capacity must be >= 1 (got $capacity)\n";
        defined $timeout && $timeout >= 0 or die "Channel timeout must be a non-negative number of milliseconds (got $timeout)\n";
    }

    # Runs $op (a get/put body that parks through the channel semaphores) under the channel's default
    # wait bound. The deadline is armed only when the op may actually park ($may_park): a ready channel
    # never pays for a timer. Exactly like Channel::select's deadline - one token registered before the
    # park (register-then-arm closes the lost-wakeup window) and one timer, re-used across the
    # semaphore's internal re-parks; Error::Timeout on expiry, the waiter unregistered from the
    # semaphore when interrupted. Teardown unregisters the caller and cancels the token on every exit,
    # which recalls the timer's armed sleep job instead of leaving a worker sleeping out the bound.
    method _with_deadline ( $may_park, $op ) {
        return $op->() if !defined $timeout || $timeout <= 0 || !$may_park;
        my $deadline = Acme::Parataxis::CancellationToken->new( kind => 'timeout' );
        $deadline->register;
        my $ms = $timeout;
        fiber {
            $deadline->register;
            try { await_sleep($ms); $deadline->cancel } catch ($e) {

lib/Acme/Parataxis/Channel.pm  view on Meta::CPAN

            };
            my $ok = 1;
            my $err;
            try { Acme::Parataxis::_park( 'Channel select', 1, $dereg ) }
            catch ($e) { $ok = 0; $err = $e }
            finally { $dereg->() }    # idempotent: on interrupt _park already ran it; on a natural wake this is the cleanup
            if ( !$ok ) {

                # Our own deadline fired -> the API is (undef, undef) on timeout. A timeout sent by an *enclosing*
                # with_timeout/nursery did not cancel our token, so it propagates instead of being swallowed.
                if ( defined $deadline && $deadline->cancelled && ref($err) && $err->isa('Acme::Parataxis::Error::Timeout') ) {
                    ( $out_ch, $out_val ) = ( undef, undef );
                    last OUTER;
                }
                $out_die = $err;
                last OUTER;
            }
        }

        # Every exit funnels through here so the armed timeout helper is never orphaned: drop the select fiber off
        # the token first (a running fiber must not receive its own interrupt), then cancel to recall the timer's

lib/Acme/Parataxis/Channel.pod  view on Meta::CPAN

=over

=item * C<capacity =E<gt> $int>

Buffer slot limit before C<put> parks (default: C<2_000_000_000>, effectively unbounded). Must be at least C<1>. If you
want backpressure, always set this explicitly.

=item * C<timeout =E<gt> $ms>

Default wait bound in milliseconds for any C<get> or C<put> that parks. If the wait exceeds this duration, it throws
L<Acme::Parataxis::Error::Timeout>. Default C<0> (no timeout).

=back

=head2 C<get( )>

    my $val = $q->get;

Removes and returns the oldest value in the channel, parking the calling fiber if the channel is empty. Once a
shut-down channel has been fully drained, C<get> returns C<undef> forever. Honors the channel's configured C<timeout>.

lib/Acme/Parataxis/Channel.pod  view on Meta::CPAN

=item * EOF semantics across methods

When a channel is shut down and drained, C<get> returns C<undef>, C<try_get> returns C<(1, undef)>, and a C<select> get
case returns C<($channel, undef)>. Check for defined values when reading from channels that may close.

=item * Backpressure is a park

When a bounded channel fills, producers park inside the scheduler rather than consuming system memory. This makes
cancellation safe: an interrupted C<put> simply aborts its registration, leaving the buffer untouched.

=item * Timeouts apply only to parking operations

A C<get> or C<put> that succeeds immediately never arms a timer. Neither C<try_get> nor C<try_put> ever consults the
configured timeout.

=back

=head1 SEE ALSO

L<Acme::Parataxis>, L<Acme::Parataxis::Stream>, L<Acme::Parataxis::Actor>, L<Acme::Parataxis::CancellationToken>

lib/Acme/Parataxis/Compat.pod  view on Meta::CPAN


    package My::Worker;
    use v5.40;
    use Acme::Parataxis qw[async fiber];

    BEGIN { Acme::Parataxis->enable_transparent_unblocking() }

    use Net::FTP;    # compiled AFTER the overrides; its internal reads and sleeps cooperate!

    async {
        my $ftp = fiber { Net::FTP->new('ftp.example.com', Timeout => 10) };
        $ftp->await;
    };

=head2 Reading an exact number of bytes safely

Because non-blocking reads return as soon as data arrives, wrap reads in a loop when a fixed payload size is required:

    sub read_exact ( $fh, $len ) {
        my $buf = q{};
        my $got = 0;

lib/Acme/Parataxis/Error.pm  view on Meta::CPAN

    # the fiber was waiting.
    package Acme::Parataxis::Error::Cancelled v0.1.3 {
        use parent 'Acme::Parataxis::Error';
        sub new   ( $class, %args ) { Acme::Parataxis::Error::_new( $class, 'The operation was cancelled', %args ) }
        sub throw ( $class, %args ) { die $class->new(%args) }
        sub kind  ($self)           {'cancelled'}
    }

    # Thrown at the re-entry of a parked wait when a with_timeout deadline fired before the block was
    # able to finish.
    package Acme::Parataxis::Error::Timeout v0.1.3 {
        use parent 'Acme::Parataxis::Error';

        sub new ( $class, %args ) {
            my $seconds = delete $args{seconds};
            my $label   = defined $seconds ? "The operation timed out after ${seconds}s" : 'The operation timed out';
            Acme::Parataxis::Error::_new( $class, $label, seconds => $seconds, %args );
        }
        sub throw   ( $class, %args ) { die $class->new(%args) }
        sub kind    ($self)           {'timeout'}
        sub seconds ($self)           { $self->{seconds} }

lib/Acme/Parataxis/Error.pod  view on Meta::CPAN

=over

=item * C<< ->kind >> returns C<'cancelled'>.

=item * Message format: C<"The operation was cancelled at <site>">.

=item * Supports C<< ->new( wait_reason => $reason ) >> and C<< ->throw( ... ) >>.

=back

=head2 Acme::Parataxis::Error::Timeout

Thrown when a L<with_timeout|Acme::Parataxis/with_timeout> deadline expires before the enclosed block completes.

=over

=item * C<< ->kind >> returns C<'timeout'>.

=item * Message format: C<"The operation timed out at <site>">.

=item * C<Error::Timeout> is a B<sibling> of C<Error::Cancelled>, not a subclass. Do not use C<isa> to tell them apart;
switch on C<< ->kind >>.

=back

=head2 Acme::Parataxis::Error::Nursery

Thrown by L<nursery|Acme::Parataxis/nursery> when one or more enrolled child fibers die.

=over

lib/Acme/Parataxis/Generator.pod  view on Meta::CPAN

    } );

    say $cubes->next for 1 .. 4;    # 1, 8, 27, 64

=head2 Exception propagation preserving error objects

    use Acme::Parataxis::Error;

    my $gen = Acme::Parataxis::Generator->new( sub ($y) {
        $y->(1);
        Acme::Parataxis::Error::Timeout->throw( seconds => 5 );
    } );

    say $gen->next;    # 1
    eval { $gen->next };
    if ( my $err = $@ ) {
        say "Caught typed error: " . $err->kind;    # 'timeout'
    }

=head1 Behavior Notes

t/100_sync_mutex.t  view on Meta::CPAN

        };
        is $m->waiters, 0, 'the timed-out waiter removed itself from the queue';
        my $c = fiber {
            $m->lock;
            $log .= 'C';
            $m->unlock;
        };
        $a->await;
        $c->await;
    };
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'the block timed out instead of deadlocking';
    is $log, 'AC', 'the cancelled waiter got no lock; the next waiter did';
};
subtest 'lock/try_lock/unlock croak outside a scheduled fiber' => sub {
    my $m = Acme::Parataxis::Sync::Mutex->new;
    like dies { $m->lock },     qr/scheduled fiber/, 'lock croaks';
    like dies { $m->try_lock }, qr/scheduled fiber/, 'try_lock croaks';
    like dies { $m->unlock },   qr/scheduled fiber/, 'unlock croaks';
    like dies { $m->guard },    qr/scheduled fiber/, 'guard croaks';
};
#

t/101_sync_rwlock.t  view on Meta::CPAN

            with_timeout( 10, sub { $rw->write_lock; $log .= 'SHOULD-NOT' } );
        };
        is $rw->write_waiters, 0, 'the timed-out writer removed itself from the queue';
        my $next = fiber { $rw->write_lock; $log .= 'N'; $rw->write_unlock };
        $holder->await;
        $next->await;
        is $rw->waiters, 0, 'the lock drained';
        is $rw->readers, 0, 'no read hold was stranded';
        ok !defined $rw->writer, 'and no writer was left recorded';
    };
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'the block timed out instead of deadlocking';
    is $log, 'HN', 'the cancelled writer never got the lock; the next one did';
};
subtest 'an interrupted read_lock unregisters and the lock stays usable' => sub {
    my $rw  = Acme::Parataxis::Sync::RwLock->new;
    my $log = '';
    my $err;
    async {
        my $w = fiber { $rw->write_lock; await_sleep(2000); $rw->write_unlock; $log .= 'W' };
        $err = dies {
            with_timeout( 10, sub { $rw->read_lock; $log .= 'SHOULD-NOT' } );
        };
        is $rw->read_waiters, 0, 'the timed-out reader removed itself from the queue';
        my $r = fiber { $rw->read_lock; $log .= 'R'; $rw->read_unlock };
        $w->await;
        $r->await;
        is $rw->waiters, 0, 'the lock drained';
        is $rw->readers, 0, 'and released every hold';
    };
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'the block timed out instead of deadlocking';
    is $log, 'WR', 'the cancelled reader never got in; the next one did';
};
subtest 'every operation croaks outside a scheduled fiber' => sub {
    my $rw = Acme::Parataxis::Sync::RwLock->new;
    like dies { $rw->read_lock },      qr/scheduled fiber/, 'read_lock croaks';
    like dies { $rw->try_read_lock },  qr/scheduled fiber/, 'try_read_lock croaks';
    like dies { $rw->read_unlock },    qr/scheduled fiber/, 'read_unlock croaks';
    like dies { $rw->write_lock },     qr/scheduled fiber/, 'write_lock croaks';
    like dies { $rw->try_write_lock }, qr/scheduled fiber/, 'try_write_lock croaks';
    like dies { $rw->write_unlock },   qr/scheduled fiber/, 'write_unlock croaks';

t/103_sync_barrier.t  view on Meta::CPAN

        };
        is $b->waiters, 0, 'the timed-out arriver removed itself';

        # two arrivals are still booked for this phase; two live parties finish it
        my $two = fiber { $b->arrive_and_wait; 'two' };
        my $ret = $b->arrive_and_wait;
        is $ret,          1,     'the main arrival released the phase';
        is $two->await,   'two', 'the other live party was released too';
        is $b->remaining, 3,     'a fresh phase is armed for the next generation';
    };
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'the first arrival timed out';
};
subtest 'barrier construction and waits outside the scheduler croak' => sub {
    like dies { Acme::Parataxis::Sync::Barrier->new( parties => 0 ) }, qr/positive number of parties/, 'parties < 1 croaks at construction';
    my $b = Acme::Parataxis::Sync::Barrier->new( parties => 2 );
    like dies { $b->arrive_and_wait }, qr/scheduled fiber/, 'arrive_and_wait croaks outside the scheduler';
};
#
done_testing;

t/104_sync_waitgroup.t  view on Meta::CPAN

    async {
        $wg->add(1);    # a unit that will never be done within the timeout
        $err = dies {
            with_timeout( 10, sub { $wg->wait } );
        };
        is $wg->waiters, 0, 'the timed-out waiter removed itself';
        $wg->done;      # drain the stuck unit; nothing stale to wake
        my $f = fiber { $wg->wait };
        is $f->await, 1, 'a fresh wait lifts normally after the group drained';
    };
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'the stuck wait timed out';
};
subtest 'waits must occur inside a scheduled fiber' => sub {
    my $wg = Acme::Parataxis::Sync::WaitGroup->new;
    like dies { $wg->wait }, qr/scheduled fiber/, 'wait() croaks outside the scheduler';
};
#
done_testing;

t/106_coro_channel.t  view on Meta::CPAN

};
subtest 'a channel get times out at the default bound' => sub {
    my $ch = Acme::Parataxis::Channel->new( timeout => 30 );
    my ( $err, $t0, $elapsed );
    async {
        $t0      = Time::HiRes::time();
        $err     = dies { $ch->get };
        $elapsed = ( Time::HiRes::time() - $t0 ) * 1000;
    };
    ok $err,                                         'get() threw instead of parking forever';
    ok $err->isa('Acme::Parataxis::Error::Timeout'), 'the error is Error::Timeout';
    ok $elapsed < 2000,                              "the timed-out get fired without hanging (elapsed=${\(int $elapsed)}ms)";
    wait_for_drain();
};
subtest 'a channel put times out at the default bound' => sub {
    my $ch = Acme::Parataxis::Channel->new( capacity => 1, timeout => 30 );
    $ch->put('full');
    my $err;
    async {
        $err = dies { $ch->put('nope') };
    };
    ok $err,                                         'put() threw on a channel that stayed full';
    ok $err->isa('Acme::Parataxis::Error::Timeout'), 'the error is Error::Timeout';
    wait_for_drain();
    is $ch->size, 1, 'the buffered item is untouched';
};
subtest 'with_timeout and cancellation still interrupt an unexpired channel wait' => sub {
    my $ch = Acme::Parataxis::Channel->new( timeout => 10000 );    # far beyond the test hull, so only the outer interrupt can fire
    my $err;
    async {
        $err = dies {
            with_timeout( 30, sub { $ch->get } );
        };
    };
    ok $err,                                         'an enclosing with_timeout fires before the channel bound';
    ok $err->isa('Acme::Parataxis::Error::Timeout'), 'as Error::Timeout';
    wait_for_drain();
    my $tok = Acme::Parataxis::CancellationToken->new;
    my $ch2 = Acme::Parataxis::Channel->new( timeout => 10000 );
    my $err2;
    async {
        $tok->register;
        fiber { yield; $tok->cancel };
        $err2 = dies { $ch2->get };
    };
    ok $err2,                                           'a cancellation token interrupts a channel wait too';

t/153_nursery.t  view on Meta::CPAN

                    nursery(
                        sub ($n) {
                            $n->spawn( sub { await_sleep(200); $done = 1 } );
                            $n->spawn( sub { await_sleep(200) } );
                        }
                    );
                }
            );
        };
    };
    ok ref($t_err) && $t_err->isa('Acme::Parataxis::Error::Timeout'), 'the enclosing timeout wins over the join';
    ok !$done,                                                        'the children were cancelled and drained, not left running';
};
subtest 'destructors of in-flight children run during cancellation' => sub {
    $DtorProbe::n = 0;
    async {
        eval {
            nursery(
                sub ($n) {
                    $n->spawn( sub { my $d = DtorProbe->new; await_sleep(50) } );
                    $n->spawn( sub { die 'boom' } );

t/155_cancel_scope.t  view on Meta::CPAN

    my $caught;
    async {
        $caught = dies {
            with_cancel(
                sub {
                    with_timeout( 20, sub { $sem->down } );
                }
            );
        };
    };
    ok ref($caught) && $caught->isa('Acme::Parataxis::Error::Timeout'), 'the deadline won over the (unfired) scope';
    is $sem->waiters, 0, 'the timed-out waiter was deregistered';
};
subtest 'composition with with_timeout: the scope beats a still-armed deadline' => sub {
    my $sem = Acme::Parataxis::Semaphore->new( count => 0 );
    my ( $tok, $caught );
    async {
        $caught = dies {
            with_cancel(
                sub {
                    my ($t) = @_;
                    $tok = $t;
                    my $fire = fiber { await_sleep(10); $tok->cancel };
                    with_timeout( 5000, sub { $sem->down } );
                }
            );
        };
    };
    ok ref($caught) && $caught->isa('Acme::Parataxis::Error::Cancelled'),    'the scope cancel won over the unexpired deadline';
    ok !( ref($caught) && $caught->isa('Acme::Parataxis::Error::Timeout') ), 'not reported as a timeout';
    is $sem->waiters, 0, 'the deadline block left no waiter behind';
};
subtest 'no stale registrations leak from normal or thrown exits' => sub {
    my $sem = Acme::Parataxis::Semaphore->new( count => 0 );
    my @toks;
    async {
        my $w = fiber {
            my $t = with_cancel( sub { $sem->down; return 'a' } );
            push @toks, $t;
        };

t/156_with_timeout.t  view on Meta::CPAN

    ->[0];
    is $got, 55, 'block value returned';
    is $ran, 1,  'block ran exactly once';
};
subtest 'a parking block that finishes under the deadline returns its value' => sub {
    my $got = async {
        with_timeout( 400, sub { await_sleep(1); 'fast' } )
    };
    is $got, 'fast', 'parked-but-fast block returned';
};
subtest 'deadline fires: Error::Timeout is thrown in the caller and the run continues' => sub {
    my ( $caught, $after );
    async {
        $caught = dies {
            with_timeout( 20, sub { sem_block() } );
        };
        $after = 'ran-on';
    };
    ok ref($caught) && $caught->isa('Acme::Parataxis::Error::Timeout'), '::Timeout thrown by with_timeout';
    is $caught->kind,             'timeout',        'kind() is "timeout"';
    is $caught->wait_reason->[0], 'Semaphore down', 'wait_reason names the blocked wait';
    is $after,                    'ran-on',         'the async block continued after catching the timeout';
    ok eval {1}, 'run untouched by the timeout';
};
subtest 'with_timeout runs inside a spawned fiber' => sub {
    my $got;
    async {
        my $f = fiber {
            my $c = fiber { await_sleep(5); 7 };

t/156_with_timeout.t  view on Meta::CPAN

                with_timeout(
                    $bound,
                    sub {
                        await_sleep($inner);
                        "ok-$i";
                    }
                );
            };
        }
    };
    ok $errors[0] && $errors[0]->isa('Acme::Parataxis::Error::Timeout'), 'first too-short bound timed out';
    ok !( $errors[1] && ref $errors[1] ),                                'second bound returned cleanly';
    ok $errors[2] && $errors[2]->isa('Acme::Parataxis::Error::Timeout'), 'third too-short bound timed out again';
};
subtest 'an explicit token cancels the block with Error::Cancelled' => sub {
    my $caught;
    async {
        my $tok  = Acme::Parataxis::CancellationToken->new;
        my $fire = fiber { await_sleep(10); $tok->cancel; 1 };
        try {
            with_timeout( 2000, $tok, sub { sem_block() } );
        }
        catch ($e) { $caught = $e; }

t/156_with_timeout.t  view on Meta::CPAN

    ok ref($caught) && $caught->isa('Acme::Parataxis::Error::Cancelled'), 'fast-fail ::Cancelled';
};
subtest 'genuine errors from the block propagate unchanged' => sub {
    my $caught;
    async {
        $caught = dies {
            with_timeout( 2000, sub { die 'real-bug' } );
        };
    };
    like $caught, qr[real-bug], 'the block die is not mistaken for a timeout';
    ok !( ref $caught && $caught->isa('Acme::Parataxis::Error::Timeout') ), 'not a ::Timeout';
};
subtest 'a zero bound means no deadline' => sub {
    my $got = async {
        with_timeout( 0, sub { await_sleep(3); 'no-bound' } )
    };
    is $got, 'no-bound', 'ms == 0 runs the block to completion';
};
subtest 'a timed-out Future await then a working one' => sub {
    my ( $err, $later );
    async {
        my $f = Acme::Parataxis::Future->new;
        $err = dies {
            with_timeout( 20, sub { $f->await; 'f' } );
        };
        my $g = Acme::Parataxis::Future->new;
        my $w = fiber { $g->await };
        $g->set_result('now');
        $later = $w->await;
    };
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'Future await timed out';
    is $later, 'now', 'a new Future await completes normally afterwards';
};
subtest 'with_timeout requires a fiber context and a non-negative bound' => sub {
    like dies {
        with_timeout( 50, sub {1} )
    }, qr[must be called from inside a scheduled fiber], 'croaks outside a scheduled fiber';
    async {
        like dies {
            with_timeout( -1, sub {1} )
        }, qr[requires a duration in milliseconds], 'croaks on a negative duration';

t/157_with_timeout_repark.t  view on Meta::CPAN

                                    $n->spawn( sub { await_sleep(300); $done = 1 } );
                                    $n->spawn( sub { await_sleep(300) } );
                                }
                            );
                        }
                    );
                }
            );
        };
    };
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'the outer timeout propagates to the caller';
    ok !$done,                                                    'the deepest grandchild was cancelled and drained by the teardown';
    is Acme::Parataxis::get_live_fiber_count(), $base, 'no fiber leaked: the still-parked grandchild coroutine was reaped without crashing';
};
subtest 'the scheduler is clean afterwards: a later with_timeout runs normally' => sub {
    my $second;
    async {
        eval {
            with_timeout(
                20,
                sub {

t/157_with_timeout_repark.t  view on Meta::CPAN

        $err = dies {
            with_timeout(
                20,
                sub {
                    with_timeout( 2000, sub { $ch->get } );
                }
            );
        };
        $elapsed = ( time - $t0 ) * 1000;
    };
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'the outer 20ms bound aborts the inner 2000ms bound';
    ok $elapsed < 1000,                                           "aborted by the outer bound at ${elapsed}ms, not left to the inner bound";
};
subtest 'the outer deadline still kills a re-park after the inner fires' => sub {
    my ( $inner_at, $inner_err, $repark_at, $repark_err );
    my $ch = Acme::Parataxis::Channel->new;
    async {
        with_timeout(
            300,
            sub {
                my $t0 = time;
                $inner_err = dies {
                    with_timeout( 30, sub { $ch->get } );
                };
                $inner_at = ( time - $t0 ) * 1000;
                my $t1 = time;
                $repark_err = dies { $ch->get };
                $repark_at  = ( time - $t1 ) * 1000;
            }
        );
    };
    ok ref($inner_err)  && $inner_err->isa('Acme::Parataxis::Error::Timeout'),  'the inner deadline fires first';
    ok ref($repark_err) && $repark_err->isa('Acme::Parataxis::Error::Timeout'), 'the outer deadline kills the re-park too';
    ok $repark_at < 2000, "re-park lost at ${repark_at}ms under the 300ms backstop, it did not hang";
};
subtest 're-parking after the deadline fired fails fast instead of deadlocking' => sub {
    my ( $e1, $e2, $elapsed );
    my $ch = Acme::Parataxis::Channel->new;
    async {
        with_timeout(
            50,
            sub {
                $e1 = dies { $ch->get };
                my $t1 = time;
                $e2      = dies { $ch->get };
                $elapsed = ( time - $t1 ) * 1000;
            }
        );
    };
    ok $e1 && ref($e1) && $e1->isa('Acme::Parataxis::Error::Timeout'), 'the first park timed out';
    ok $e2 && ref($e2) && $e2->isa('Acme::Parataxis::Error::Timeout'),
        'the re-park under the fired deadline failed fast with ::Timeout (no deadlock)';
    ok $elapsed < 500, "re-park failed fast at ${elapsed}ms, it did not wait";
};
subtest 'a re-park reuses the armed timer instead of arming a second one' => sub {
    my ( $first_err, $repark_err, $repark_at, $jobs );
    my $ch  = Acme::Parataxis::Channel->new;
    my $sig = Acme::Parataxis::Channel->new;
    async {
        my $tok = Acme::Parataxis::CancellationToken->new;
        fiber { await_sleep(20); $tok->cancel; $sig->put(1) };
        fiber {

t/157_with_timeout_repark.t  view on Meta::CPAN

                    $repark_at  = ( time - $t0 ) * 1000;
                }
            );
        };
        $sig->get;    # the canceller fiber is done and its sleep job reclaimed: outstanding is exactly the one ~700ms helper
        $jobs = Acme::Parataxis::get_outstanding_jobs();
        await_sleep(700);
    };
    ok $first_err && ref($first_err) && $first_err->isa('Acme::Parataxis::Error::Cancelled'), 'the cancel token tore the first park';
    is $jobs, 1, 'only the original deadline helper is armed: the re-park did not stack a second timer for the same bound';
    ok $repark_err && ref($repark_err) && $repark_err->isa('Acme::Parataxis::Error::Timeout'),
        'the re-park was served by the reused helper (::Timeout), so it did not deadlock';
    ok $repark_at < 5000 && $repark_at > 400, "re-park resolved at ${repark_at}ms - by the ~700ms deadline helper, not instantly";
};
subtest 'a cancel scope and a with_timeout deadline coexist on one park' => sub {
    my ( $err, $done );
    async {
        my $ch  = Acme::Parataxis::Channel->new;
        my $tok = Acme::Parataxis::CancellationToken->new;
        fiber {
            $tok->register;
            $err = dies {

t/256_driver_mojo.t  view on Meta::CPAN

    my ( $err, $after );
    Acme::Parataxis::run(
        sub {
            $err = dies {
                with_timeout( 30, sub { await_read( $b, 2000 ) } );
            };
            $after = 'ran-on';
        }
    );
    Acme::Parataxis->detach_loop;
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'enclosing ::Timeout propagated';
    is $err->kind, 'timeout', 'kind is timeout';
    is $after,     'ran-on',  'the fiber continued after catching it';
};
subtest 'a driver sleep mixes with a concurrent pool job' => sub {
    Acme::Parataxis->attach_loop( Mojo::IOLoop->new );
    my ( $pool, $ms );
    my $t0 = time;
    Acme::Parataxis::run(
        sub {
            my $pw = fiber { await_sleep(20); 'pool-writer' };

t/257_driver_ioasync.t  view on Meta::CPAN

    my ( $err, $after );
    Acme::Parataxis::run(
        sub {
            $err = dies {
                with_timeout( 30, sub { await_read( $b, 4000 ) } );
            };
            $after = 'ran-on';
        }
    );
    Acme::Parataxis->detach_loop;
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'enclosing ::Timeout propagated';
    is $err->kind, 'timeout', 'kind is timeout';
    is $after,     'ran-on',  'the fiber continued after catching it';
};

# event-loop acceptance: high-volume readiness on the loop, and proof that the worker pool does none of it.
# Count every pool submission. _submit_job is the only gate onto submit_c_job (await_sleep, await_core_id,
# await_read and await_write all route through it) and run() never submits on its own, so a zero count while a
# loop is attached means no worker thread was ever asked to provide readiness or a sleep.
my $submits         = 0;
my $orig_submit_job = \&Acme::Parataxis::_submit_job;

t/301_rate_limiter.t  view on Meta::CPAN

        $parked_waiters = $rl->waiters;
        $f->await;
        $after_waiters = $rl->waiters;

        # The bucket must still be usable: a later acquire still collects a token when one is refilled.
        my $g = fiber { $rl->acquire(1); $later = 1 };
        $g->await;
        $rl->stop;
    };
    is $parked_waiters, 1, 'the acquire really was parked on the empty bucket when the deadline was armed';
    ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'the deadline threw Error::Timeout';
    is $after_waiters, 0, 'the interrupted waiter unregistered itself, so no later refill can wake a fiber that no longer wants a token';
    ok $later, 'the bucket still hands out tokens afterwards';
    is live_count(), $BASE, 'no fiber left behind';
};
subtest 'burst-vs-strict-rate: the burst is instant, the sustained rate is exactly rate' => sub {
    my ( $burst_ms, $steady_ms );
    async {
        my $rl = Acme::Parataxis::RateLimiter->new( rate => 50, burst => 20 );    # 20 instant, then 1 per 20ms
        my $t0 = time;
        $rl->acquire(1) for 1 .. 20;

t/302_mock_time.t  view on Meta::CPAN

    code    => sub {
        my $err;
        my $f = fiber {
            $err = dies {
                with_timeout( 3_600_000, sub { await_sleep( 3_600_000 * 2 ); 'ok' } );
            };
        };
        yield;
        Acme::Parataxis->advance(3_600_000);
        $f->await;    # deterministic: wait until the deadline has fired the block and the block has set $err
        ok ref($err) && $err->isa('Acme::Parataxis::Error::Timeout'), 'a 1h with_timeout fires under advance (inner 2h sleep did not beat it)';
        is Acme::Parataxis->virtual_now, 3_600_000, 'advance returned the bound in ms';
    }
);

# C) Ticker ticks on the virtual boundary (values are virtual seconds, not wall-clock epoch)
run(
    virtual => 1,
    code    => sub {
        my @ticks;
        my $t = Acme::Parataxis::Ticker->new( interval => 1000 );

t/302_mock_time.t  view on Meta::CPAN

            my $ch = Acme::Parataxis::Channel->new( capacity => 1, timeout => 50 );
            fiber {
                $got_err = dies { $ch->get };
                $done    = 1;
            };
            yield;
            Acme::Parataxis->advance(50);    # get has been empty for its whole 50ms bound
            my $guard = 0;
            yield while !$done && ++$guard < 50;
            ok $done,                                                             'get resumed after the bound';
            ok ref($got_err) && $got_err->isa('Acme::Parataxis::Error::Timeout'), 'a 50ms channel bound fired on advance';
        };
    }
);

# G) earliest virtual deadline fires first, and an hour apart the auto fast-forward walks both
run(
    virtual => 1,
    code    => sub {
        my @order;
        subtest 'earliest virtual deadline fires first' => sub {

t/353_stm.t  view on Meta::CPAN

                            $v->set( $x + 1 );
                            retry;    # park; the deadline must interrupt the txn
                            1;
                        };
                    }
                );
            };
        };
        $f->await;
    };
    ok ref($caught) && $caught->isa('Acme::Parataxis::Error::Timeout'), 'a timeout interrupts a retry-parked transaction';
    is $v->value, 1, 'the aborted transaction committed nothing';
};
subtest 'TVar / atomically / retry croak outside the right context' => sub {
    my $v = Acme::Parataxis::TVar->new( value => 1 );
    like dies { $v->get }, qr[TVar operations must occur inside a scheduled fiber], 'get() outside a fiber';
    like dies {
        atomically( sub {1} )
    }, qr[must be called from inside a scheduled fiber], 'atomically() outside a fiber';
    async {
        fiber {



( run in 2.139 seconds using v1.01-cache-2.11-cpan-234fa220139 )