| 1 | use v5.40; | ||
| 2 | no warnings qw[experimental::class experimental::try recursion]; | ||
| 3 | use feature 'class'; | ||
| 4 | # | ||
| 5 | # STM (software transactional memory). A TVar is a versioned mutable cell whose | ||
| 6 | # reads and writes only take effect through Acme::Parataxis->atomically. The transaction | ||
| 7 | # log lives on the calling fiber's Locals-stash (the same slot Acme::Parataxis::Local | ||
| 8 | # uses), keyed so it can never collide with a Local id: | ||
| 9 | # | ||
| 10 | # { reads => { refaddr => [ $tvar, $version ] }, # journaled reads (first read wins) | ||
| 11 | # writes => { refaddr => [ $tvar, $new_value ] },# staged writes (invisible until commit) | ||
| 12 | # reads_list => [ $tvar, ... ] } # first-read order, for retry parking | ||
| 13 | # | ||
| 14 | my $TXN_KEY = 'Acme::Parataxis::TVar:txn'; | ||
| 15 | my %RETRY_REGS; # fid => dereg: removes the fiber from every TVar's waiters list | ||
| 16 | # | ||
| 17 | class Acme::Parataxis::TVar v0.1.6 { | ||
| 18 | use Acme::Parataxis; | ||
| 19 | use Acme::Parataxis::Error; # for the internal STM_Retry control-flow exception | ||
| 20 | use Acme::Parataxis::Sync::Mutex; # the global commit lock | ||
| 21 | use builtin qw[refaddr]; | ||
| 22 | use Carp qw[croak]; | ||
| 23 | field $value : reader : param; # committed value | ||
| 24 | field $version : reader = 0; # bumped on every committed write; the conflict detector | ||
| 25 | field @waiters; # fids parked by retry() whose read sets include this TVar | ||
| 26 | |||
| 27 | # The current fiber's transaction log, or a croak when there is none. Every TVar | ||
| 28 | # operation (and retry()) runs strictly inside an atomically block. | ||
| 29 | method _txn () { | ||
| 30 | my $fid = Acme::Parataxis->current_fid; | ||
| 31 | croak 'TVar operations must occur inside a scheduled fiber' if $fid < 0; | ||
| 32 | my $stash = Acme::Parataxis::_fiber_locals( Acme::Parataxis->by_id($fid) ); | ||
| 33 | croak 'TVar operations must occur inside an atomically block' unless $stash->{$TXN_KEY}; | ||
| 34 | return $stash->{$TXN_KEY}; | ||
| 35 | } | ||
| 36 | |||
| 37 | # Read the committed value, journaling the read. Re-reading a TVar written earlier in | ||
| 38 | # the SAME transaction returns the transaction's own write (read-your-writes). | ||
| 39 | method get () { | ||
| 40 | my $txn = $self->_txn; | ||
| 41 | my $key = refaddr($self); | ||
| 42 | return $txn->{writes}{$key}[1] if exists $txn->{writes}{$key}; | ||
| 43 | if ( !exists $txn->{reads}{$key} ) { | ||
| 44 | $txn->{reads}{$key} = [ $self, $version ]; | ||
| 45 | push @{ $txn->{reads_list} }, $self; | ||
| 46 | } | ||
| 47 | return $value; | ||
| 48 | } | ||
| 49 | |||
| 50 | # Stage a write. The committed TVar is untouched until the outermost atomically | ||
| 51 | # commits, i.e. only once every journaled read still matches its version. | ||
| 52 | method set ($v) { | ||
| 53 | my $txn = $self->_txn; | ||
| 54 | $txn->{writes}{ refaddr($self) } = [ $self, $v ]; | ||
| 55 | return $v; | ||
| 56 | } | ||
| 57 | |||
| 58 | # The committed value, readable from anywhere (no transaction required). Use for | ||
| 59 | # inspection and tests; reads that participate in a transaction go through get(). | ||
| 60 | method waiters() { return scalar @waiters } # retry waiters parked on this TVar | ||
| 61 | method _add_waiter ($fid) { push @waiters, $fid; 1 } | ||
| 62 | |||
| 63 | method _remove_waiter ($fid) { # unregister a retry waiter (idempotent) | ||
| 64 | my $before = @waiters; | ||
| 65 | @waiters = grep { $_ != $fid } @waiters; | ||
| 66 | return $before - @waiters; | ||
| 67 | } | ||
| 68 | |||
| 69 | # Applied by a commit: publish the value, bump the version, wake every fiber parked by | ||
| 70 | # retry() on a read set that includes this TVar. Waking runs the unregister first so a | ||
| 71 | # fiber is never enqueued twice (once here, once by a second TVar committing later). | ||
| 72 | method _commit_value ($v) { | ||
| 73 | $value = $v; | ||
| 74 | $version++; | ||
| 75 | my @w = @waiters; | ||
| 76 | @waiters = (); | ||
| 77 | Acme::Parataxis::TVar::_wake_retry_waiter($_) for @w; | ||
| 78 | return 1; | ||
| 79 | } | ||
| 80 | |||
| 81 | # The transaction engine: Runs $code as one transaction on the calling fiber. Nested atomically calls join the | ||
| 82 | # outer transaction (no separate commit; retry() still aborts the whole thing). | ||
| 83 | sub _atomically ($cb) { | ||
| 84 | my $fid = Acme::Parataxis->current_fid; | ||
| 85 | croak 'atomically() must be called from inside a scheduled fiber' if $fid < 0; | ||
| 86 | my $fiber = Acme::Parataxis->by_id($fid); | ||
| 87 | my $stash = Acme::Parataxis::_fiber_locals($fiber); | ||
| 88 | my $want = wantarray; | ||
| 89 | if ( $stash->{$TXN_KEY} ) { | ||
| 90 | my @r; | ||
| 91 | if ($want) { @r = $cb->() } | ||
| 92 | else { $r[0] = $cb->() } | ||
| 93 | return $want ? @r : $r[0]; | ||
| 94 | } | ||
| 95 | my $txn = { reads => {}, writes => {}, reads_list => [] }; | ||
| 96 | $stash->{$TXN_KEY} = $txn; | ||
| 97 | my @r; | ||
| 98 | my $loop_ok = 1; | ||
| 99 | my $loop_err; | ||
| 100 | |||
| 101 | # The finally is load-bearing: the stash entry must be cleared on *every* exit, including | ||
| 102 | # the abort path where a real error (or an interrupt out of _park_on_reads) throws out of | ||
| 103 | # the loop, so a later atomically never inherits a stale transaction. | ||
| 104 | try { | ||
| 105 | while (1) { | ||
| 106 | my $run_ok = 1; | ||
| 107 | my $err; | ||
| 108 | |||
| 109 | # Note the shape: catch()'s own variable is scoped to the catch block, so the error | ||
| 110 | # has to be handed to the enclosing lexical *inside* the block or $err stays undef. | ||
| 111 | try { | ||
| 112 | if ($want) { @r = $cb->() } | ||
| 113 | else { $r[0] = $cb->() } | ||
| 114 | } | ||
| 115 | catch ($caught) { $run_ok = 0; $err = $caught } | ||
| 116 | if ($run_ok) { | ||
| 117 | last if Acme::Parataxis::TVar::_commit($txn); | ||
| 118 | _wipe($txn); # commit conflict: rerun from a clean slate | ||
| 119 | next; | ||
| 120 | } | ||
| 121 | if ( ref($err) && $err->isa('Acme::Parataxis::Error::STM_Retry') ) { | ||
| 122 | Acme::Parataxis::TVar::_park_on_reads($txn); | ||
| 123 | _wipe($txn); | ||
| 124 | next; | ||
| 125 | } | ||
| 126 | die $err; # any real error: abort the transaction, surface it unchanged | ||
| 127 | } | ||
| 128 | } | ||
| 129 | catch ($caught) { $loop_ok = 0; $loop_err = $caught } | ||
| 130 | finally { delete $stash->{$TXN_KEY} } | ||
| 131 | die $loop_err unless $loop_ok; | ||
| 132 | return $want ? @r : $r[0]; | ||
| 133 | } | ||
| 134 | |||
| 135 | # Commit under the global commit lock: every journaled read must still carry the version | ||
| 136 | # it had when read, then the write set is flushed (each TVar bumps its version and wakes | ||
| 137 | # its retry waiters). A stale read discards the transaction and reports a conflict. | ||
| 138 | # The commit never yields, so the lock is uncontended in the cooperative scheduler; a | ||
| 139 | # parked-wait behind it is the honest fallback if the executor ever goes parallel. | ||
| 140 | sub _commit ($txn) { | ||
| 141 | state $lock = Acme::Parataxis::Sync::Mutex->new; | ||
| 142 | $lock->lock; | ||
| 143 | my $ok = 1; | ||
| 144 | for my $key ( keys %{ $txn->{reads} } ) { | ||
| 145 | my ( $tv, $v ) = @{ $txn->{reads}{$key} }; | ||
| 146 | if ( $v != $tv->version ) { $ok = 0; last } | ||
| 147 | } | ||
| 148 | if ($ok) { | ||
| 149 | for my $key ( keys %{ $txn->{writes} } ) { | ||
| 150 | my ( $tv, $v ) = @{ $txn->{writes}{$key} }; | ||
| 151 | $tv->_commit_value($v); | ||
| 152 | } | ||
| 153 | } | ||
| 154 | $lock->unlock; | ||
| 155 | return $ok; | ||
| 156 | } | ||
| 157 | |||
| 158 | # Parks the fiber on the transaction's read set until any of those TVars changes, then | ||
| 159 | # returns so _atomically can re-run the block with a fresh log. The deregistration | ||
| 160 | # passed to _park removes the fiber from every TVar's waiter list on an interrupt, so a | ||
| 161 | # cancelled transaction never leaves a stale fid that a later commit could wake. | ||
| 162 | sub _park_on_reads ($txn) { | ||
| 163 | my $fid = Acme::Parataxis->current_fid; | ||
| 164 | my @tv = @{ $txn->{reads_list} }; | ||
| 165 | croak 'retry with an empty read set would never wake; read at least one TVar before retry()' if !@tv; | ||
| 166 | $_->_add_waiter($fid) for @tv; | ||
| 167 | my $dereg = sub { $_->_remove_waiter($fid) for @tv }; | ||
| 168 | $RETRY_REGS{$fid} = $dereg; | ||
| 169 | my $ok = 1; | ||
| 170 | my $err; | ||
| 171 | try { Acme::Parataxis::_park( 'STM retry', 3, $dereg ) } | ||
| 172 | catch ($caught) { $ok = 0; $err = $caught } | ||
| 173 | |||
| 174 | # Both cleanups must run even when the park throws (an interrupt), or a cancelled | ||
| 175 | # transaction would leave a stale fid on every TVar in its read set. | ||
| 176 | finally { | ||
| 177 | delete $RETRY_REGS{$fid}; | ||
| 178 | $dereg->(); # a commit wake already unregistered; strip any lists that did not change (idempotent) | ||
| 179 | } | ||
| 180 | die $err unless $ok; # interrupt (timeout/cancel): the transaction aborts | ||
| 181 | return; | ||
| 182 | } | ||
| 183 | |||
| 184 | # Wakes a retry-parked fiber once: unregisters it from every TVar's waiters list, then | ||
| 185 | # enqueues it. The unregister keeps a single commit from turning into multiple wakes. | ||
| 186 | sub _wake_retry_waiter ($fid) { | ||
| 187 | return unless defined Acme::Parataxis->by_id($fid); | ||
| 188 | if ( my $dereg = delete $RETRY_REGS{$fid} ) { $dereg->() } | ||
| 189 | Acme::Parataxis::_scheduler_enqueue_by_id($fid); | ||
| 190 | } | ||
| 191 | |||
| 192 | # The retry() implementation: aborts the current transaction. The STM_Retry exception | ||
| 193 | # is caught by _atomically, which parks on the read set and re-runs the block. | ||
| 194 | sub _retry () { | ||
| 195 | my $fid = Acme::Parataxis->current_fid; | ||
| 196 | croak 'retry() must be called from inside a scheduled fiber' if $fid < 0; | ||
| 197 | my $stash = Acme::Parataxis::_fiber_locals( Acme::Parataxis->by_id($fid) ); | ||
| 198 | croak 'retry() must be called from inside an atomically block' unless $stash->{$TXN_KEY}; | ||
| 199 | die Acme::Parataxis::Error::STM_Retry->new; | ||
| 200 | } | ||
| 201 | sub _wipe ($txn) { $txn->{reads} = {}; $txn->{writes} = {}; $txn->{reads_list} = []; } | ||
| 202 | }; | ||
| 203 | # | ||
| 204 | 1; |