diff --git a/AGENTS.md b/AGENTS.md
index 6f9213b..f9d49eb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -249,15 +249,41 @@ 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. **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.
+- **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 the `JoinHandle`
+ holding it is awaited or collected, so the supply limits **concurrency**, not throughput. One kind
+ does not come back: a slot whose worker died before settling it, which is still pending in shared
+ memory where 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 has two lifetimes and one counter, and confusing them is how both bugs happened.** The
+ **local view** (`SlotTable`'s entry) is per-process bookkeeping; the **shared record** is the
+ substrate's. `open()`/`adopt()` hand out one claim, `JoinHandle` carries it and gives it back once,
+ and when the last claim goes: the view is always forgotten, whatever this process's role, while the
+ record goes back only if this process **owns** it and the family really settled it. Retaining
+ settled views costs a `ResultSlot` per spawn for the whole run — invisible to every arena counter
+ and to `memory_get_usage(true)` at its 2 MiB chunk granularity, surfacing only as the parent's RSS
+ climbing (issue #24). Retaining records exhausts the table (issue #16). A pending slot's view is
+ never forgotten whatever its claims: `failPendingOf()` still has to turn it into a throw.
+- **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 the record 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 handle goes.
+- **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.
+- **A handle collected without ever being awaited discards its answer and recycles the slot.**
+ Spawning without awaiting says the result is not wanted, and the alternative — keeping the record
+ for the life of the run — is the exhaustion bug itself. Nothing is silently misled: a sibling that
+ attached to the id gets a generation refusal, not the next task's answer.
## Environment
@@ -346,15 +372,21 @@ php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-preemption.php --seconds=30
| --- | --- | --- |
| `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 |
+| `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 |
| `tools/soak-preemption.php` | a continuous preemptive run of call-free burners, parkers and socket-pair IO: every burner's arithmetic matches the uninterrupted reference, memory stays flat, every coroutine finishes and none is left parked in the interrupt callback, and the process reaches its own verdict instead of a fatal | 0 correct and flat, 1 a check failed, 2 inconclusive — including a run that was never preempted, which measured a cooperative workload |
-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. `soak-preemption.php
---self-test` corrupts one burner's sum by a single unit — the smallest wrong answer a lost resume
-could produce — and `--inject-leak` retains a block per round; both must come back FAIL.
+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, and
+`--leak-slots` takes a slot every round without giving it back and must fail on the **slot** series
+with the byte series still flat. `soak-preemption.php --self-test` corrupts one burner's sum by a
+single unit — the smallest wrong answer a lost resume could produce — and `--inject-leak` retains a
+block per round; both must come back FAIL.
**The preemption soak is the exception to "CI runs tests and static-analysis only".** It runs there,
20 seconds per minor, because its subject is the one thing a two-second test cannot show: the suite's
diff --git a/README.md b/README.md
index e8eebd7..3c670ca 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,64 @@ $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 the `JoinHandle` holding it is awaited or collected — whichever comes first — 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 |
+| spawn and never await, handle dropped | 1, until the handle is collected |
+| spawn and never await, handle kept | 1, for as long as the handle is kept |
+| a task whose worker died before settling | 1, for the rest of the run |
+
+Only the last row really consumes the budget. 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; it is deliberately left out of circulation.
+
+A handle nobody awaits is not a leak: dropping it recycles the slot and **discards the answer**,
+which is what spawning without awaiting asks for. Dropping one whose task has *not* settled yet
+keeps the slot until it does, because a worker that has not answered may still write to the record —
+so firing tasks off faster than the pool drains them still costs one slot per task in flight, which
+is the same concurrency rule as everywhere else, and overrunning the table is the same typed
+refusal. The value itself is not lost to the arena — the
+arena frees nothing — only the slot record's claim on it goes. If you want the result, await; if you
+want to await it later or elsewhere, keep the handle or the id, and note that an id whose owner has
+already released it is refused rather than answered.
+
+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 15f2932..c6d9e4a 100644
--- a/src/Parallel/JoinHandle.php
+++ b/src/Parallel/JoinHandle.php
@@ -27,9 +27,40 @@
* 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
+ *
+ * A slot is expensive to hold: the local view costs a few hundred bytes for the life of the run
+ * (issue #24) and the shared record costs one out of a supply that is pre-sized in the arena and
+ * cannot grow (issue #16). This handle holds exactly **one claim** on both, and gives it back at
+ * the first of two moments:
+ *
+ * - **when it is awaited.** The answer is taken out of the slot, kept here, and the claim released
+ * immediately — so a batch that spawns N tasks and awaits them in a loop is down to one live slot
+ * by the end of the loop rather than N until the array of handles goes out of scope. Awaiting
+ * again replays what was kept, the same value or the same throwable, and never reads shared
+ * memory a second time.
+ * - **when it is collected**, for a handle nobody ever awaited. That is what keeps a fire-and-forget
+ * `spawnParallel()` loop from retaining anything at all.
+ *
+ * Whichever comes first, it happens **once**: two releases for one claim would drop somebody else's.
+ *
+ * The order within the first 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 kept here. */
+ private bool $taken = false;
+
+ /** Whether this handle's one claim has already gone back, from await() or from the destructor. */
+ private bool $released = false;
+
+ private mixed $outcome = null;
+
+ private ?\Throwable $failure = null;
+
public function __construct(
private readonly SlotTable $slots,
private readonly SchedulerInterface $scheduler,
@@ -38,20 +69,28 @@ public function __construct(
) {}
/**
- * The claim this handle was given by `open()`/`adopt()` goes back when the handle does.
+ * A handle that was never awaited still gives its claim back.
*
* 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
+ * the moment the slot 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.
+ * `tools/soak-arena-watermark.php` reports as RSS with both arena counters flat (issue #24).
+ *
+ * For a handle that **was** awaited this is a no-op: the claim went back then, which is the
+ * point of the guard in {@see self::relinquish()}.
*
- * The shared slot is untouched: its answer, and its id, stay in the arena.
+ * A settled slot whose handle is collected without ever being awaited has its shared record
+ * recycled too, and the answer in it is discarded — deliberately. Spawning without awaiting is
+ * a statement that the result is not wanted, and the alternative is worse: a fire-and-forget
+ * loop would consume the slot supply exactly as it did before recycling existed, which is the
+ * bug this all exists to fix. Nothing is silently misled by it, because a sibling that attached
+ * to the id gets a generation refusal rather than the next task's answer.
*/
public function __destruct()
{
- $this->slots->release($this->slotId);
+ $this->relinquish();
}
public function slotId(): int
@@ -61,6 +100,10 @@ public function slotId(): int
public function isComplete(): bool
{
+ if ($this->taken) {
+ return true;
+ }
+
$slot = $this->slots->slot($this->slotId);
if (!$slot->complete) {
@@ -75,6 +118,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
@@ -98,16 +149,42 @@ 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->relinquish();
+
+ if ($this->failure !== null) {
+ throw $this->failure;
}
- // 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;
+ return $this->outcome;
+ }
+
+ /**
+ * Hand back this handle's one claim, at most once.
+ *
+ * Both callers are legitimate and both can happen to the same handle - await() gives the claim
+ * back as soon as the answer is safely copied out, and the destructor covers a handle that was
+ * never awaited - so the guard is what keeps the pair from counting as two. Releasing twice
+ * would take a claim belonging to another handle on the same slot, and `attachResult()` of a
+ * slot this process opened is exactly that situation.
+ */
+ private function relinquish(): void
+ {
+ if ($this->released) {
+ return;
}
- return ValueCodec::fromRecord($slot->value ?? TaggedRecord::nil());
+ $this->released = true;
+
+ $this->slots->release($this->slotId);
}
}
diff --git a/src/Parallel/ResultSlot.php b/src/Parallel/ResultSlot.php
index a74c868..f90b3f4 100644
--- a/src/Parallel/ResultSlot.php
+++ b/src/Parallel/ResultSlot.php
@@ -32,11 +32,30 @@
*
* 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 that end its two lifecycles
+ *
+ * The local view here and the shared record in the substrate both have to end, and they end at
+ * different moments for different reasons. {@see self::$claims} decides *when* — it is the count of
+ * handles in this process that can still ask for the result — and these two decide *what* is ended
+ * when it reaches zero:
+ *
+ * - {@see self::$owned} — this process allocated the slot. Only an owner gives the shared record
+ * back; a process that attached to somebody else's slot has no idea who else is still reading it.
+ * - {@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 recycling it would hand a live record to the next task while
+ * a zombie worker may yet write to it. Those records stay out of circulation on purpose.
+ *
+ * Neither field affects the local view: that goes when the last claim does, whatever the role.
*/
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;
+
/** The outcome as a record, once complete and successful — the path that needs no arena. */
public ?TaggedRecord $value = null;
@@ -61,17 +80,20 @@ final class ResultSlot
*
* 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.
+ * says so — one claim per handle, given back when the handle is awaited or collected, whichever
+ * comes first. 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.
+ * The same moment ends the **shared** record's life, but only when {@see self::$owned} and
+ * {@see self::$sharedSettled} both allow it: slots are recycled through the substrate's free
+ * list, and giving one back is a claim that nobody will read it through this ticket again.
*/
public int $claims = 0;
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 849acc5..1f8c542 100644
--- a/src/Parallel/SlotTable.php
+++ b/src/Parallel/SlotTable.php
@@ -15,6 +15,7 @@
use Lisachenko\NativePhpCoroutines\Exception\ParallelTaskException;
use Lisachenko\NativePhpCoroutines\Parallel\Protocol\TaggedRecord;
use Lisachenko\NativePhpCoroutines\SchedulerInterface;
+use Lisachenko\SharedData\Ipc\IpcException;
use Lisachenko\SharedData\Ipc\SharedError;
use Lisachenko\SharedData\Ipc\SlotResult;
@@ -38,22 +39,47 @@
* 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
+ * # Two lifecycles, one counter
*
- * 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.
+ * A slot has a **local view** — the entry in this table — and a **shared record** in the substrate.
+ * They are not the same thing and they do not end at the same moment, but one number decides both:
+ * the count of {@see JoinHandle}s in this process that can still ask for the result.
+ * {@see self::open()} and {@see self::adopt()} hand out one claim each, a handle carries it, and the
+ * handle gives it back when it is awaited or collected, whichever comes first.
*
- * 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.
+ * **The local view** is per-process bookkeeping: the identity, the parked coroutines and the answer
+ * once it has been materialized. It is dropped as soon as the slot has settled and nothing here
+ * holds a claim or is parked on it, **whatever this process's role** — owner or adopter alike.
+ * Keeping settled views 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, far
+ * below the 2 MiB chunk granularity of `memory_get_usage(true)` and costing 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.
+ * **The shared record** is the substrate's, and giving it back is what stops a long-running pool
+ * exhausting a supply that is pre-sized in the arena and cannot grow (issue #16). It goes back only
+ * when this process **owns** it — an adopter never releases, because it cannot know who else in the
+ * family is still reading — and only when the family really settled it.
+ *
+ * **When releasing the record 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()`. So the record can
+ * go back the moment the last claim does, with 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.
+ *
+ * One kind of slot deliberately does **not** go 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. That is a
+ * memory-safety question rather than a bookkeeping one, which is why it is answered differently from
+ * a result nobody read. Its local view is still dropped.
*/
final class SlotTable
{
@@ -96,8 +122,10 @@ public function liveViews(): int
/**
* 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.
+ * 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. 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
{
@@ -118,32 +146,56 @@ public function open(int $workerId): ResultSlot
* 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.
+ *
* 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.
+ * the view survives until both handles are gone. An adopter is not an owner, though: it never
+ * releases the shared 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) {
+ ++$slot->claims;
+
+ return $slot;
}
- $slot = $this->slots[$slotId] ??= new ResultSlot($slotId, $workerId);
+ $result = $arena->slotTable()->readSlot($slotId);
+ $slot = $this->slots[$slotId] = new ResultSlot($slotId, $workerId, owned: false);
+ // Claimed BEFORE it is settled, and the order is load-bearing: settle() ends by forgetting
+ // a settled slot that nothing holds, so claiming afterwards would bump a view that had
+ // already been dropped from the table and hand back a slot await() cannot find.
++$slot->claims;
+ if (!$result->isPending()) {
+ $this->settle($slot, $result);
+ }
+
return $slot;
}
/**
- * Give up one claim on a slot's local view, and forget the view if that was the last one.
+ * Give up one claim, and end both of the slot's lifecycles 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.
+ * releases when it is awaited or collected, whichever comes first, so the claim lives exactly as
+ * long as something in this process can still ask for the result. Two handles may name one slot
+ * (`attachResult()` of a slot this process opened is exactly that) and only the last of them
+ * ends anything. 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
{
@@ -290,6 +342,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;
@@ -333,13 +390,21 @@ private function wake(ResultSlot $slot): void
}
/**
- * Drop the local view of a slot that has settled and that nothing in this process still holds.
+ * End both of a settled slot's lifecycles once nothing in this process still holds it.
*
- * 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.
+ * 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. So
+ * does one with a coroutine still parked on it — a waiter is a reader that has not read yet.
+ *
+ * Past that gate the two lifecycles part company:
+ *
+ * - the **local view** always goes. Whatever this process's role, nothing here can ask for the
+ * result any more, and the entry is only bookkeeping.
+ * - the **shared record** goes back to the substrate's free list only if this process owns it
+ * and the family really settled it. An adopter never releases; and a slot completed locally
+ * because its worker died is still pending in shared memory, where a zombie may yet write to
+ * it, so recycling it could let that write land on another task. The substrate refuses such a
+ * release for exactly that reason, and the `sharedSettled` guard is what keeps us from asking.
*/
private function forgetIfSettled(ResultSlot $slot): void
{
@@ -348,5 +413,32 @@ private function forgetIfSettled(ResultSlot $slot): void
}
unset($this->slots[$slot->id]);
+
+ if (!$slot->owned || !$slot->sharedSettled) {
+ return;
+ }
+
+ $this->releaseShared($slot->id);
+ }
+
+ /**
+ * Hand a settled record back to the substrate, from a path that may be a destructor.
+ *
+ * Every caller reaching here has already checked that this process owns the slot, that the
+ * family settled it and that the claim just given up was the last — which is precisely the
+ * substrate's precondition, so the refusal below should be unreachable. It is caught anyway
+ * because this can run from `JoinHandle::__destruct()`, and an exception thrown out of a
+ * destructor during shutdown is a fatal that buries whatever real problem caused it. The cost
+ * of swallowing one is a slot that stays out of circulation until teardown; the cost of not
+ * swallowing it is a process that dies reporting the wrong thing.
+ */
+ private function releaseShared(int $slotId): void
+ {
+ try {
+ $this->arena?->slotTable()->releaseSlot($slotId);
+ } catch (IpcException) {
+ // Deliberately dropped; see above. Nothing is corrupted - the substrate refuses rather
+ // than recycling anything it is unsure of.
+ }
}
}
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/testACompletedResultSlotIsNotRetainedByItsWaiter.phpt b/tests/Functional/testACompletedResultSlotIsNotRetainedByItsWaiter.phpt
index c426d22..88ca2c7 100644
--- a/tests/Functional/testACompletedResultSlotIsNotRetainedByItsWaiter.phpt
+++ b/tests/Functional/testACompletedResultSlotIsNotRetainedByItsWaiter.phpt
@@ -24,6 +24,11 @@ include __DIR__ . '/../Support/parallel.php';
// 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).
+//
+// A handle gives its claim back at the FIRST of two moments: when it is awaited, or when it is
+// collected. So the view is already gone on the line after await() and dropping the handle changes
+// nothing — that path is covered by testAnUnawaitedHandleGivesItsSlotBackWhenItIsCollected.phpt,
+// which is the case the destructor still exists for.
$scheduler = new Scheduler();
@@ -48,6 +53,7 @@ $main = $scheduler->spawn(function () use ($supervisor, $task): void {
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();
@@ -65,7 +71,7 @@ echo 'children left: ', parallelChildrenLeft(), "\n";
--EXPECT--
views while the result is outstanding: 1
result: 42
-views after await, handle still held: 1
+views after await, handle still held: 0
views after the handle is dropped: 0
views after 8 more round trips: 0
children left: none
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/tests/Functional/testAWorkerKilledInsideACriticalSectionReportsTheRecoveredLock.phpt b/tests/Functional/testAWorkerKilledInsideACriticalSectionReportsTheRecoveredLock.phpt
index cf55923..1426cb0 100644
--- a/tests/Functional/testAWorkerKilledInsideACriticalSectionReportsTheRecoveredLock.phpt
+++ b/tests/Functional/testAWorkerKilledInsideACriticalSectionReportsTheRecoveredLock.phpt
@@ -91,5 +91,5 @@ echo 'children left: ', parallelChildrenLeft(), PHP_EOL;
--EXPECT--
the worker holds the result-slot lock: yes
the worker is gone before the parent reads a slot: yes
-worker #0 died: it died holding an arena lock (EOWNERDEAD); the lock was recovered, but whatever it was writing is not an answer; 1 result slot(s) can never complete: #0
+worker #0 died: it died holding an arena lock (EOWNERDEAD); the lock was recovered, but whatever it was writing is not an answer; 1 result slot(s) can never complete: #0/gen1
children left: none
diff --git a/tests/Functional/testAnUnawaitedHandleGivesItsSlotBackWhenItIsCollected.phpt b/tests/Functional/testAnUnawaitedHandleGivesItsSlotBackWhenItIsCollected.phpt
new file mode 100644
index 0000000..baca7b7
--- /dev/null
+++ b/tests/Functional/testAnUnawaitedHandleGivesItsSlotBackWhenItIsCollected.phpt
@@ -0,0 +1,65 @@
+--TEST--
+A settled handle that is collected without ever being awaited gives its result slot back to the family
+--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(20.0, 'an unawaited handle giving its slot back');
+
+ $slots = $runtime->arena()?->slotTable();
+ $handle = $self->spawnParallel($task);
+
+ // Settled but never awaited. A slot that is still pending is never recycled - a worker that has
+ // not answered yet may still write to it - so the drop has to happen after it has settled for
+ // this to be about the handle rather than about timing.
+ parallelWaitFor(static fn(): bool => $handle->isComplete(), 10.0);
+
+ echo 'settled, never awaited - slots outstanding: ', $slots?->outstanding(), PHP_EOL;
+
+ unset($handle);
+
+ echo 'after the handle is collected: ', $slots?->outstanding(), PHP_EOL;
+
+ // Only reachable if the record really went back on the free list
+ echo 'a second task gets the recycled record: ', $self->spawnParallel($task)->await(), PHP_EOL;
+ echo 'slot records ever created: ', $slots?->highWaterMark(), PHP_EOL;
+});
+
+echo 'children left: ', parallelChildrenLeft(), PHP_EOL;
+?>
+--EXPECT--
+settled, never awaited - slots outstanding: 1
+after the handle is collected: 0
+a second task gets the recycled record: 42
+slot records ever created: 1
+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']);