From 8f761313c984720eef30ffd209a8cd0230a7ab82 Mon Sep 17 00:00:00 2001 From: Alexander Lisachenko <640114+lisachenko@users.noreply.github.com> Date: Sun, 16 Aug 2026 09:12:08 +0000 Subject: [PATCH] fix(parallel): forget a result slot's local view once nothing can read it SlotTable::open() put a ResultSlot in $slots and nothing ever took one out, so a spawnParallel()->await() loop retained one per spawn - about 220 bytes with its array bucket - for the whole life of the run. Nothing reports it: the arena watermark is byte-flat because a published task and an integer result allocate nothing, and memory_get_usage(true) is flat because 2 MiB chunk granularity swallows it for hundreds of rounds. The only symptom is the parent's RSS climbing, which is what issue #24 measured (24 KiB over 40 rounds, 192 KiB over 120) and read as native memory outside the PHP heap. It is not native: memory_get_usage(FALSE) climbs 1.76 KiB per 8-spawn round, which is the retention exactly. The answer was never in the entry - it is in shared memory - so the entry is worth keeping only while something in this process can still ask for it. open() and adopt() now hand out a claim, JoinHandle carries it and releases it in its destructor, and a settled slot with no claims and no waiters is dropped. A pending slot is never dropped, whatever its claim count, because failPendingOf() still has to be able to turn it into a throw. The shared slot keeps its answer and its id; adopt() takes a fresh view of it whenever one is wanted again. Measured on tools/soak-arena-watermark.php, tolerance unchanged at 4 KiB: RSS climb 24.0 KiB -> 12.0 KiB at 40 rounds. The remainder was the substrate faulting its pre-sized slot table in a page at a time and is fixed there; with both, the soak reports a plateau at 40 and at 120 rounds and --self-test still FAILs. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01U5QRWPfmkZME7hDjU6i5EA --- AGENTS.md | 8 +- src/Parallel/JoinHandle.php | 17 ++++ src/Parallel/ResultSlot.php | 14 +++ src/Parallel/SlotTable.php | 89 ++++++++++++++++++- src/Parallel/WorkerSupervisor.php | 5 +- ...tedResultSlotIsNotRetainedByItsWaiter.phpt | 71 +++++++++++++++ 6 files changed, 200 insertions(+), 4 deletions(-) create mode 100644 tests/Functional/testACompletedResultSlotIsNotRetainedByItsWaiter.phpt 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