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
64 changes: 48 additions & 16 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
62 changes: 61 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 |
Expand Down
21 changes: 20 additions & 1 deletion src/Exception/WorkerCrashedException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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)),
);
}

Expand Down Expand Up @@ -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);
}
}
Loading