From 33ce93100d5d95893e077d4b3c0385c4d93e02c4 Mon Sep 17 00:00:00 2001 From: Claude Fable 5 Date: Sun, 16 Aug 2026 09:22:57 +0000 Subject: [PATCH 1/2] feat(parallel): give result slots back once their handle has taken the answer A pool spawning ten tasks a second exhausted the 4096-slot supply in under seven minutes however few tasks were ever in flight, because a slot was taken per spawnParallel() and never returned. The substrate now recycles slots through a generation-tagged free list; this is the consumer half - the signal that says a slot has been read, and the audit that says when saying so is true. **When it is safe.** `SlotTable::settle()` is the only place this package reads a shared slot record, and it copies the whole outcome into per-process state before returning: the decoded value, or a `ParallelTaskException` built from the shared error object's named properties. After that, nothing here looks at shared memory for that slot again - `refresh()` skips locally complete slots, and `failPendingOf()` reaches the record only through `refresh()`. So `JoinHandle` takes its answer out of the slot, keeps it, and only then releases: capture, then release. Awaiting the same handle again replays what was kept rather than reading a record that may already belong to somebody else. What came *out* of the record stays valid. An `OBJ` or `STR` answer is an arena address, and the arena frees nothing - releasing a slot returns the slot **record**, never the memory the answer lives in. The same reasoning covers a panic's `SharedError`: the strings the exception carries are arena strings that outlive any slot. No attempt is made to reclaim an error graph, and none should be from a worker: children never free arena memory, so error graphs stay leak-until-teardown (that is #19's ground, not this change's). **Who releases.** The owner - the process that opened the slot - and only once every local handle on it is satisfied, which is what the per-slot handle count is for (`attachResult()` of a slot this process opened is legitimately two handles on one slot). An adopter never releases: it cannot know who else in the family is still reading. A cross-process reader therefore has to finish before the owner's await() returns, and if it does not, its next read is refused by generation rather than answered with the next task's result. **What deliberately does not come back:** a slot whose worker died before settling it (still pending in shared memory, and a zombie worker may yet write to it), and a handle nobody awaits (nothing has read it, so nothing can say it is safe). Both are the pre-recycling behaviour, now scoped to the cases that actually need it. The local slot map is pruned on release either way - a per-process map that only ever grows is a leak of its own on a pool that runs for days. Option 2 as well: `new Runtime(..., slots: N)` sizes the table, and the README documents the arithmetic - one slot per spawn, given back at await, so the supply bounds concurrency rather than throughput, with the two exceptions above spelled out. `tools/soak-arena-watermark.php` now runs on a deliberately small table (64 slots, 320 spawns) and reports the high-water mark, which must be exactly flat: a slot is either handed back or it is not, so that series has no tolerance to spend. `--leak-slots` makes the new detector fail on demand, the way `--self-test` does for the watermark. Requires the recycling substrate (lisachenko/php-shared-data-extension), so CI here stays red until that lands on its main. Suite: 100 tests OK on PHP 8.4; phpstan level max clean; soak-arena-watermark, soak-memory-flatness and soak-no-leftover-children all PASS. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01U5QRWPfmkZME7hDjU6i5EA --- AGENTS.md | 43 ++++-- README.md | 52 ++++++- src/Exception/WorkerCrashedException.php | 21 ++- src/Parallel/JoinHandle.php | 53 ++++++- src/Parallel/ResultSlot.php | 23 +++ src/Parallel/SlotTable.php | 113 +++++++++++++- src/Runtime.php | 21 ++- ...herThanAnsweredWithAnotherTasksResult.phpt | 79 ++++++++++ .../testAPoolOutlivesItsResultSlotSupply.phpt | 57 +++++++ tools/soak-arena-watermark.php | 141 +++++++++++++----- 10 files changed, 538 insertions(+), 65 deletions(-) create mode 100644 tests/Functional/testAHandleOnARecycledSlotIsRefusedRatherThanAnsweredWithAnotherTasksResult.phpt create mode 100644 tests/Functional/testAPoolOutlivesItsResultSlotSupply.phpt diff --git a/AGENTS.md b/AGENTS.md index 0349c2e..22c0183 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -239,9 +239,28 @@ in every process. slot carries. A panic slot whose payload does not attach as a `SharedError` still surfaces as a `ParallelTaskException` — one that says the detail is unavailable, never one that presents another object's fields as this task's failure. -- **Result slots are bump-allocated from a pre-sized table and never given back.** They are a bounded - supply for the life of the arena, which is what `soak-arena-watermark.php` reports rather than - assumes. +- **Result slots are a bounded supply that circulates.** The table is pre-sized in the arena before + the fork and never grows, but a slot goes back on the substrate's free list once its `JoinHandle` + has taken the answer, so the supply limits **concurrency**, not throughput. Two kinds do not come + back: a handle nobody awaits (nothing has read it, so nothing can say it is safe) and a slot whose + worker died before settling it (still pending in shared memory, and a zombie worker may yet write + to it — recycling it would let that write land on another task). `soak-arena-watermark.php` reports + the high-water mark and requires it to plateau exactly. +- **A slot id is a ticket, not an index**, and the difference is a safety property. Index and + generation are packed into the 32 bits a wake event carries, the generation moves the moment the + owner releases the slot, and every substrate verb refuses a mismatch by name. Keep an id only for + as long as the result it names: `attachResult()` on a released id throws, which is the design + working, not a race. Releasing is the **owner's** job — the process that spawned the task — so a + second process that attaches to somebody else's slot has to finish reading before the owner's + `await()` returns. +- **Capture, then release.** `SlotTable::settle()` is the only place this package reads a shared + slot record, and it copies the whole outcome — the decoded value, or a `ParallelTaskException` + built from the shared error object's named properties — into per-process state before returning. + Nothing may add a reader of the shared record after that point; `refresh()` skips locally complete + slots for exactly this reason. What came *out* of the record stays valid regardless: an `OBJ` or + `STR` answer is an arena address and the arena frees nothing, so releasing a slot returns the slot + record and never the memory the answer lives in. Error graphs are not reclaimed at all — a child + may never free arena memory — and stay leak-until-teardown on purpose. ## Environment @@ -329,12 +348,18 @@ php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-arena-watermark.php | --- | --- | --- | | `tools/soak-memory-flatness.php` | RSS and `memory_get_usage(true)` stay flat over sustained spawn/park/resume cycles; a monotonic climb or growth past the tolerance fails | 0 flat, 1 climbing, 2 inconclusive | | `tools/soak-no-leftover-children.php` | no live child and no zombie survives a run | 0 clean, 1 leftovers, 2 inconclusive | -| `tools/soak-arena-watermark.php` | the arena watermark **plateaus** under a steady state, process memory stays flat, and no child survives. Leak-until-teardown is the design, so the criterion is a plateau, not zero growth | 0 plateau, 1 climbing or a leftover child, 2 inconclusive | - -Every one of them can produce its own failure on demand (`--inject-leak`, `--self-test`). Use that -after changing the detection logic: a detector nobody has seen fail is a detector nobody knows works. -`soak-arena-watermark.php --self-test` rewrites a shared string property every round, which is the -substrate's documented per-write arena cost, and must come back FAIL. +| `tools/soak-arena-watermark.php` | the arena watermark **plateaus** under a steady state, **result-slot consumption plateaus exactly**, process memory stays flat, and no child survives. Leak-until-teardown is the design for bytes, so their criterion is a plateau rather than zero growth; a slot is either handed back or it is not, so its criterion has no tolerance at all | 0 plateau, 1 climbing or a leftover child, 2 inconclusive | + +The watermark soak runs on a deliberately small slot table (`--slots=64`, far fewer than the run +spawns), because a table big enough to absorb the whole run would prove nothing about slots coming +back. + +Every one of them can produce its own failure on demand (`--inject-leak`, `--self-test`, +`--leak-slots`). Use that after changing the detection logic: a detector nobody has seen fail is a +detector nobody knows works. `soak-arena-watermark.php --self-test` rewrites a shared string property +every round, which is the substrate's documented per-write arena cost, and must come back FAIL; +`--leak-slots` takes a slot every round without giving it back and must fail on the **slot** series +with the byte series still flat. ## Repository map diff --git a/README.md b/README.md index 056f960..efec1f9 100644 --- a/README.md +++ b/README.md @@ -437,7 +437,9 @@ $runtime->run(function (TaskRuntime $runtime) use ($task, $report): void { - **`spawnParallel()` returns a `JoinHandle`.** `await()` parks the calling coroutine on the poller, wakes on the settled slot and reads the value **straight out of shared memory**. A slot that is already settled returns without parking, and a slot may be awaited from any process of the family — - `attachResult($slotId)` is the handle for that. + `attachResult($slotId)` is the handle for that. `await()` also gives the slot back (see + [the slot budget](#the-result-slot-budget)), so the id it was awaited on stops naming this result: + keep the value, not the id. - **A `SharedChannel` is a `ChannelInterface`**, so it drops into `Select` next to a local `Channel` and one `select` statement can mix the two. Its `readinessFd()` is the arena's wake socket, which the poller drains on every readiness — level-triggered pokes, so an undrained pipe would spin. @@ -451,6 +453,54 @@ $runtime->run(function (TaskRuntime $runtime) use ($task, $report): void { makes one shareable for the life of the family; a closure created afterwards is refused, because no inspection can tell it apart from a stale address holding a different, perfectly valid `Closure`. +### The result-slot budget + +Every `spawnParallel()` takes **one result slot** out of a table that lives in the arena. The table +is pre-sized before the fork and cannot grow — the engine would move a growing shared structure into +one worker's private heap and leave its siblings reading garbage — so the supply is fixed for the +life of the family: + +```php +$runtime = new Runtime( + workers: 4, + arenaSize: 64 << 20, // bytes the whole family shares + slots: 4096, // result slots, the default +); +``` + +**It is a limit on concurrency, not on throughput.** A slot goes back on the substrate's free list +as soon as its `JoinHandle` has taken the answer, so a pool doing millions of spawns needs only as +many slots as it has results *in flight at once*: + +| What the workload does | Slots it needs | +| --- | --- | +| spawn, `await()`, repeat | 1 | +| spawn N, then await all N | N | +| a pool of W workers kept saturated | ≈ W, plus whatever is queued ahead of them | +| a handle that is spawned and never awaited | 1, for the rest of the run | +| a task whose worker died before settling | 1, for the rest of the run | + +The last two are the ones that actually consume the budget. A handle nobody awaits has never had its +answer read, so nothing can say the slot is safe to reuse; a slot whose worker was killed mid-task is +still *pending* in shared memory and a zombie worker may yet write to it, so recycling it could let +that write land on another task. Both are deliberately left out of circulation. + +Spawn **arguments** do not cost a slot in this runtime: a `SPAWN` record carries the task's arena +address in its own 16 bytes, so the only slot a spawn takes is the one its result lands in. + +**Exhaustion is a typed refusal, not corruption.** `IpcException` names the table, how many slots are +outstanding and the knob to turn. And because slot ids are recycled, an id is a *ticket* — the slot +index plus the generation it was handed out in — so a handle kept past its release is refused by name +rather than answered with the result of whatever task got the slot next: + +``` +Result slot 7 is at generation 12 and this handle holds generation 11: the slot was released +and handed to another task. +``` + +`tools/soak-arena-watermark.php` reports the series that matters: the number of slot records the +table has ever created must **plateau** under steady churn. + ## Layers | Layer | What it gives you | FFI | diff --git a/src/Exception/WorkerCrashedException.php b/src/Exception/WorkerCrashedException.php index a17542e..bc0439d 100644 --- a/src/Exception/WorkerCrashedException.php +++ b/src/Exception/WorkerCrashedException.php @@ -12,12 +12,18 @@ namespace Lisachenko\NativePhpCoroutines\Exception; +use Lisachenko\SharedData\Ipc\SlotTicket; + /** * A worker died without completing the work it had been given. * * Raised in whichever process was waiting, and deliberately loud: the alternative to an exception * here is a coroutine parked forever on a result slot that nobody will ever fill. Any slots the * dead worker owned are named, so a caller can tell exactly which results are lost. + * + * A slot is named by its **ticket** — index and generation — because that is what a slot id is once + * slots are recycled. `#7/gen3` is a different claim from `#7/gen4`, and a report that printed only + * the index would point at whichever task holds the record now. */ final class WorkerCrashedException extends \RuntimeException implements CoroutineException { @@ -34,7 +40,7 @@ public function __construct( $message .= sprintf( '; %d result slot(s) can never complete: %s', count($abandonedSlots), - implode(', ', array_map(static fn(int $slot): string => '#' . $slot, $abandonedSlots)), + implode(', ', array_map(self::nameSlot(...), $abandonedSlots)), ); } @@ -66,4 +72,17 @@ public static function notRunning(int $workerId): self { return new self($workerId, 'the worker is not running'); } + + /** + * How one lost slot is spelled in the message. + * + * A shared slot id is a ticket and always carries a non-zero generation, because generation 0 + * is deliberately no slot at all. A runtime with no arena numbers its slots itself and has no + * generations to report, so those keep the plain `#7` they always had rather than growing a + * `/gen0` that would mean nothing. + */ + private static function nameSlot(int $slot): string + { + return SlotTicket::generationOf($slot) === 0 ? '#' . $slot : SlotTicket::describe($slot); + } } diff --git a/src/Parallel/JoinHandle.php b/src/Parallel/JoinHandle.php index 4997135..b71081f 100644 --- a/src/Parallel/JoinHandle.php +++ b/src/Parallel/JoinHandle.php @@ -27,9 +27,28 @@ * The park is marked **externally wakeable**, which keeps deadlock detection honest — no amount of * local scheduling could produce this wakeup, so a process with nothing but parallel waits * outstanding is idle, not deadlocked. + * + * # The handle owns the answer, not the slot + * + * Shared slots are recycled, so holding one open for the rest of a run is a real cost: a pool that + * never gives slots back exhausts a supply that is pre-sized in the arena and cannot grow. This + * handle therefore takes its answer out of the slot the first time it is awaited, keeps it, and + * tells {@see SlotTable::release()} the slot is finished with. Awaiting again replays what was + * kept — the same value, or the same throwable — and never touches shared memory a second time. + * + * The order matters and is not an implementation detail: **capture, then release.** After the + * release the shared record may already belong to another task, and a read of it would be refused + * by generation rather than answered — which is the safety net, not the plan. */ final class JoinHandle implements JoinHandleInterface { + /** Whether the answer has been taken out of the slot and the slot handed back. */ + private bool $taken = false; + + private mixed $outcome = null; + + private ?\Throwable $failure = null; + public function __construct( private readonly SlotTable $slots, private readonly SchedulerInterface $scheduler, @@ -44,6 +63,10 @@ public function slotId(): int public function isComplete(): bool { + if ($this->taken) { + return true; + } + $slot = $this->slots->slot($this->slotId); if (!$slot->complete) { @@ -58,6 +81,14 @@ public function isComplete(): bool public function await(): mixed { + if ($this->taken) { + if ($this->failure !== null) { + throw $this->failure; + } + + return $this->outcome; + } + $slot = $this->slots->slot($this->slotId); // Read shared memory before every park, never after: a slot settled between the spawn and @@ -81,16 +112,22 @@ public function await(): mixed $this->slots->refresh(); } - if ($slot->error !== null) { - throw $slot->error; - } + // Taken out of the slot BEFORE it is handed back. An OBJ result is the very object the + // worker mutated, at the address it lives at, and it stays valid afterwards: releasing a + // slot returns the slot record, never the arena memory the answer lives in — the arena + // frees nothing at all. + $this->failure = $slot->error; + $this->outcome = $slot->hasDecoded + ? $slot->decoded + : ValueCodec::fromRecord($slot->value ?? TaggedRecord::nil()); + $this->taken = true; + + $this->slots->release($this->slotId); - // Read straight out of the arena: an OBJ result is the very object the worker mutated, at - // the address it lives at, and never a copy rebuilt from an encoding. - if ($slot->hasDecoded) { - return $slot->decoded; + if ($this->failure !== null) { + throw $this->failure; } - return ValueCodec::fromRecord($slot->value ?? TaggedRecord::nil()); + return $this->outcome; } } diff --git a/src/Parallel/ResultSlot.php b/src/Parallel/ResultSlot.php index 9bf7e0b..5a891f4 100644 --- a/src/Parallel/ResultSlot.php +++ b/src/Parallel/ResultSlot.php @@ -32,11 +32,33 @@ * * Nothing here is on the wire: a `RESULT` record names a slot and says "settled", and the value is * read from the arena rather than from the socket. + * + * # The three fields recycling added + * + * A shared slot is a **borrowed** record now: the substrate hands it back out once it is released, + * so this process has to know when it is done with one and whether it is entitled to give it back + * at all. + * + * - {@see self::$owned} — this process allocated the slot. Only an owner releases; a process that + * attached to somebody else's slot has no idea who else is still reading it. + * - {@see self::$handles} — how many {@see JoinHandle}s in this process still name the slot. The + * release happens when the last of them has taken its answer, which is what "every handle has + * read it" means locally. + * - {@see self::$sharedSettled} — whether the *shared* record really settled, as opposed to this + * process having decided the answer locally. A slot failed because its worker died is complete + * here and still pending there, and releasing it would hand a live record to the next task while + * a zombie worker may yet write to it. Those slots stay out of circulation on purpose. */ final class ResultSlot { public bool $complete = false; + /** Whether the authoritative shared record settled, rather than this process giving up on it. */ + public bool $sharedSettled = false; + + /** Local claims on this slot; the shared record goes back when the last one is satisfied. */ + public int $handles = 0; + /** The outcome as a record, once complete and successful — the path that needs no arena. */ public ?TaggedRecord $value = null; @@ -59,5 +81,6 @@ final class ResultSlot public function __construct( public readonly int $id, public readonly int $workerId, + public readonly bool $owned = true, ) {} } diff --git a/src/Parallel/SlotTable.php b/src/Parallel/SlotTable.php index cb1352f..a5a443e 100644 --- a/src/Parallel/SlotTable.php +++ b/src/Parallel/SlotTable.php @@ -37,6 +37,37 @@ * substrate's `readSlot()`, which takes the slot's mutex for the `{state, tag, payload}` triple and * materializes the value after releasing it, so a reader can never observe a tag from one generation * and a payload from another. + * + * # Shared slots are borrowed, and this class is what gives them back + * + * The substrate recycles slots, which is what stops a long-running pool exhausting a supply that is + * pre-sized in the arena and cannot grow. A slot goes back on its free list only when its owner says + * so, and that signal is this class's job: {@see self::release()} hands the record back once the + * last local handle has taken its answer. + * + * **When exactly it is safe** is the whole question, and the answer is *after the outcome has been + * copied into per-process state*. {@see self::settle()} is the only place this process reads the + * shared record, and it copies everything it needs — the decoded value, or a + * {@see ParallelTaskException} built from the shared error object's named properties — into the + * local {@see ResultSlot} before returning. From that point nothing here looks at shared memory for + * that slot again: {@see self::refresh()} skips slots that are locally complete, and + * {@see self::failPendingOf()} reaches the shared record only through `refresh()`. Releasing after + * a handle has taken its answer therefore has no late reader to race with. + * + * The values that came *out* of the record stay valid: an `OBJ` or `STR` result is an address into + * the arena, and the arena frees nothing — releasing a slot returns the slot **record**, not the + * memory the answer lives in. The same goes for a panic's `SharedError`: the strings the + * `ParallelTaskException` carries are arena strings, and no reclamation of that graph is attempted + * here. A child may never free arena memory at all, so error graphs remain leak-until-teardown. + * + * Two slots deliberately do **not** come back: + * + * - one whose worker died before settling it. The local answer is a crash exception, the shared + * record is still pending, and a zombie worker may yet write to it. Recycling it would let that + * write land on another task's slot. + * - one whose handle is never awaited. Nothing has read it, so nothing can say it is safe. + * + * Both are the pre-recycling behaviour, scoped down to the cases that actually need it. */ final class SlotTable { @@ -64,13 +95,20 @@ public function isShared(): bool return $this->arena !== null; } - /** Reserve a slot for work about to be dispatched to $workerId. */ + /** + * Reserve a slot for work about to be dispatched to $workerId. + * + * With an arena the id that comes back is a substrate slot **ticket** — index and generation — + * and this process owns it: it is the one that will give the record back. + */ public function open(int $workerId): ResultSlot { $id = $this->arena?->slotTable()->allocateSlot() ?? $this->nextId++; $slot = new ResultSlot($id, $workerId); + ++$slot->handles; + $this->slots[$slot->id] = $slot; return $slot; @@ -82,17 +120,73 @@ public function open(int $workerId): ResultSlot * This is what makes a result awaitable from a process that did not spawn the task: the slot id * is the whole handle, the state is in shared memory, and a process that has attached to the * arena can read it whether or not it has ever heard of the worker that will settle it. + * + * The shared record is read **here**, before anything else, precisely because the id may be + * stale: slots are recycled, and a ticket the table has moved past is refused by the substrate + * with the slot and both generations named. That refusal is the point — the alternative to it + * is attaching to whichever task got the slot next and presenting its result as this one's. + * + * An adopter is not an owner. It never releases the record, because it cannot know who else in + * the family is still reading it; the process that allocated the slot does that, and an adopter + * that has not finished by then finds its next read refused rather than answered. */ public function adopt(int $slotId, int $workerId = -1): ResultSlot { - if ($this->arena === null) { - throw new \LogicException( - 'a result slot can only be adopted from another process when the slots live in the ' - . 'shared arena; construct the runtime with workers > 0', - ); + $arena = $this->arena ?? throw new \LogicException( + 'a result slot can only be adopted from another process when the slots live in the ' + . 'shared arena; construct the runtime with workers > 0', + ); + + $slot = $this->slots[$slotId] ?? null; + + if ($slot === null) { + $result = $arena->slotTable()->readSlot($slotId); + $slot = $this->slots[$slotId] = new ResultSlot($slotId, $workerId, owned: false); + + if (!$result->isPending()) { + $this->settle($slot, $result); + } } - return $this->slots[$slotId] ??= new ResultSlot($slotId, $workerId); + ++$slot->handles; + + return $slot; + } + + /** + * Give a slot back once the handle holding it has taken its answer. + * + * Counted rather than immediate: two handles in one process may name one slot — `attachResult()` + * of a slot this process opened is exactly that — and the record only goes back when the last + * of them is satisfied. The local entry is dropped either way, because a per-process map that + * only ever grows is a leak of its own on a pool that runs for days. + */ + public function release(int $slotId): void + { + $slot = $this->slots[$slotId] ?? null; + + if ($slot === null) { + return; + } + + if ($slot->handles > 0) { + --$slot->handles; + } + + if ($slot->handles > 0 || !$slot->complete) { + return; + } + + unset($this->slots[$slotId]); + + // Only what this process owns, and only what the family really settled: a slot completed + // locally because its worker died is still pending in shared memory, and the substrate + // refuses to recycle a pending slot for the same reason we would not want it to. + if (!$slot->owned || !$slot->sharedSettled) { + return; + } + + $this->arena?->slotTable()->releaseSlot($slotId); } public function slot(int $slotId): ResultSlot @@ -227,6 +321,11 @@ public function failPendingOf(int $workerId, \Throwable $error): void */ private function settle(ResultSlot $slot, SlotResult $result): void { + // The one place this process reads the shared record, so the one place that decides when it + // is safe to hand it back: everything the waiter will ever need is copied into per-process + // state right here, and nothing after this point looks at shared memory for this slot. + $slot->sharedSettled = true; + if (!$result->isPanic()) { $slot->complete = true; $slot->hasDecoded = true; diff --git a/src/Runtime.php b/src/Runtime.php index d1f90d6..5c8dc16 100644 --- a/src/Runtime.php +++ b/src/Runtime.php @@ -100,6 +100,13 @@ final class Runtime implements TaskRuntime * a forked worker's runtime binds the mapping it inherited; * application code leaves it null. * @param int $arenaSize Bytes the whole family shares, when this runtime creates it. + * @param int $slots Result slots the family shares. One is taken per + * `spawnParallel()` and given back when its handle is + * awaited, so this sizes **concurrency**, not throughput: + * it has to cover the tasks in flight at once plus any slot + * held open by a handle nobody awaits. Pre-sized in the + * arena before the fork and never grown; exhausting it is a + * typed refusal naming the knob, never corruption. */ public function __construct( private readonly int $workers = 0, @@ -107,6 +114,7 @@ public function __construct( private readonly float $slice = Preemptor::DEFAULT_SLICE_SECONDS, ?SharedArena $arena = null, int $arenaSize = SharedArena::DEFAULT_SIZE, + int $slots = SharedArena::DEFAULT_SLOT_COUNT, ) { if ($workers < 0) { throw new \InvalidArgumentException( @@ -121,7 +129,9 @@ public function __construct( // Created here and nowhere later: everything the family shares has to exist before the first // fork, and run() forks before it spawns anything. - $this->arena = $arena ?? ($workers > 0 ? new SharedArena($arenaSize, max(32, $workers + 8)) : null); + $this->arena = $arena ?? ($workers > 0 + ? new SharedArena($arenaSize, max(32, $workers + 8), $slots) + : null); if ($this->arena === null) { $this->supervisor = null; @@ -240,6 +250,15 @@ public function publishTask(Task $task): void ); } + /** + * Take a handle on a slot some other process opened, by its id. + * + * A slot id is a **ticket**: the slot index and the generation it was handed out in. Slots are + * recycled, so an id kept past the moment its owner released it names a record that belongs to + * another task now, and attaching to it is refused by the substrate — with the slot and both + * generations named — rather than answered with that task's result. Hold an id only for as long + * as the result it names. + */ public function attachResult(int $slotId): JoinHandleInterface { $slots = $this->slots ?? throw new \LogicException( diff --git a/tests/Functional/testAHandleOnARecycledSlotIsRefusedRatherThanAnsweredWithAnotherTasksResult.phpt b/tests/Functional/testAHandleOnARecycledSlotIsRefusedRatherThanAnsweredWithAnotherTasksResult.phpt new file mode 100644 index 0000000..0247aa9 --- /dev/null +++ b/tests/Functional/testAHandleOnARecycledSlotIsRefusedRatherThanAnsweredWithAnotherTasksResult.phpt @@ -0,0 +1,79 @@ +--TEST-- +A handle on a recycled slot id is refused rather than answered with the result of the task that got the slot next +--INI-- +ffi.enable=1 +opcache.jit=off +error_reporting=E_ALL & ~E_DEPRECATED +--FILE-- +publishTask($first); +$runtime->publishTask($second); + +$runtime->run(static function (TaskRuntime $self) use ($first, $second): void { + parallelDeadline(20.0, 'the stale handle being refused'); + + $handle = $self->spawnParallel($first); + $stale = $handle->slotId(); + + echo 'first task: ', $handle->await(), PHP_EOL; + + $reused = $self->spawnParallel($second); + + echo 'the same slot record went out again: ', + SlotTicket::indexOf($reused->slotId()) === SlotTicket::indexOf($stale) ? 'yes' : 'no', PHP_EOL; + echo 'under a new generation: ', + SlotTicket::generationOf($reused->slotId()) > SlotTicket::generationOf($stale) ? 'yes' : 'no', PHP_EOL; + + try { + $value = $self->attachResult($stale)->await(); + + echo 'the stale handle was answered with ', var_export($value, true), ', which it must not', PHP_EOL; + } catch (IpcException $refused) { + echo 'the stale handle is refused: yes', PHP_EOL; + echo 'it names the slot: ', + str_contains($refused->getMessage(), 'slot ' . SlotTicket::indexOf($stale)) ? 'yes' : 'no', PHP_EOL; + echo 'it names both generations: ', + str_contains($refused->getMessage(), 'generation ' . SlotTicket::generationOf($stale)) + && str_contains($refused->getMessage(), 'generation ' . SlotTicket::generationOf($reused->slotId())) + ? 'yes' : 'no', PHP_EOL; + } + + echo 'and the task that owns the slot now is unharmed: ', $reused->await(), PHP_EOL; +}); + +echo 'children left: ', parallelChildrenLeft(), PHP_EOL; +?> +--EXPECT-- +first task: first +the same slot record went out again: yes +under a new generation: yes +the stale handle is refused: yes +it names the slot: yes +it names both generations: yes +and the task that owns the slot now is unharmed: second +children left: none diff --git a/tests/Functional/testAPoolOutlivesItsResultSlotSupply.phpt b/tests/Functional/testAPoolOutlivesItsResultSlotSupply.phpt new file mode 100644 index 0000000..cbe6eb8 --- /dev/null +++ b/tests/Functional/testAPoolOutlivesItsResultSlotSupply.phpt @@ -0,0 +1,57 @@ +--TEST-- +A pool spawning far more tasks than the slot supply runs to completion, reusing the same few slots +--INI-- +ffi.enable=1 +opcache.jit=off +error_reporting=E_ALL & ~E_DEPRECATED +--FILE-- +publishTask($task); + +$runtime->run(static function (TaskRuntime $self) use ($runtime, $task): void { + parallelDeadline(30.0, 'a hundred tasks over eight slots'); + + $sum = 0; + for ($index = 0; $index < 100; ++$index) { + $sum += $self->spawnParallel($task)->await(); + } + + $slots = $runtime->arena()?->slotTable(); + + echo 'tasks completed: ', intdiv($sum, 7), PHP_EOL; + echo 'slot records ever created: ', $slots?->highWaterMark(), PHP_EOL; + echo 'slots still outstanding: ', $slots?->outstanding(), PHP_EOL; + echo 'slots recycled: ', $slots?->recycled(), PHP_EOL; +}); + +echo 'children left: ', parallelChildrenLeft(), PHP_EOL; +?> +--EXPECT-- +tasks completed: 100 +slot records ever created: 1 +slots still outstanding: 0 +slots recycled: 99 +children left: none diff --git a/tools/soak-arena-watermark.php b/tools/soak-arena-watermark.php index 44fcaab..9ffecba 100644 --- a/tools/soak-arena-watermark.php +++ b/tools/soak-arena-watermark.php @@ -40,15 +40,19 @@ * * `--self-test` swaps the scalar payload for a fresh string per round, which is exactly the * documented per-write cost. It must FAIL. A detector nobody has seen fail is a detector nobody - * knows works. + * knows works — and the same goes for the slot detector, so `--leak-slots` takes a slot every round + * without giving it back and must FAIL on the slot series. * * # What else it watches * * - **memory flatness** of the parent process, the same two metrics `soak-memory-flatness.php` uses, * because the arena being flat says nothing about the request heap that reads it; - * - **result-slot consumption**, which is a bump allocation of its own: slots are taken from a - * pre-sized table and never given back, so the soak reports how many of them a round costs and - * sizes the table for the run rather than pretending the supply is endless; + * - **result-slot consumption**, which is the thing issue #16 was about. Slots come out of a + * pre-sized table that cannot grow, and they are now *recycled*: one is taken per + * `spawnParallel()` and handed back when its handle has taken the answer. So the criterion is a + * plateau here too, and a strict one — the table's high-water mark must stop moving entirely + * once the steady state is reached. A climb means slots are not coming back, which is the + * failure that used to kill a long-running pool hours in; * - **leftover children**, because a soak that leaves a worker behind has not proven anything about * a runtime that shuts down. * @@ -59,7 +63,6 @@ namespace Lisachenko\NativePhpCoroutines\Tools\ArenaWatermark; use Lisachenko\NativePhpCoroutines\ChannelInterface; -use Lisachenko\NativePhpCoroutines\Parallel\SharedArena; use Lisachenko\NativePhpCoroutines\Parallel\SharedChannel; use Lisachenko\NativePhpCoroutines\Parallel\Task; use Lisachenko\NativePhpCoroutines\Runtime; @@ -93,14 +96,20 @@ public function run(TaskRuntime $runtime): mixed } } -/** @return array{rounds: int, tasks: int, warmup: int, tolerance: int, workers: int, selfTest: bool} */ +/** + * @return array{rounds: int, tasks: int, warmup: int, tolerance: int, workers: int, slots: int, + * selfTest: bool, leakSlots: bool} + */ function options(): array { - $parsed = getopt('', ['rounds:', 'tasks:', 'warmup:', 'tolerance:', 'workers:', 'self-test', 'help']) ?: []; + $parsed = getopt('', [ + 'rounds:', 'tasks:', 'warmup:', 'tolerance:', 'workers:', 'slots:', 'self-test', 'leak-slots', 'help', + ]) ?: []; if (array_key_exists('help', $parsed)) { echo 'usage: soak-arena-watermark.php [--rounds=40] [--tasks=8] ', - '[--warmup=] [--tolerance=4096] [--workers=2] [--self-test]', PHP_EOL; + '[--warmup=] [--tolerance=4096] [--workers=2] [--slots=64] ', + '[--self-test] [--leak-slots]', PHP_EOL; exit(0); } @@ -115,7 +124,10 @@ function options(): array 'warmup' => max(1, min($warmup, $rounds - 3)), 'tolerance' => max(0, (int) ($parsed['tolerance'] ?? 4096)), 'workers' => max(1, (int) ($parsed['workers'] ?? 2)), + // Deliberately far fewer than the run will spawn: the point is that the supply circulates. + 'slots' => max(1, (int) ($parsed['slots'] ?? 64)), 'selfTest' => array_key_exists('self-test', $parsed), + 'leakSlots' => array_key_exists('leak-slots', $parsed), ]; } @@ -183,6 +195,36 @@ function bytes(int $value): string return sprintf('%.1f KiB', $value / 1024); } +/** + * Slot consumption has to be exactly flat once the steady state is reached. + * + * A slot is a countable record, not a byte watermark: the pool takes one per spawn and gives it + * back when the handle takes the answer, so a workload of constant concurrency creates a constant + * number of records and then stops creating any. One extra record is not noise, it is a slot that + * did not come back — which is exactly what issue #16 was about. + * + * @param list $samples High-water marks of the measured rounds. + * @return array{ok: bool, reason: string} + */ +function slotPlateauVerdict(array $samples): array +{ + if ($samples === []) { + return ['ok' => false, 'reason' => 'no measured rounds']; + } + + $first = $samples[0]; + $last = $samples[count($samples) - 1]; + + if ($last !== $first) { + return [ + 'ok' => false, + 'reason' => sprintf('%d slot records at the first measured round, %d at the last', $first, $last), + ]; + } + + return ['ok' => true, 'reason' => sprintf('flat at %d slot record(s) across the measured rounds', $first)]; +} + /** What "no children" looks like: -1 means this process has none at all. */ function childrenLeft(): string { @@ -204,27 +246,14 @@ function childrenLeft(): string $options = options(); -// Result slots are bump-allocated from a pre-sized table and never given back, so a run that asks -// for more than the table holds fails on exhaustion rather than on the thing it set out to measure. -// Refusing up front is more useful than discovering it two hundred rounds in. -$slotCount = SharedArena::DEFAULT_SLOT_COUNT; -$slotsNeeded = $options['rounds'] * $options['tasks']; - -if ($slotsNeeded > $slotCount) { - printf( - 'SOAK arena-watermark: INCONCLUSIVE — %d rounds of %d tasks need %d result slots and the ' . - 'table holds %d; lower --rounds or --tasks%s', - $options['rounds'], - $options['tasks'], - $slotsNeeded, - $slotCount, - PHP_EOL, - ); +// The table is sized for CONCURRENCY, not for throughput: a slot is taken per spawn and handed back +// when its handle takes the answer, and this soak awaits each task before spawning the next. So the +// supply is deliberately a fraction of what the run will spawn — a table big enough to absorb the +// whole run would prove nothing about slots coming back. +$slotCount = $options['slots']; +$spawns = $options['rounds'] * $options['tasks']; - exit(2); -} - -$runtime = new Runtime(workers: $options['workers'], arenaSize: 64 << 20); +$runtime = new Runtime(workers: $options['workers'], arenaSize: 64 << 20, slots: $slotCount); $arena = $runtime->arena(); if ($arena === null) { @@ -243,8 +272,10 @@ function childrenLeft(): string $runtime->publishTask($scalarTask); echo 'PHP ', PHP_VERSION, ' — ', $options['rounds'], ' rounds of ', $options['tasks'], -' tasks on ', $options['workers'], ' workers, first ', $options['warmup'], ' discarded as warmup', +' tasks on ', $options['workers'], ' workers over ', $slotCount, ' result slots (', $spawns, +' spawns), first ', $options['warmup'], ' rounds discarded as warmup', $options['selfTest'] ? ' (SELF-TEST: a string is rewritten every round, this must FAIL)' : '', +$options['leakSlots'] ? ' (LEAK-SLOTS: a slot is taken and never given back, this must FAIL)' : '', PHP_EOL, PHP_EOL; /** @var list $watermarks */ @@ -253,8 +284,12 @@ function childrenLeft(): string $allocated = []; /** @var list $resident */ $resident = []; +/** @var list $slotHighWater Distinct slot records the table has ever created. */ +$slotHighWater = []; +/** @var list $slotsOutstanding Slots handed out and not yet given back, at the end of a round. */ +$slotsOutstanding = []; -$slotsConsumed = 0; +$slotsRecycled = 0; $runtime->run(static function (TaskRuntime $self) use ( $options, @@ -263,11 +298,14 @@ function childrenLeft(): string &$watermarks, &$allocated, &$resident, - &$slotsConsumed, + &$slotHighWater, + &$slotsOutstanding, + &$slotsRecycled, ): void { $channel = $self->shared('soak.channel'); $counter = $self->shared('soak.counter'); $store = $arena->store(); + $slots = $arena->slotTable(); if (!$channel instanceof ChannelInterface || !$counter instanceof SoakCounter) { throw new \RuntimeException('the soak roots did not bind in this process'); @@ -283,6 +321,12 @@ function childrenLeft(): string $channel->recv(); } + if ($options['leakSlots']) { + // The slot-detector's own failure on demand: a slot taken and never released is the + // pre-recycling behaviour, and the high-water series must climb because of it. + $slots->allocateSlot(); + } + // A scalar property write allocates nothing; a *string* rewrite allocates a block, which is // exactly the documented per-write cost --self-test exists to prove is detectable. $handle = $store->mutableHandle($counter); @@ -300,8 +344,10 @@ function childrenLeft(): string gc_collect_cycles(); - $watermarks[] = $arena->arena()->watermark(); - $allocated[] = memory_get_usage(true); + $watermarks[] = $arena->arena()->watermark(); + $allocated[] = memory_get_usage(true); + $slotHighWater[] = $slots->highWaterMark(); + $slotsOutstanding[] = $slots->outstanding(); $rss = residentSetSize(); if ($rss !== null) { @@ -309,16 +355,18 @@ function childrenLeft(): string } printf( - 'round %3d watermark %12s allocated %10s rss %10s%s', + 'round %3d watermark %12s allocated %10s rss %10s slots %4d high / %3d out%s', $round + 1, bytes($watermarks[count($watermarks) - 1]), bytes($allocated[count($allocated) - 1]), $rss === null ? 'n/a' : bytes($rss), + $slotHighWater[count($slotHighWater) - 1], + $slotsOutstanding[count($slotsOutstanding) - 1], PHP_EOL, ); } - $slotsConsumed = $options['rounds'] * $options['tasks']; + $slotsRecycled = $slots->recycled(); }); $measured = [ @@ -336,15 +384,32 @@ function childrenLeft(): string exit(2); } +$slotSeries = array_values(array_slice($slotHighWater, $options['warmup'])); + echo PHP_EOL; printf( - 'result slots consumed: %d of %d reserved — bump-allocated and never given back%s', - $slotsConsumed, + 'result slots: %d spawns over a table of %d — %d records ever created, %d recycled, %d still out%s', + $spawns, $slotCount, + $slotHighWater === [] ? 0 : $slotHighWater[count($slotHighWater) - 1], + $slotsRecycled, + $slotsOutstanding === [] ? 0 : $slotsOutstanding[count($slotsOutstanding) - 1], + PHP_EOL, +); + +// The slot criterion is stricter than the byte ones on purpose: a slot is either handed back or it +// is not, so a steady state has an exactly flat high-water mark and there is no tolerance to spend. +$slotVerdict = slotPlateauVerdict($slotSeries); + +printf( + '%-10s %s — %s%s', + 'slots', + $slotVerdict['ok'] ? 'plateau' : 'CLIMBING', + $slotVerdict['reason'], PHP_EOL, ); -$failed = false; +$failed = !$slotVerdict['ok']; foreach ($measured as $metric => $samples) { $verdict = trendVerdict($samples, $options['tolerance']); From 4489714d225f32b9eb30d9b943a4bccc2fc156f2 Mon Sep 17 00:00:00 2001 From: Alexander Lisachenko <640114+lisachenko@users.noreply.github.com> Date: Sun, 16 Aug 2026 09:51:53 +0000 Subject: [PATCH 2/2] ci: rerun against the substrate's merged slot recycling The previous run installed the substrate from main before lisachenko/php-shared-data-extension#25 landed there, so the generation-ticket surface this branch consumes did not exist yet. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01U5QRWPfmkZME7hDjU6i5EA