diff --git a/AGENTS.md b/AGENTS.md index 0349c2e..da8dfd5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -241,7 +241,13 @@ in every process. 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. + assumes. **The per-process *view* of a slot is a different lifetime and must not follow it:** + `SlotTable` hands out a claim with every `open()`/`adopt()`, `JoinHandle` releases it in its + destructor, and a settled slot with no claims and no waiters is forgotten. Retaining settled views + instead costs a `ResultSlot` per spawn for the whole run — which no arena counter can see and + `memory_get_usage(true)` cannot either at its 2 MiB chunk granularity, so it surfaces only as the + parent's RSS climbing. That was issue #24; the shared slot and its answer are untouched by the + forget, and `adopt()` takes a fresh view whenever one is wanted again. ## Environment diff --git a/src/Parallel/JoinHandle.php b/src/Parallel/JoinHandle.php index 4997135..15f2932 100644 --- a/src/Parallel/JoinHandle.php +++ b/src/Parallel/JoinHandle.php @@ -37,6 +37,23 @@ public function __construct( private readonly int $workerId, ) {} + /** + * The claim this handle was given by `open()`/`adopt()` goes back when the handle does. + * + * A handle is the only thing in this process that can still ask for the result, so its death is + * the moment the slot's **local view** stops being worth keeping. Without this a steady-state + * `spawnParallel()->await()` loop retains one `ResultSlot` per spawn for the whole run — a few + * hundred bytes a spawn that never show up in `memory_get_usage(true)` (2 MiB chunk granularity) + * and never touch the arena watermark, which is exactly the climb + * `tools/soak-arena-watermark.php` reports as RSS with both arena counters flat. + * + * The shared slot is untouched: its answer, and its id, stay in the arena. + */ + public function __destruct() + { + $this->slots->release($this->slotId); + } + public function slotId(): int { return $this->slotId; diff --git a/src/Parallel/ResultSlot.php b/src/Parallel/ResultSlot.php index 9bf7e0b..a74c868 100644 --- a/src/Parallel/ResultSlot.php +++ b/src/Parallel/ResultSlot.php @@ -56,6 +56,20 @@ final class ResultSlot */ public array $waiters = []; + /** + * How many {@see JoinHandle}s in this process can still ask for this result. + * + * The local view is bookkeeping, not the answer: the answer is in shared memory and stays there. + * So the view is worth keeping only while somebody here can still read it, and the count is what + * says so — one claim per handle, released when the handle is collected. When the last claim + * goes and the slot has settled, {@see SlotTable} forgets it, which is what keeps a steady-state + * spawn/await loop from retaining a `ResultSlot` per spawn for the life of the run. + * + * The **shared** slot id is a different thing and is not affected: ids are bump-allocated from a + * pre-sized table and never recycled, by design. + */ + public int $claims = 0; + public function __construct( public readonly int $id, public readonly int $workerId, diff --git a/src/Parallel/SlotTable.php b/src/Parallel/SlotTable.php index cb1352f..849acc5 100644 --- a/src/Parallel/SlotTable.php +++ b/src/Parallel/SlotTable.php @@ -37,6 +37,23 @@ * 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. + * + * # A local view lives as long as somebody here can still read it, and no longer + * + * The authority is shared memory, so the entry in this table is only a per-process convenience: the + * identity, the parked coroutines and the answer once it has been materialized. It is therefore + * **claimed** — {@see self::open()} and {@see self::adopt()} hand out one claim, a {@see JoinHandle} + * carries it, and the handle's destructor gives it back. A settled slot with no claims and no + * waiters is forgotten. + * + * Keeping settled slots instead is a real leak and a quiet one: a `spawnParallel()->await()` loop + * retains a `ResultSlot` per spawn (~220 bytes with its array bucket) for the life of the run, which + * is far below the 2 MiB chunk granularity of `memory_get_usage(true)` and costs the arena nothing, + * so it shows up only as the parent's RSS climbing — the shape reported in issue #24. + * + * Forgetting the view does **not** free the shared slot. Ids are bump-allocated from a pre-sized + * table and never recycled, on purpose, and the settled answer stays readable by every process of + * the family — {@see self::adopt()} takes a fresh view of it whenever one is wanted again. */ final class SlotTable { @@ -64,13 +81,31 @@ public function isShared(): bool return $this->arena !== null; } - /** Reserve a slot for work about to be dispatched to $workerId. */ + /** + * How many slots this process still holds a local view of. + * + * A diagnostic, and the one a memory gate wants: in a steady state it tracks the work actually + * in flight, so a number that grows with the *total* number of spawns is the leak this class's + * claim counting exists to prevent. + */ + public function liveViews(): int + { + return count($this->slots); + } + + /** + * Reserve a slot for work about to be dispatched to $workerId. + * + * The slot comes back holding **one claim**, which the caller owns and must hand to a + * {@see JoinHandle} — or {@see self::release()} itself if the dispatch never happens. + */ public function open(int $workerId): ResultSlot { $id = $this->arena?->slotTable()->allocateSlot() ?? $this->nextId++; $slot = new ResultSlot($id, $workerId); + $slot->claims = 1; $this->slots[$slot->id] = $slot; return $slot; @@ -82,6 +117,9 @@ 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. + * + * Like {@see self::open()} this hands out a claim, so adopting a slot twice is two claims and + * the view survives until both handles are gone. */ public function adopt(int $slotId, int $workerId = -1): ResultSlot { @@ -92,7 +130,32 @@ public function adopt(int $slotId, int $workerId = -1): ResultSlot ); } - return $this->slots[$slotId] ??= new ResultSlot($slotId, $workerId); + $slot = $this->slots[$slotId] ??= new ResultSlot($slotId, $workerId); + + ++$slot->claims; + + return $slot; + } + + /** + * Give up one claim on a slot's local view, and forget the view if that was the last one. + * + * Paired with the claim {@see self::open()} and {@see self::adopt()} hand out — {@see JoinHandle} + * releases in its destructor, so the view lives exactly as long as something in this process can + * still ask for the result. Releasing a slot this table does not know is a no-op: it has already + * been forgotten, which is the same outcome. + */ + public function release(int $slotId): void + { + $slot = $this->slots[$slotId] ?? null; + + if ($slot === null) { + return; + } + + $slot->claims = max(0, $slot->claims - 1); + + $this->forgetIfSettled($slot); } public function slot(int $slotId): ResultSlot @@ -263,5 +326,27 @@ private function wake(ResultSlot $slot): void $this->scheduler->schedule($waiter); } } + + // A slot nobody holds any more is settled here for the last time; keeping its view would + // retain a ResultSlot per spawn for the rest of the run. + $this->forgetIfSettled($slot); + } + + /** + * Drop the local view of a slot that has settled and that nothing in this process still holds. + * + * Only ever a *local* forget. The shared slot keeps its answer and keeps its id: any process of + * the family — including this one, through {@see self::adopt()} — can read it again afterwards, + * because the authority was never this table. A slot that is still pending stays, whatever its + * claim count: the supervisor owes it either an answer or a crash, and + * {@see self::failPendingOf()} has to be able to find it. + */ + private function forgetIfSettled(ResultSlot $slot): void + { + if ($slot->claims > 0 || !$slot->complete || $slot->waiters !== []) { + return; + } + + unset($this->slots[$slot->id]); } } diff --git a/src/Parallel/WorkerSupervisor.php b/src/Parallel/WorkerSupervisor.php index 85fe13e..6ce69fd 100644 --- a/src/Parallel/WorkerSupervisor.php +++ b/src/Parallel/WorkerSupervisor.php @@ -221,8 +221,11 @@ public function spawn(Task $task, ?int $worker = null): JoinHandleInterface $target->dispatch($slot->id, $address); } catch (\Throwable $failure) { // The worker went away between the placement and the write. The slot exists, so it must - // be completed with the failure rather than left for a waiter to park on forever. + // be completed with the failure rather than left for a waiter to park on forever — and + // the claim open() handed out is given back here, because no JoinHandle will be built to + // carry it. $this->slots->completeWithError($slot->id, $failure); + $this->slots->release($slot->id); throw $failure; } diff --git a/tests/Functional/testACompletedResultSlotIsNotRetainedByItsWaiter.phpt b/tests/Functional/testACompletedResultSlotIsNotRetainedByItsWaiter.phpt new file mode 100644 index 0000000..c426d22 --- /dev/null +++ b/tests/Functional/testACompletedResultSlotIsNotRetainedByItsWaiter.phpt @@ -0,0 +1,71 @@ +--TEST-- +The local view of a result slot is dropped once the handle that could still read it is gone +--INI-- +ffi.enable=1 +opcache.jit=off +error_reporting=E_ALL & ~E_DEPRECATED +--FILE-- +register($task); + +$supervisor = new WorkerSupervisor($scheduler, $tasks); +$supervisor->start(1); + +$main = $scheduler->spawn(function () use ($supervisor, $task): void { + parallelDeadline(5.0, 'the result slot bookkeeping'); + + $slots = $supervisor->slots(); + + $handle = $supervisor->spawn($task); + echo 'views while the result is outstanding: ', $slots->liveViews(), "\n"; + + echo 'result: ', $handle->await(), "\n"; + echo 'views after await, handle still held: ', $slots->liveViews(), "\n"; + + unset($handle); + echo 'views after the handle is dropped: ', $slots->liveViews(), "\n"; + + // The steady state the soak drives: nothing is retained, however many round trips happen. + for ($round = 0; $round < 8; ++$round) { + $supervisor->spawn($task)->await(); + } + + echo 'views after 8 more round trips: ', $slots->liveViews(), "\n"; +}); + +$scheduler->runUntil($main); + +$supervisor->shutdown(); + +echo 'children left: ', parallelChildrenLeft(), "\n"; +?> +--EXPECT-- +views while the result is outstanding: 1 +result: 42 +views after await, handle still held: 1 +views after the handle is dropped: 0 +views after 8 more round trips: 0 +children left: none