diff --git a/AGENTS.md b/AGENTS.md index 091c713..3f9a978 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -119,6 +119,16 @@ shared struct before it aborts* — siblings then read plausible garbage with no (native-php-coroutines#24). Touch the block once, in the creating process, before the fork: it does not add memory, it decides when the memory is charged, and afterwards a climb really is a climb. +- **Recycling is in-place reuse, never a free.** A fixed-record table may hand a record back out + — `Ipc\ResultSlotTable` does, through a free list threaded through the slot records themselves + — but the block stays where it is and nothing is unmapped, so the rule above is untouched. A + recycled record needs an **identity that changes with it**: without the generation in + `Ipc\SlotTicket`, an id held one moment too long addresses the next occupant and is answered + with its data. Every verb re-checks that generation; a mismatch is a typed refusal naming both. + Recycling does **not** make the prefault above redundant, and the two must not be confused: a + steady-state pool reuses a handful of records and would look page-flat by accident, while a + workload whose concurrency genuinely grows still walks into fresh records. The prefault is what + makes that second case flat too, so residency stops being a function of the workload at all. - Gate memory claims with the soaks, and watch the **watermark plateau** rather than the peak: ```bash @@ -136,8 +146,11 @@ that refusal is the feature; never soften it into a migration. Keep the **version history table in `Registry`'s docblock current**: one line per version, saying what changed and why a reader of the older layout would be wrong. A consumer structure that merely lives in the arena payload and adds no field to a registry record does **not** bump -the version (`Ipc\SharedChannel`, `Ipc\SharedArray`, `Ipc\ClosureProvenance`); it publishes -itself in the roots directory instead. +the version (`Ipc\SharedChannel`, `Ipc\SharedArray`, `Ipc\ClosureProvenance`, +`Ipc\ResultSlotTable`); it publishes itself in the roots directory instead. Such a structure +carries its **own** guard when its record shape changes — `ResultSlotTable::FORMAT` is one, a +header word checked at `attach()` — because "does not bump `LAYOUT_VERSION`" must not mean +"changes shape with nothing refusing a reader of the old one". ## 8. Frozen-mode invariants that must survive every change diff --git a/README.md b/README.md index 0baa1fd..2ab8a44 100644 --- a/README.md +++ b/README.md @@ -332,7 +332,7 @@ $wake = WakeRegistry::create($arena); // socket pairs, created $jobs = SharedChannel::create($allocator, $codec, $wake, 64, name: 'jobs'); $results = ResultSlotTable::create($allocator, $codec, $wake, 1024); -$slot = $results->allocateSlot(); +$slot = $results->allocateSlot(); // a TICKET: slot index + generation if (pcntl_fork() === 0) { [$job, $ok] = $jobs->recv(); // parks on the socket, wakes on an event $results->complete($slot, process($job)); // writes a record, pokes the waiter @@ -340,8 +340,19 @@ if (pcntl_fork() === 0) { } $jobs->send($sharedObject); // an address, never a copy $value = $results->await($slot)->value; // read straight out of shared memory +$results->releaseSlot($slot); // read and done with: back on the free list ``` +**Slots are recycled, and a slot id is a ticket rather than an index.** The arena is bump-only +and nothing frees a block, so `releaseSlot()` reuses the slot *record in place* through a free +list threaded through the slots themselves. What makes that safe is the generation packed +beside the index in every id (`Ipc\SlotTicket`, 16 bits each, so the whole thing still fits the +uint32 a wake event carries): the generation moves the instant an owner releases its claim, and +reading, awaiting, completing or releasing a slot with an out-of-date ticket is an +`IpcException` naming the slot and both generations — never another task's result. A slot +nobody releases simply stays out of circulation, and a slot whose 16-bit generation is used up +is retired rather than wrapped, so no handle is ever revived by a counter coming back round. + Values move as **16-byte records**: `uint8 tag | 7 pad | uint64 payload`, where the payload is the value itself (`int`, `float`, nothing at all for `null`/`bool`) or an arena address (an interned `zend_string`, a shared `zend_object`, a `SharedArray`, the record of a shared @@ -361,7 +372,7 @@ lost, and every blocking loop also re-polls on a bounded slice. |---|---| | `SharedChannel` | ring of records + waiter tables under a dedicated robust mutex; capacity 0 is a true cross-process rendezvous; `close()` crosses processes (receivers drain, then `[null, false]`; senders throw) | | `SharedArray` | fixed-capacity vector of records, `ArrayAccess`/`Countable`/`IteratorAggregate`, stripe-locked | -| `ResultSlotTable` | futures: `allocateSlot()` / `complete()` / `completePanic()` / `await()`, with panics travelling as a shared `SharedError` object | +| `ResultSlotTable` | futures: `allocateSlot()` / `complete()` / `completePanic()` / `await()` / `releaseSlot()`, ids carrying a generation so a recycled slot never answers an old handle, and panics travelling as a shared `SharedError` object | | `SharedMutex` | robust process-shared mutex with trylock-and-backoff, `EOWNERDEAD` recovered and reported | | `AtomicInt` | one shared cell: plain aligned get/set, stripe-locked `add()`/`compareAndSet()` | | `SharedWaitGroup` | counter plus waiter table; `add()`/`done()`/`wait()`, negative counts throw | @@ -480,9 +491,11 @@ $channel->recv($timeout): array; // [value, true] | [null, $channel->close(): void; // crosses processes, drains first $channel->notificationStream(); // park your own event loop on this $slots = ResultSlotTable::create($allocator, $codec, $wake, $capacity); -$slots->allocateSlot(): int; -$slots->complete($id, $value): void; // completePanic($id, SharedError::capture(...)) -$slots->await($id, $timeout): SlotResult; // readSlot() never blocks +$slots->allocateSlot(): int; // a ticket: SlotTicket::indexOf()/generationOf() +$slots->complete($ticket, $value): void; // completePanic($ticket, SharedError::capture(...)) +$slots->await($ticket, $timeout): SlotResult; // readSlot() never blocks +$slots->releaseSlot($ticket): void; // settled + read => back on the free list +$slots->outstanding(); $slots->highWaterMark(); // what a soak watches plateau // shared closures (registration is the acceptance test; everything else is refused) $closures = ClosureProvenance::create($allocator, $store); // pre-fork diff --git a/docs/shared-memory-model.md b/docs/shared-memory-model.md index d4173b7..18c6b2b 100644 --- a/docs/shared-memory-model.md +++ b/docs/shared-memory-model.md @@ -265,8 +265,13 @@ sentence. cross-process rendezvous; `close()` crosses processes; - `SharedArray` — fixed-capacity vector of records, per-instance stripe: the container a `zend_array` cannot be (§4); -- `ResultSlotTable` — futures. A slot settles exactly once, carrying either a value record or - a `SharedError` (a persisted three-string object; a `Throwable` can never be shared); +- `ResultSlotTable` — futures. A slot settles exactly once **per generation**, carrying either + a value record or a `SharedError` (a persisted three-string object; a `Throwable` can never be + shared). Slots are **recycled in place** through a free list threaded through the slot records + — nothing is freed, because nothing here ever can be (§6) — and a slot id is a `SlotTicket`, + index and generation packed into the 32 bits a wake event has for it. Every verb checks the + generation, so a handle outliving its release is refused by name instead of being handed the + next task's answer; - `SharedMutex` / `AtomicInt` / `SharedWaitGroup` — robust locking, an aligned word with stripe-locked read-modify-write (FFI has no CAS), and a counter with waiters; - `ClosureProvenance` — the register of closures the family may invoke by address. It stores diff --git a/src/Ipc/IpcException.php b/src/Ipc/IpcException.php index d50b56c..20a83a6 100644 --- a/src/Ipc/IpcException.php +++ b/src/Ipc/IpcException.php @@ -44,26 +44,115 @@ public static function wakeRegistryNotInherited(): self ); } - public static function slotTableFull(int $capacity): self + public static function slotTableFull(int $capacity, int $outstanding, int $retired): self { return new self(sprintf( - 'All %d result slots are used. The slot table is pre-sized in the arena and never grows; ' . - 'create it with a larger capacity before the workers fork.', + 'All %d result slots are in use (%d outstanding, %d retired). Slots are recycled through ' . + 'a free list, so a slot only comes back when its owner calls releaseSlot() - a handle ' . + 'that is never awaited never gives its slot back. Either release what is settled, or ' . + 'pre-size the table larger before the workers fork; it is allocated in the arena and ' . + 'never grows.', $capacity, + $outstanding, + $retired, )); } - public static function unknownSlot(int $id, int $capacity): self + public static function unknownSlot(int $index, int $capacity): self { - return new self(sprintf('Result slot %d does not exist; the table holds slots 0..%d', $id, $capacity - 1)); + return new self(sprintf( + 'Result slot %d does not exist; the table holds slots 0..%d', + $index, + $capacity - 1, + )); + } + + /** + * A handle that names a slot the table has already handed to somebody else + * + * This is the whole safety property of recycling: a slot id is only half a claim, and the + * generation is the other half. Answering such a handle with the slot's current contents + * would hand one task's result to another task's waiter, silently and plausibly. + */ + public static function staleSlot(int $index, int $held, int $current): self + { + return new self(sprintf( + 'Result slot %d is at generation %d and this handle holds generation %d: the slot was ' . + 'released and handed to another task. A recycled slot never answers an older handle - ' . + 'read the result before releasing it, and do not keep the id afterwards.', + $index, + $current, + $held, + )); + } + + /** + * A slot that has been used up: its generation counter reached the end of the ticket layout + */ + public static function slotRetired(int $index): self + { + return new self(sprintf( + 'Result slot %d is retired: its generation counter reached the end of the 16 bits a slot ' . + 'ticket carries, so the slot was taken out of circulation instead of wrapping round to a ' . + 'generation an old handle could match.', + $index, + )); + } + + public static function slotAlreadyCompleted(int $index, int $generation): self + { + return new self(sprintf( + 'Result slot %d is already completed in generation %d. A slot is written exactly once per ' . + 'generation - allocate a new one for the next result rather than reusing a settled slot.', + $index, + $generation, + )); + } + + /** + * A release of a slot whose answer has not been written yet + * + * Recycling a pending slot would hand a live record to the next task while the process that + * owes the answer is still going to write it - the one way this design could return another + * task's result. Refusing is the only correct answer. + */ + public static function slotNotSettled(int $index): self + { + return new self(sprintf( + 'Result slot %d is still pending and cannot be released: the process that owes its answer ' . + 'may still write it, and recycling the slot now would let that write land on another ' . + 'task. Release a slot only once it has settled and its result has been read.', + $index, + )); + } + + public static function capacityTooLarge(string $structure, int $capacity, int $maximum): self + { + return new self(sprintf( + '%s capacity is %d, above the %d a slot ticket can address: an id carries the slot index ' . + 'and its generation in the 32 bits a wake event has for it, and a wider table would ' . + 'truncate ids rather than fail', + $structure, + $capacity, + $maximum, + )); } - public static function slotAlreadyCompleted(int $id): self + /** + * A table in the arena whose record shape is not the one this build reads + * + * `ResultSlotTable` is a consumer structure published in the roots directory, so it does not + * ride `Registry::LAYOUT_VERSION`; this word is its own guard, and it exists because reading + * the wrong slot geometry at the right address is silent rather than fatal. + */ + public static function slotTableFormat(int $found, int $expected): self { return new self(sprintf( - 'Result slot %d is already completed. A slot is written exactly once - allocate a new one ' . - 'for the next result rather than reusing a settled slot.', - $id, + 'The result slot table in the arena is format %d and this build reads format %d. Slots ' . + 'are addressed by offset, so a mismatched shape is read at the right address with the ' . + 'wrong meaning - the whole family has to run one build of this package.', + $found, + $expected, )); } diff --git a/src/Ipc/ResultSlotTable.php b/src/Ipc/ResultSlotTable.php index e9b1ee1..cc54660 100644 --- a/src/Ipc/ResultSlotTable.php +++ b/src/Ipc/ResultSlotTable.php @@ -22,25 +22,60 @@ * This is the piece the runtime model of EPIC #15 is built on. A coroutine finishing * ANYWHERE in the process tree writes its return value into its slot as a 16-byte record, * and the process waiting for it - very likely a different one - is told over its - * notification socket with a fixed event record `{RESULT, slot id, tag, address}`. It then + * notification socket with a fixed event record `{RESULT, slot ticket, tag, address}`. It then * reads the value straight out of shared memory. The socket never carries the value: for an * INT or FLOAT the event's address field is zero, and for a string, object or shared array * it holds an ADDRESS every process maps identically. * * ```text - * header (4 words) capacity | next slot | mutex address | reserved - * slot (8 words) state | tag | payload | waiters parked | waiter table (4 entries) + * header (8 words) capacity | next | mutex | format | free head | live | recycled | retired + * slot (12 words) state | tag | payload | parked | generation | next free | 2 spare + * | waiter table (4 entries) * ``` * - * A slot settles exactly once: complete() and completePanic() refuse a slot that is already - * DONE or PANIC, which is what makes "read the record after seeing the state" a safe - * sequence rather than a race with a second writer. Slots are handed out by a bump counter - * and never recycled in v1 - the table is pre-sized before the fork, like everything else in - * the arena, and exhausting it is a typed failure that names the knob. + * A slot settles exactly once **per generation**: complete() and completePanic() refuse a slot + * that is already DONE or PANIC, which is what makes "read the record after seeing the state" a + * safe sequence rather than a race with a second writer. * * The same machinery carries spawn ARGUMENTS in the opposite direction: a slot completed by * the spawning process before the worker looks at it is a one-shot value handed downwards - * with the identical tag contract. + * with the identical tag contract - and it is released and recycled exactly like a result. + * + * ## Slots are recycled, and a generation is what makes that safe + * + * The arena is a bump allocator and **children never free arena memory**, so recycling a slot + * can never mean giving its bytes back: the slot record is reused **in place**. What comes back + * is the *right to use it*, tracked in a free list threaded through the slots themselves - one + * header word for the head, one word per slot for the link, no allocation anywhere. + * + * The hazard recycling creates is that a slot id stops being a unique name. A handle held past + * the moment its slot went back on the free list would address whatever task got the slot next, + * and would be answered with that task's result - the exact silent-wrong-answer this package + * exists to refuse. So an id is not an index: it is a {@see SlotTicket}, index and generation + * packed into the 32 bits a {@see WakeEvent} carries, and **every verb checks the generation it + * was handed against the one in the slot**. A mismatch is `IpcException`, naming the slot and + * both generations. Reading, awaiting, completing and releasing all fail the same way. + * + * The generation moves at **release**, not at reuse: the moment an owner gives up its claim is + * the moment the claim has to stop being answerable, and a slot that sits on the free list for a + * while must not keep answering the handle that put it there. A generation is 16 bits and it + * **never wraps** - a slot whose counter reaches {@see SlotTicket::MAX_GENERATION} is *retired* + * (stamped generation 0 and left off the free list) rather than started over, so no handle can + * ever be revived by a counter coming back round. Retirement costs one slot out of the supply + * after 65 535 uses of it, which is the ordinary leak-until-teardown bargain of this arena. + * + * ## Who releases, and when + * + * {@see self::releaseSlot()} is the consumer's signal that a settled slot has been read by + * everybody who was going to read it. This package does not guess at that: it refuses to + * release a slot that has not settled ({@see IpcException::slotNotSettled()}), and otherwise + * takes the caller at its word. The common case is one owner per slot - the process that + * allocated it and awaits its result - and a second process that attaches to somebody else's + * slot has to finish reading before the owner releases, or its next read fails loudly rather + * than quietly returning the wrong task's answer. + * + * A slot nobody releases simply stays out of circulation, which is exactly the behaviour this + * table had before recycling existed. */ final class ResultSlotTable { @@ -51,19 +86,36 @@ final class ResultSlotTable */ public const int SLOT_WAITERS = 4; + /** + * The record shape this build reads, checked at attach() + * + * `ResultSlotTable` is a consumer structure published in the roots directory, so it does not + * ride `Registry::LAYOUT_VERSION` (AGENTS.md §7). This word is its own guard: a table written + * by a build with a different slot geometry is refused instead of read at the right address + * with the wrong meaning. Bump it in the same commit as any change to the words below. + */ + public const int FORMAT = 2; + private const float WAIT_SLICE = 0.05; private const int WORD_CAPACITY = 0; private const int WORD_NEXT = 1; private const int WORD_MUTEX = 2; - private const int HEADER_WORDS = 4; - - private const int SLOT_WORD_STATE = 0; - private const int SLOT_WORD_TAG = 1; - private const int SLOT_WORD_PAYLOAD = 2; - private const int SLOT_WORD_PARKED = 3; - private const int SLOT_WORD_WAITERS = 4; - private const int SLOT_WORDS = 8; + private const int WORD_FORMAT = 3; + private const int WORD_FREE = 4; + private const int WORD_LIVE = 5; + private const int WORD_RECYCLED = 6; + private const int WORD_RETIRED = 7; + private const int HEADER_WORDS = 8; + + private const int SLOT_WORD_STATE = 0; + private const int SLOT_WORD_TAG = 1; + private const int SLOT_WORD_PAYLOAD = 2; + private const int SLOT_WORD_PARKED = 3; + private const int SLOT_WORD_GENERATION = 4; + private const int SLOT_WORD_NEXT_FREE = 5; + private const int SLOT_WORD_WAITERS = 8; + private const int SLOT_WORDS = 12; private readonly Arena $arena; @@ -83,8 +135,14 @@ private function __construct( if (!$this->arena->contains($address, self::HEADER_WORDS * 8)) { throw IpcException::notShared('result slot table', $address); } - $this->capacity = $this->arena->readWord($address + self::WORD_CAPACITY * 8); - $this->mutex = $this->arena->readWord($address + self::WORD_MUTEX * 8); + + $format = (int) $this->arena->readWord($address + self::WORD_FORMAT * 8); + if ($format !== self::FORMAT) { + throw IpcException::slotTableFormat($format, self::FORMAT); + } + + $this->capacity = (int) $this->arena->readWord($address + self::WORD_CAPACITY * 8); + $this->mutex = (int) $this->arena->readWord($address + self::WORD_MUTEX * 8); } /** @@ -100,20 +158,27 @@ public static function create( if ($capacity <= 0) { throw IpcException::invalidCapacity('Result slot table', $capacity); } + if ($capacity > SlotTicket::MAX_SLOTS) { + throw IpcException::capacityTooLarge('Result slot table', $capacity, SlotTicket::MAX_SLOTS); + } $arena = $allocator->arena(); $size = (self::HEADER_WORDS + $capacity * self::SLOT_WORDS) * 8; $address = $arena->allocate($size, 64); $mutex = $arena->allocateMutex(); - // Pre-sized means pre-sized. Slots are handed out one at a time for the whole life of the - // run, so without this the table's pages fault in one per eight slots and the family's RSS - // climbs with the workload while the arena watermark - correctly - never moves. That is - // indistinguishable from a leak to any memory gate, and it was reported as one - // (native-php-coroutines#24). Creation happens before the fork, so the cost is paid once. + // Pre-sized means pre-sized. Slots are handed out one record at a time for the whole life + // of the run, so without this the table's pages fault in a few dozen slots at a time and + // the family's RSS climbs with the workload while the arena watermark - correctly - never + // moves. That is indistinguishable from a leak to any memory gate, and it was reported as + // one (native-php-coroutines#24). Creation happens before the fork, so the cost is paid + // once. Recycling does not replace this: a steady workload reuses a handful of records and + // would look flat by accident, while one whose concurrency really grows still reaches + // records nothing has touched. $arena->prefault($address, $size); $arena->writeWord($address + self::WORD_CAPACITY * 8, $capacity); $arena->writeWord($address + self::WORD_MUTEX * 8, $mutex); + $arena->writeWord($address + self::WORD_FORMAT * 8, self::FORMAT); if ($name !== null) { $arena->putRoot($name, $address); @@ -153,6 +218,53 @@ public function capacity(): int return $this->capacity; } + /** + * Slots handed out and not yet released - what a steady-state workload should plateau at + * + * Read without the lock on purpose: a single aligned 8-byte load never tears (EPIC #15, + * correction #2), and a diagnostic that took the table mutex would serialize every reader + * against every allocation for a number that is a snapshot either way. + */ + public function outstanding(): int + { + return (int) $this->arena->readWord($this->address + self::WORD_LIVE * 8); + } + + /** + * Distinct slots the bump cursor has ever created - the table's high-water mark + * + * With recycling this is the number of slots a workload really needed at once. It is the + * series a soak watches: consumption climbing means slots are not coming back. + */ + public function highWaterMark(): int + { + return (int) $this->arena->readWord($this->address + self::WORD_NEXT * 8); + } + + /** + * How many times a released slot has been handed out again + */ + public function recycled(): int + { + return (int) $this->arena->readWord($this->address + self::WORD_RECYCLED * 8); + } + + /** + * Slots taken out of circulation because their generation counter was used up + */ + public function retired(): int + { + return (int) $this->arena->readWord($this->address + self::WORD_RETIRED * 8); + } + + /** + * Slots that could still be handed out: never-used ones plus everything on the free list + */ + public function available(): int + { + return $this->capacity - $this->outstanding() - $this->retired(); + } + /** * The descriptor a scheduler parks on while awaiting slots * @@ -169,79 +281,154 @@ public function wasLockRecovered(): bool } /** - * Takes the next free slot; the id is what travels to whoever will complete it + * Takes a slot and returns the ticket for it: the id that travels to whoever will complete it + * + * A recycled slot is preferred over a fresh one - the free list is a LIFO stack, so the slot + * that came back most recently goes out first and a steady workload keeps reusing a handful of + * records. Only when nothing is on the list does the bump cursor move, which is what makes the + * high-water mark a real measure of concurrency rather than of throughput. */ public function allocateSlot(): int { $recovered = $this->arena->lockMutexAt($this->mutex); - $next = $this->arena->readWord($this->address + self::WORD_NEXT * 8); - $fits = $next < $this->capacity; - if ($fits) { - $this->arena->writeWord($this->address + self::WORD_NEXT * 8, $next + 1); + $index = $this->popFreeSlot(); + $generation = 0; + + if ($index === null) { + $next = (int) $this->arena->readWord($this->address + self::WORD_NEXT * 8); + if ($next < $this->capacity) { + $index = $next; + $generation = 1; + $this->arena->writeWord($this->address + self::WORD_NEXT * 8, $next + 1); + $this->arena->writeWord($this->slotAt($index) + self::SLOT_WORD_GENERATION * 8, $generation); + } + } else { + $generation = (int) $this->arena->readWord($this->slotAt($index) + self::SLOT_WORD_GENERATION * 8); + } + + if ($index !== null) { + $slot = $this->slotAt($index); + $this->clearSlotRecord($slot); + $this->arena->writeWord($slot + self::SLOT_WORD_STATE * 8, ResultState::Pending->value); + $this->bumpHeader(self::WORD_LIVE, 1); } + $outstanding = (int) $this->arena->readWord($this->address + self::WORD_LIVE * 8); + $retired = (int) $this->arena->readWord($this->address + self::WORD_RETIRED * 8); + $this->arena->unlockMutexAt($this->mutex); $this->recoveredLock = $this->recoveredLock || $recovered; - if (!$fits) { - throw IpcException::slotTableFull($this->capacity); + if ($index === null) { + throw IpcException::slotTableFull($this->capacity, $outstanding, $retired); } - return $next; + return SlotTicket::pack($index, $generation); + } + + /** + * Gives a settled, fully read slot back to the free list under a new generation + * + * The caller is asserting that nobody will read this slot through this ticket again. That is + * the one thing this table cannot check for itself - a waiter in another process is invisible + * from here - so the guarantee is made from the other end instead: the generation moves now, so + * anybody who *does* come back is refused by name rather than answered with the next task's + * result. + * + * The whole slot record is wiped, waiter table included. A process still parked inside + * {@see self::await()} on the old generation therefore finds nothing of its own left; it fails + * the generation check on its next pass and never writes into the recycled record, because + * unparking re-checks the generation under the same lock. + */ + public function releaseSlot(int $ticket): void + { + $slot = $this->slotAddress($ticket); + $index = SlotTicket::indexOf($ticket); + $want = SlotTicket::generationOf($ticket); + + $recovered = $this->arena->lockMutexAt($this->mutex); + + $current = (int) $this->arena->readWord($slot + self::SLOT_WORD_GENERATION * 8); + $state = (int) $this->arena->readWord($slot + self::SLOT_WORD_STATE * 8); + $stale = $current !== $want; + $settled = $state === ResultState::Done->value || $state === ResultState::Panic->value; + + if (!$stale && $settled) { + $this->recycle($index, $slot, $current); + } + + $this->arena->unlockMutexAt($this->mutex); + + $this->recoveredLock = $this->recoveredLock || $recovered; + + if ($stale) { + throw $this->staleFailure($index, $want, $current); + } + if (!$settled) { + throw IpcException::slotNotSettled($index); + } } /** * Settles a slot with a value and wakes whoever is awaiting it */ - public function complete(int $id, mixed $value): void + public function complete(int $ticket, mixed $value): void { // Encoded before the lock: interning a string allocates arena memory and a // non-shareable value must throw without a lock ever being taken [$tag, $payload] = $this->codec->encode($value); - $this->settle($id, ResultState::Done, $tag, $payload, WakeOpcode::Result); + $this->settle($ticket, ResultState::Done, $tag, $payload, WakeOpcode::Result); } /** * Settles a slot with the address of a shared error-info object (see SharedError) */ - public function completePanic(int $id, int $errorAddress): void + public function completePanic(int $ticket, int $errorAddress): void { if (!$this->arena->contains($errorAddress, 8)) { throw NotShareableValueException::foreignAddress($errorAddress); } - $this->settle($id, ResultState::Panic, ValueTag::Obj, $errorAddress, WakeOpcode::Panic); + $this->settle($ticket, ResultState::Panic, ValueTag::Obj, $errorAddress, WakeOpcode::Panic); } /** * Reads a slot as it stands right now, without waiting */ - public function readSlot(int $id): SlotResult + public function readSlot(int $ticket): SlotResult { - $slot = $this->slotAddress($id); + $slot = $this->slotAddress($ticket); + $index = SlotTicket::indexOf($ticket); + $want = SlotTicket::generationOf($ticket); $recovered = $this->arena->lockMutexAt($this->mutex); - $state = $this->arena->readWord($slot + self::SLOT_WORD_STATE * 8); - $tag = $this->arena->readWord($slot + self::SLOT_WORD_TAG * 8); - $payload = $this->arena->readWord($slot + self::SLOT_WORD_PAYLOAD * 8); + $current = (int) $this->arena->readWord($slot + self::SLOT_WORD_GENERATION * 8); + $stale = $current !== $want; + $state = (int) $this->arena->readWord($slot + self::SLOT_WORD_STATE * 8); + $tag = (int) $this->arena->readWord($slot + self::SLOT_WORD_TAG * 8); + $payload = (int) $this->arena->readWord($slot + self::SLOT_WORD_PAYLOAD * 8); $this->arena->unlockMutexAt($this->mutex); $this->recoveredLock = $this->recoveredLock || $recovered; + if ($stale) { + throw $this->staleFailure($index, $want, $current); + } + $state = ResultState::from($state); if ($state === ResultState::Pending) { - return new SlotResult($id, $state); + return new SlotResult($ticket, $state); } $valueTag = ValueTag::from($tag); // Materialized outside the lock: attaching an object registers it in this request's // object store, which is an engine call that allocates - return new SlotResult($id, $state, $this->codec->decode($valueTag, $payload), $valueTag); + return new SlotResult($ticket, $state, $this->codec->decode($valueTag, $payload), $valueTag); } /** @@ -249,24 +436,28 @@ public function readSlot(int $id): SlotResult * * @param float|null $timeout Seconds to wait; null waits forever */ - public function await(int $id, ?float $timeout = null): SlotResult + public function await(int $ticket, ?float $timeout = null): SlotResult { - $slot = $this->slotAddress($id); + $slot = $this->slotAddress($ticket); + $index = SlotTicket::indexOf($ticket); + $want = SlotTicket::generationOf($ticket); $deadline = $timeout === null ? null : microtime(true) + $timeout; $wakeSlot = $this->wake->slot(); $waiters = new WaiterTable($this->arena, $slot + self::SLOT_WORD_WAITERS * 8, self::SLOT_WAITERS); while (true) { - $result = $this->readSlot($id); + $result = $this->readSlot($ticket); if (!$result->isPending()) { return $result; } $recovered = $this->arena->lockMutexAt($this->mutex); + $current = (int) $this->arena->readWord($slot + self::SLOT_WORD_GENERATION * 8); + $stale = $current !== $want; $settled = $this->arena->readWord($slot + self::SLOT_WORD_STATE * 8) !== ResultState::Pending->value; $entry = null; - if (!$settled) { + if (!$stale && !$settled) { // Registered and re-checked under ONE lock: a completion after this point // necessarily sees the entry, so no wakeup can be lost $entry = $waiters->register($wakeSlot); @@ -277,6 +468,10 @@ public function await(int $id, ?float $timeout = null): SlotResult $this->recoveredLock = $this->recoveredLock || $recovered; + if ($stale) { + throw $this->staleFailure($index, $want, $current); + } + if (!$settled) { if ($deadline === null) { $this->wake->wait(self::WAIT_SLICE); @@ -286,11 +481,11 @@ public function await(int $id, ?float $timeout = null): SlotResult $this->wake->wait(min($remaining, self::WAIT_SLICE)); } } - $this->unpark($slot, $waiters, $entry); + $this->unpark($slot, $want, $waiters, $entry); } if ($deadline !== null && microtime(true) >= $deadline) { - return $this->readSlot($id); + return $this->readSlot($ticket); } } } @@ -298,15 +493,19 @@ public function await(int $id, ?float $timeout = null): SlotResult /** * Writes the record, flips the state and notifies the parked waiters */ - private function settle(int $id, ResultState $state, ValueTag $tag, int $payload, WakeOpcode $opcode): void + private function settle(int $ticket, ResultState $state, ValueTag $tag, int $payload, WakeOpcode $opcode): void { - $slot = $this->slotAddress($id); + $slot = $this->slotAddress($ticket); + $index = SlotTicket::indexOf($ticket); + $want = SlotTicket::generationOf($ticket); $waiters = new WaiterTable($this->arena, $slot + self::SLOT_WORD_WAITERS * 8, self::SLOT_WAITERS); $recovered = $this->arena->lockMutexAt($this->mutex); + $current = (int) $this->arena->readWord($slot + self::SLOT_WORD_GENERATION * 8); + $stale = $current !== $want; $settled = $this->arena->readWord($slot + self::SLOT_WORD_STATE * 8) !== ResultState::Pending->value; - if (!$settled) { + if (!$stale && !$settled) { $this->arena->writeWord($slot + self::SLOT_WORD_TAG * 8, $tag->value); $this->arena->writeWord($slot + self::SLOT_WORD_PAYLOAD * 8, $payload); // State last: a reader that sees a settled state is guaranteed to see the @@ -318,14 +517,105 @@ private function settle(int $id, ResultState $state, ValueTag $tag, int $payload $this->recoveredLock = $this->recoveredLock || $recovered; + // Thrown outside the critical section on purpose: an exception raised while the robust + // mutex is held would leave it owned by a frame that is unwinding + if ($stale) { + throw $this->staleFailure($index, $want, $current); + } if ($settled) { - throw IpcException::slotAlreadyCompleted($id); + throw IpcException::slotAlreadyCompleted($index, $want); } - $this->wake->notifyAll($waiters->occupants(), WakeEvent::forValue($opcode, $id, $tag, $payload)); + $this->wake->notifyAll($waiters->occupants(), WakeEvent::forValue($opcode, $ticket, $tag, $payload)); } - private function unpark(int $slot, WaiterTable $waiters, ?int $entry): void + /** + * Wipes a settled slot and puts it back in circulation; the caller holds the table lock + * + * Nothing is freed here and nothing can be: the arena is bump-only and a child may never + * free (AGENTS.md §2, §6). The record is reused where it lies, which is the only shape + * recycling can have in this allocator. + */ + private function recycle(int $index, int $slot, int $generation): void + { + $this->clearSlotRecord($slot); + $this->arena->writeWord($slot + self::SLOT_WORD_STATE * 8, ResultState::Free->value); + $this->bumpHeader(self::WORD_LIVE, -1); + + if ($generation >= SlotTicket::MAX_GENERATION) { + // Retired rather than wrapped: a counter coming back round would make a handle from + // 65 535 generations ago match again, and this design has no second line of defence + // behind the generation check + $this->arena->writeWord($slot + self::SLOT_WORD_GENERATION * 8, SlotTicket::RETIRED); + $this->bumpHeader(self::WORD_RETIRED, 1); + + return; + } + + $this->arena->writeWord($slot + self::SLOT_WORD_GENERATION * 8, $generation + 1); + $this->pushFreeSlot($index, $slot); + } + + /** + * Takes the most recently released slot off the free list; the caller holds the table lock + * + * @return int|null Slot index, or null when nothing has been released yet + */ + private function popFreeSlot(): ?int + { + $head = (int) $this->arena->readWord($this->address + self::WORD_FREE * 8); + if ($head === 0) { + return null; + } + + $index = $head - 1; + $slot = $this->slotAt($index); + + $this->arena->writeWord( + $this->address + self::WORD_FREE * 8, + (int) $this->arena->readWord($slot + self::SLOT_WORD_NEXT_FREE * 8), + ); + $this->arena->writeWord($slot + self::SLOT_WORD_NEXT_FREE * 8, 0); + $this->bumpHeader(self::WORD_RECYCLED, 1); + + return $index; + } + + /** + * Pushes a slot onto the free list; the caller holds the table lock + * + * The link is `index + 1` so that a zero word means "end of list" without a separate flag, + * the same trick {@see WaiterTable} uses for occupancy. + */ + private function pushFreeSlot(int $index, int $slot): void + { + $this->arena->writeWord( + $slot + self::SLOT_WORD_NEXT_FREE * 8, + (int) $this->arena->readWord($this->address + self::WORD_FREE * 8), + ); + $this->arena->writeWord($this->address + self::WORD_FREE * 8, $index + 1); + } + + /** + * Zeroes everything about a slot except its state and generation; the caller holds the lock + * + * The waiter table goes too. Leaving one entry of a past generation behind would cost the + * next owner of the slot a spurious notification at best, and at worst a waiter table that + * is permanently full of processes that stopped caring several tasks ago. + */ + private function clearSlotRecord(int $slot): void + { + $this->arena->writeWord($slot + self::SLOT_WORD_TAG * 8, 0); + $this->arena->writeWord($slot + self::SLOT_WORD_PAYLOAD * 8, 0); + $this->arena->writeWord($slot + self::SLOT_WORD_PARKED * 8, 0); + $this->arena->writeWord($slot + self::SLOT_WORD_NEXT_FREE * 8, 0); + + for ($entry = 0; $entry < self::SLOT_WAITERS; $entry++) { + $this->arena->writeWord($slot + (self::SLOT_WORD_WAITERS + $entry) * 8, 0); + } + } + + private function unpark(int $slot, int $generation, WaiterTable $waiters, ?int $entry): void { if ($entry === null) { return; @@ -333,8 +623,13 @@ private function unpark(int $slot, WaiterTable $waiters, ?int $entry): void $recovered = $this->arena->lockMutexAt($this->mutex); - $waiters->release($entry); - $this->bumpParked($slot, -1); + // Only while the slot is still the one this process parked on: a slot recycled underneath + // a parked waiter belongs to another task now, and releasing "our" entry in it would cost + // that task a wakeup it is entitled to + if ((int) $this->arena->readWord($slot + self::SLOT_WORD_GENERATION * 8) === $generation) { + $waiters->release($entry); + $this->bumpParked($slot, -1); + } $this->arena->unlockMutexAt($this->mutex); @@ -346,16 +641,50 @@ private function unpark(int $slot, WaiterTable $waiters, ?int $entry): void */ private function bumpParked(int $slot, int $delta): void { - $parked = $this->arena->readWord($slot + self::SLOT_WORD_PARKED * 8) + $delta; + $parked = (int) $this->arena->readWord($slot + self::SLOT_WORD_PARKED * 8) + $delta; $this->arena->writeWord($slot + self::SLOT_WORD_PARKED * 8, max($parked, 0)); } - private function slotAddress(int $id): int + /** + * Moves a header counter; the caller holds the table lock + */ + private function bumpHeader(int $word, int $delta): void + { + $value = (int) $this->arena->readWord($this->address + $word * 8) + $delta; + $this->arena->writeWord($this->address + $word * 8, max($value, 0)); + } + + /** + * The refusal for a handle whose generation is not the slot's, told apart from a dead slot + */ + private function staleFailure(int $index, int $held, int $current): IpcException + { + return $current === SlotTicket::RETIRED + ? IpcException::slotRetired($index) + : IpcException::staleSlot($index, $held, $current); + } + + /** + * Where a ticket's slot record starts, refusing an index the table does not have + * + * Called before the lock is taken, never under it: it is the one part of addressing a slot + * that can throw. + */ + private function slotAddress(int $ticket): int { - if ($id < 0 || $id >= $this->capacity) { - throw IpcException::unknownSlot($id, $this->capacity); + $index = SlotTicket::indexOf($ticket); + if ($index < 0 || $index >= $this->capacity) { + throw IpcException::unknownSlot($index, $this->capacity); } - return $this->address + (self::HEADER_WORDS + $id * self::SLOT_WORDS) * 8; + return $this->slotAt($index); + } + + /** + * Address arithmetic for a slot index already known to be in range + */ + private function slotAt(int $index): int + { + return $this->address + (self::HEADER_WORDS + $index * self::SLOT_WORDS) * 8; } } diff --git a/src/Ipc/ResultState.php b/src/Ipc/ResultState.php index beca855..3085327 100644 --- a/src/Ipc/ResultState.php +++ b/src/Ipc/ResultState.php @@ -14,11 +14,17 @@ namespace Lisachenko\SharedData\Ipc; /** - * The three states a result slot can be in + * The states a result slot can be in * * PENDING is the zero value on purpose: a freshly allocated slot is kernel-zeroed arena * memory, so a slot that was never written reads as pending in every process without * anybody having to initialize it. + * + * FREE is the recycling state and it exists so that a released slot is never mistaken for a + * fresh one. A slot on the free list has already had its generation bumped, so a handle from + * the previous generation fails the generation check long before the state is consulted; the + * state is what makes a *dump* of the table readable and what lets the allocator assert that + * the slot it just popped really was free. */ enum ResultState: int { @@ -33,4 +39,9 @@ enum ResultState: int * The coroutine threw; the slot carries the address of a shared error-info object */ case Panic = 2; + + /** + * Settled, read, released: the slot is on the free list waiting to be handed out again + */ + case Free = 3; } diff --git a/src/Ipc/SlotResult.php b/src/Ipc/SlotResult.php index 574f61a..be34861 100644 --- a/src/Ipc/SlotResult.php +++ b/src/Ipc/SlotResult.php @@ -19,6 +19,10 @@ * The value is built from the shared record AFTER the slot lock is released, so a SlotResult * is an ordinary request-scoped value object. For a PANIC it carries the shared error-info * object (see SharedError), which is a real object in the arena and not a rendered message. + * + * `$id` is the {@see SlotTicket} the read was made with - slot index and generation - not a bare + * index, so it can be handed straight back to readSlot(), await() or releaseSlot() and stays a + * claim on THIS result rather than on whatever the slot holds later. */ final class SlotResult { diff --git a/src/Ipc/SlotTicket.php b/src/Ipc/SlotTicket.php new file mode 100644 index 0000000..7c4131d --- /dev/null +++ b/src/Ipc/SlotTicket.php @@ -0,0 +1,102 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Lisachenko\SharedData\Ipc; + +/** + * A claim on one result slot: its index and the generation that claim was minted in + * + * A ticket is a plain `int` with a documented bit layout, not an object, and the layout is + * chosen by the **socket**, not by convenience: + * + * ```text + * bits 0..15 slot index 0 .. 65535 + * bits 16..31 generation 1 .. 65535 (0 is never a live generation) + * ``` + * + * ## Why it has to fit in 32 bits + * + * The only thing this package's sockets ever carry is a {@see WakeEvent}: 16 fixed bytes + * whose `id` field is a **uint32**. A slot id therefore has to survive a round trip through + * that field, and packing the generation beside the index is what lets a settling worker be + * told *which* generation of a slot it is answering for rather than merely which slot. The + * alternative - keeping the generation purely slot-local and checking it only at read time - + * would leave a zombie worker able to settle a slot that had been recycled underneath it, + * because nothing it holds would disagree with the slot's own state. + * + * Both halves are 16 bits, so the packed value is at most 0xFFFFFFFF and a table may hold at + * most 65536 slots ({@see self::MAX_SLOTS}); {@see ResultSlotTable::create()} refuses a larger + * capacity rather than silently truncating a ticket. + * + * ## Generation 0 is deliberately impossible + * + * A freshly bump-allocated slot starts at generation 1, so a bare slot *index* handed to any + * verb decodes as generation 0 and fails the generation check instead of quietly addressing + * generation 1. That turns "somebody passed the wrong integer" into a typed exception, which + * is the same treatment a genuinely stale handle gets. Generation 0 is also what a **retired** + * slot is stamped with (see {@see ResultSlotTable}), so nothing can ever address one again. + */ +final class SlotTicket +{ + /** + * Bits the slot index occupies; the generation takes the 16 above it + */ + public const int INDEX_BITS = 16; + + public const int INDEX_MASK = (1 << self::INDEX_BITS) - 1; + + /** + * Slots one table may hold - a hard ceiling of the ticket layout, not a policy + */ + public const int MAX_SLOTS = 1 << self::INDEX_BITS; + + /** + * Highest generation a slot can reach; the next release retires the slot instead of wrapping + */ + public const int MAX_GENERATION = (1 << 16) - 1; + + /** + * The generation word of a slot that is out of circulation for good + */ + public const int RETIRED = 0; + + private function __construct() + { + } + + /** + * Packs a claim; both halves are range-checked by the table that mints them + */ + public static function pack(int $index, int $generation): int + { + return ($generation << self::INDEX_BITS) | ($index & self::INDEX_MASK); + } + + public static function indexOf(int $ticket): int + { + return $ticket & self::INDEX_MASK; + } + + public static function generationOf(int $ticket): int + { + return ($ticket >> self::INDEX_BITS) & self::MAX_GENERATION; + } + + /** + * How a ticket is spelled in a message: the slot index, then the generation + */ + public static function describe(int $ticket): string + { + return sprintf('#%d/gen%d', self::indexOf($ticket), self::generationOf($ticket)); + } +} diff --git a/tests/Ipc/NotificationPlaneForkTest.php b/tests/Ipc/NotificationPlaneForkTest.php index 67c3dae..5256571 100644 --- a/tests/Ipc/NotificationPlaneForkTest.php +++ b/tests/Ipc/NotificationPlaneForkTest.php @@ -133,8 +133,13 @@ public function testAFullProducerConsumerRoundTripCallsNoEncodingFunctionAtAll() SerializationGuard::reset(); - $child = $this->fork(static function () use ($channel, $slots): int { - $slotId = 0; + // Allocated before the fork, so the child inherits the TICKET rather than guessing an + // index: a slot id carries its generation, and generation 0 is deliberately no slot at all + $slotId = $slots->allocateSlot(); + $this->assertSame(0, SlotTicket::indexOf($slotId)); + $this->assertSame(1, SlotTicket::generationOf($slotId)); + + $child = $this->fork(static function () use ($channel, $slots, $slotId): int { for ($index = 0; $index < 4; $index++) { [$value, $ok] = $channel->recv(10.0); if (!$ok) { @@ -148,9 +153,6 @@ public function testAFullProducerConsumerRoundTripCallsNoEncodingFunctionAtAll() return self::OK; }); - $slotId = $slots->allocateSlot(); - $this->assertSame(0, $slotId); - $array[0] = 'inside the shared array'; $channel->send('a string of real bytes', 10.0); $channel->send(1234, 10.0); diff --git a/tests/Ipc/ResultSlotForkTest.php b/tests/Ipc/ResultSlotForkTest.php index 22fe3e4..fd23deb 100644 --- a/tests/Ipc/ResultSlotForkTest.php +++ b/tests/Ipc/ResultSlotForkTest.php @@ -198,7 +198,7 @@ public function testAPreSizedSlotTableRefusesToGrow(): void $slots->allocateSlot(); $this->expectException(IpcException::class); - $this->expectExceptionMessageMatches('/pre-sized in the arena and never grows/'); + $this->expectExceptionMessageMatches('/All 2 result slots are in use/'); $slots->allocateSlot(); } diff --git a/tests/Ipc/ResultSlotRecyclingForkTest.php b/tests/Ipc/ResultSlotRecyclingForkTest.php new file mode 100644 index 0000000..379dcae --- /dev/null +++ b/tests/Ipc/ResultSlotRecyclingForkTest.php @@ -0,0 +1,287 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Lisachenko\SharedData\Ipc; + +/** + * Slots come back, and an old handle never gets somebody else's answer + * + * The arena is bump-only and children may never free, so a recycled slot is the SAME record + * reused in place - there is no other shape recycling could take here. What makes that safe is + * that a slot id is a {@see SlotTicket}: index plus generation. The generation moves the moment + * an owner releases its claim, so a handle held one moment too long is refused by name instead + * of being answered with whatever task got the slot next. + * + * Every case below is about one of the two halves: the supply really does come back, and the + * refusal really is loud. + */ +class ResultSlotRecyclingForkTest extends IpcTestCase +{ + private function slots(int $capacity = 64): ResultSlotTable + { + return ResultSlotTable::create($this->allocator(), $this->codec(), $this->wake(), $capacity, null); + } + + public function testAReleasedSlotIsHandedOutAgainUnderANewGeneration(): void + { + $slots = $this->slots(4); + + $first = $slots->allocateSlot(); + $slots->complete($first, 'the first answer'); + + $this->assertSame('the first answer', $slots->readSlot($first)->value); + $this->assertSame(1, $slots->outstanding()); + + $slots->releaseSlot($first); + $this->assertSame(0, $slots->outstanding()); + + $second = $slots->allocateSlot(); + + $this->assertSame( + SlotTicket::indexOf($first), + SlotTicket::indexOf($second), + 'the released slot record was not reused', + ); + $this->assertSame(SlotTicket::generationOf($first) + 1, SlotTicket::generationOf($second)); + $this->assertNotSame($first, $second, 'the ticket must change even though the slot did not'); + + // The record is genuinely reset, not merely re-labelled + $this->assertTrue($slots->readSlot($second)->isPending()); + $this->assertSame(1, $slots->recycled()); + $this->assertSame(1, $slots->highWaterMark(), 'a recycled slot must not move the bump cursor'); + } + + public function testASteadyStreamOfResultsKeepsReusingOneSlot(): void + { + $slots = $this->slots(4); + + for ($round = 0; $round < 1_000; $round++) { + $ticket = $slots->allocateSlot(); + $slots->complete($ticket, $round); + + $this->assertSame($round, $slots->readSlot($ticket)->value); + + $slots->releaseSlot($ticket); + } + + // The whole point of the change: a thousand results, one slot record, nothing climbing + $this->assertSame(1, $slots->highWaterMark()); + $this->assertSame(0, $slots->outstanding()); + $this->assertSame(4, $slots->available()); + $this->assertSame(999, $slots->recycled()); + } + + public function testAStaleHandleIsRefusedByEveryVerbRatherThanAnsweredWithTheNextResult(): void + { + $slots = $this->slots(4); + + $stale = $slots->allocateSlot(); + $slots->complete($stale, 'the answer the stale handle read'); + $slots->releaseSlot($stale); + + $fresh = $slots->allocateSlot(); + $slots->complete($fresh, 'the answer that belongs to somebody else'); + + $verbs = [ + 'readSlot' => static fn(): mixed => $slots->readSlot($stale), + 'await' => static fn(): mixed => $slots->await($stale, 0.05), + 'complete' => static fn(): mixed => $slots->complete($stale, 'too late'), + 'completePanic' => static fn(): mixed => $slots->completePanic($stale, $slots->address()), + 'releaseSlot' => static fn(): mixed => $slots->releaseSlot($stale), + ]; + + foreach ($verbs as $verb => $call) { + try { + $call(); + $this->fail(sprintf('%s() answered a stale handle instead of refusing it', $verb)); + } catch (IpcException $refused) { + $this->assertStringContainsString('generation', $refused->getMessage(), $verb); + $this->assertStringContainsString( + sprintf('slot %d', SlotTicket::indexOf($stale)), + $refused->getMessage(), + $verb, + ); + } + } + + // And the task that legitimately owns the slot is untouched by all that + $this->assertSame('the answer that belongs to somebody else', $slots->readSlot($fresh)->value); + } + + public function testABareSlotIndexIsNotAValidHandle(): void + { + $slots = $this->slots(4); + $ticket = $slots->allocateSlot(); + + $this->expectException(IpcException::class); + $this->expectExceptionMessageMatches('/generation 0/'); + + // Generation 0 never exists, so the integer that looks most like the old slot id is + // refused rather than quietly addressing the first generation of that slot + $slots->readSlot(SlotTicket::indexOf($ticket)); + } + + public function testAPendingSlotIsRefusedRatherThanRecycledUnderItsWriter(): void + { + $slots = $this->slots(4); + $ticket = $slots->allocateSlot(); + + $this->expectException(IpcException::class); + $this->expectExceptionMessageMatches('/still pending and cannot be released/'); + + $slots->releaseSlot($ticket); + } + + public function testReleasingTwiceIsRefusedRatherThanDoubleFreeingTheSlot(): void + { + $slots = $this->slots(4); + $ticket = $slots->allocateSlot(); + $slots->complete($ticket, 1); + $slots->releaseSlot($ticket); + + $this->expectException(IpcException::class); + $this->expectExceptionMessageMatches('/generation/'); + + $slots->releaseSlot($ticket); + } + + public function testATableWhoseSlotsAreAllGenuinelyHeldStillFillsUp(): void + { + $slots = $this->slots(2); + + $first = $slots->allocateSlot(); + $second = $slots->allocateSlot(); + + try { + $slots->allocateSlot(); + $this->fail('a full table handed out a third slot'); + } catch (IpcException $full) { + $this->assertStringContainsString('All 2 result slots are in use', $full->getMessage()); + $this->assertStringContainsString('2 outstanding', $full->getMessage()); + $this->assertStringContainsString('releaseSlot()', $full->getMessage()); + } + + // Releasing one is what makes room again, and only that + $slots->complete($first, 'read and done with'); + $slots->readSlot($first); + $slots->releaseSlot($first); + + $third = $slots->allocateSlot(); + $this->assertSame(SlotTicket::indexOf($first), SlotTicket::indexOf($third)); + $this->assertNotSame(SlotTicket::indexOf($second), SlotTicket::indexOf($third)); + } + + public function testASlotIsRetiredRatherThanLettingItsGenerationWrapRound(): void + { + $slots = $this->slots(1); + + for ($use = 0; $use < SlotTicket::MAX_GENERATION; $use++) { + $ticket = $slots->allocateSlot(); + $slots->complete($ticket, $use); + $slots->releaseSlot($ticket); + } + + $this->assertSame(1, $slots->retired(), 'the slot was recycled past the end of its counter'); + $this->assertSame(0, $slots->available()); + + try { + $slots->allocateSlot(); + $this->fail('a retired slot was handed out again'); + } catch (IpcException $full) { + $this->assertStringContainsString('1 retired', $full->getMessage()); + } + } + + public function testASlotRecycledByTheParentCarriesAChildsResultAndRefusesTheOldHandle(): void + { + $slots = $this->slots(2); + $arena = $this->arena(); + $report = $arena->allocate(8); + $arena->writeWord($report, 0); + + // Round one: settled here, read here, given back here + $first = $slots->allocateSlot(); + $slots->complete($first, 'round one'); + $this->assertSame('round one', $slots->readSlot($first)->value); + $slots->releaseSlot($first); + + // Round two lands on the very same record, and a CHILD settles it + $second = $slots->allocateSlot(); + $this->assertSame(SlotTicket::indexOf($first), SlotTicket::indexOf($second)); + + $child = $this->fork(static function () use ($slots, $first, $second, $arena, $report): int { + // The stale ticket of round one must not settle round two's slot from over here + try { + $slots->complete($first, 'a result from the wrong generation'); + + return self::WRONG_STATE; + } catch (IpcException) { + $arena->writeWord($report, 1); + } + + usleep(150_000); + $slots->complete($second, 'round two, settled by the child'); + + return self::OK; + }); + + $result = $slots->await($second, 10.0); + + $this->assertTrue($result->isDone()); + $this->assertSame('round two, settled by the child', $result->value); + $this->assertSame(self::OK, $this->await($child)); + $this->assertSame(1, $arena->readWord($report), 'the child was allowed to use the stale ticket'); + + // The parent's own copy of the dead handle is refused just as flatly + $this->expectException(IpcException::class); + $slots->readSlot($first); + } + + public function testASpawnArgumentSlotIsReleasedByItsReaderAndComesBackToTheTable(): void + { + $slots = $this->slots(2); + $argument = $slots->allocateSlot(); + $answer = $slots->allocateSlot(); + + $slots->complete($argument, 21); + + $child = $this->fork(static function () use ($slots, $argument, $answer): int { + $input = $slots->await($argument, 5.0); + if (!$input->isDone() || !\is_int($input->value)) { + return self::WRONG_VALUE; + } + + // The reader of a one-shot downward slot is the one that gives it back: the parent + // has nothing left to read there and would only be guessing when it is safe + $slots->releaseSlot($argument); + $slots->complete($answer, $input->value * 2); + + return self::OK; + }); + + $this->assertSame(42, $slots->await($answer, 10.0)->value); + $this->assertSame(self::OK, $this->await($child)); + + // Released in the child, visible as free in the parent: the free list is arena state + $slots->releaseSlot($answer); + $this->assertSame(0, $slots->outstanding()); + $this->assertSame(2, $slots->available()); + + $reused = $slots->allocateSlot(); + $this->assertContains( + SlotTicket::indexOf($reused), + [SlotTicket::indexOf($argument), SlotTicket::indexOf($answer)], + ); + $this->assertSame(2, SlotTicket::generationOf($reused)); + } +}