Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
17 changes: 17 additions & 0 deletions src/Parallel/JoinHandle.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 14 additions & 0 deletions src/Parallel/ResultSlot.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
89 changes: 87 additions & 2 deletions src/Parallel/SlotTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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;
Expand All @@ -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
{
Expand All @@ -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
Expand Down Expand Up @@ -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]);
}
}
5 changes: 4 additions & 1 deletion src/Parallel/WorkerSupervisor.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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--
<?php

declare(strict_types=1);

use Lisachenko\NativePhpCoroutines\Parallel\PreforkTaskDirectory;
use Lisachenko\NativePhpCoroutines\Parallel\WorkerSupervisor;
use Lisachenko\NativePhpCoroutines\Scheduler;
use Lisachenko\NativePhpCoroutines\Tests\Support\SumTask;

use function Lisachenko\NativePhpCoroutines\Tests\Support\parallelChildrenLeft;
use function Lisachenko\NativePhpCoroutines\Tests\Support\parallelDeadline;

include __DIR__ . '/../../vendor/autoload.php';
include __DIR__ . '/../Support/parallel.php';

// The answer lives in the slot, not in the table's entry for it, so the entry is worth keeping only
// while something in this process can still ask. Keeping settled entries instead costs a ResultSlot
// per spawn for the whole run — invisible to memory_get_usage(true) at its 2 MiB chunk granularity
// and free of arena memory, so it surfaces only as the parent's RSS climbing (issue #24).

$scheduler = new Scheduler();

$tasks = new PreforkTaskDirectory();
$task = new SumTask(20, 22);
$tasks->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