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
17 changes: 15 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,16 @@ shared struct before it aborts* — siblings then read plausible garbage with no
(native-php-coroutines#24). Touch the block once, in the creating process, before the fork: it
does not add memory, it decides when the memory is charged, and afterwards a climb really is
a climb.
- **Recycling is in-place reuse, never a free.** A fixed-record table may hand a record back out
— `Ipc\ResultSlotTable` does, through a free list threaded through the slot records themselves
— but the block stays where it is and nothing is unmapped, so the rule above is untouched. A
recycled record needs an **identity that changes with it**: without the generation in
`Ipc\SlotTicket`, an id held one moment too long addresses the next occupant and is answered
with its data. Every verb re-checks that generation; a mismatch is a typed refusal naming both.
Recycling does **not** make the prefault above redundant, and the two must not be confused: a
steady-state pool reuses a handful of records and would look page-flat by accident, while a
workload whose concurrency genuinely grows still walks into fresh records. The prefault is what
makes that second case flat too, so residency stops being a function of the workload at all.
- Gate memory claims with the soaks, and watch the **watermark plateau** rather than the peak:

```bash
Expand All @@ -136,8 +146,11 @@ that refusal is the feature; never soften it into a migration.
Keep the **version history table in `Registry`'s docblock current**: one line per version,
saying what changed and why a reader of the older layout would be wrong. A consumer structure
that merely lives in the arena payload and adds no field to a registry record does **not** bump
the version (`Ipc\SharedChannel`, `Ipc\SharedArray`, `Ipc\ClosureProvenance`); it publishes
itself in the roots directory instead.
the version (`Ipc\SharedChannel`, `Ipc\SharedArray`, `Ipc\ClosureProvenance`,
`Ipc\ResultSlotTable`); it publishes itself in the roots directory instead. Such a structure
carries its **own** guard when its record shape changes — `ResultSlotTable::FORMAT` is one, a
header word checked at `attach()` — because "does not bump `LAYOUT_VERSION`" must not mean
"changes shape with nothing refusing a reader of the old one".

## 8. Frozen-mode invariants that must survive every change

Expand Down
23 changes: 18 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,16 +332,27 @@ $wake = WakeRegistry::create($arena); // socket pairs, created
$jobs = SharedChannel::create($allocator, $codec, $wake, 64, name: 'jobs');
$results = ResultSlotTable::create($allocator, $codec, $wake, 1024);

$slot = $results->allocateSlot();
$slot = $results->allocateSlot(); // a TICKET: slot index + generation
if (pcntl_fork() === 0) {
[$job, $ok] = $jobs->recv(); // parks on the socket, wakes on an event
$results->complete($slot, process($job)); // writes a record, pokes the waiter
exit(0);
}
$jobs->send($sharedObject); // an address, never a copy
$value = $results->await($slot)->value; // read straight out of shared memory
$results->releaseSlot($slot); // read and done with: back on the free list
```

**Slots are recycled, and a slot id is a ticket rather than an index.** The arena is bump-only
and nothing frees a block, so `releaseSlot()` reuses the slot *record in place* through a free
list threaded through the slots themselves. What makes that safe is the generation packed
beside the index in every id (`Ipc\SlotTicket`, 16 bits each, so the whole thing still fits the
uint32 a wake event carries): the generation moves the instant an owner releases its claim, and
reading, awaiting, completing or releasing a slot with an out-of-date ticket is an
`IpcException` naming the slot and both generations — never another task's result. A slot
nobody releases simply stays out of circulation, and a slot whose 16-bit generation is used up
is retired rather than wrapped, so no handle is ever revived by a counter coming back round.

Values move as **16-byte records**: `uint8 tag | 7 pad | uint64 payload`, where the payload
is the value itself (`int`, `float`, nothing at all for `null`/`bool`) or an arena address
(an interned `zend_string`, a shared `zend_object`, a `SharedArray`, the record of a shared
Expand All @@ -361,7 +372,7 @@ lost, and every blocking loop also re-polls on a bounded slice.
|---|---|
| `SharedChannel` | ring of records + waiter tables under a dedicated robust mutex; capacity 0 is a true cross-process rendezvous; `close()` crosses processes (receivers drain, then `[null, false]`; senders throw) |
| `SharedArray` | fixed-capacity vector of records, `ArrayAccess`/`Countable`/`IteratorAggregate`, stripe-locked |
| `ResultSlotTable` | futures: `allocateSlot()` / `complete()` / `completePanic()` / `await()`, with panics travelling as a shared `SharedError` object |
| `ResultSlotTable` | futures: `allocateSlot()` / `complete()` / `completePanic()` / `await()` / `releaseSlot()`, ids carrying a generation so a recycled slot never answers an old handle, and panics travelling as a shared `SharedError` object |
| `SharedMutex` | robust process-shared mutex with trylock-and-backoff, `EOWNERDEAD` recovered and reported |
| `AtomicInt` | one shared cell: plain aligned get/set, stripe-locked `add()`/`compareAndSet()` |
| `SharedWaitGroup` | counter plus waiter table; `add()`/`done()`/`wait()`, negative counts throw |
Expand Down Expand Up @@ -480,9 +491,11 @@ $channel->recv($timeout): array; // [value, true] | [null,
$channel->close(): void; // crosses processes, drains first
$channel->notificationStream(); // park your own event loop on this
$slots = ResultSlotTable::create($allocator, $codec, $wake, $capacity);
$slots->allocateSlot(): int;
$slots->complete($id, $value): void; // completePanic($id, SharedError::capture(...))
$slots->await($id, $timeout): SlotResult; // readSlot() never blocks
$slots->allocateSlot(): int; // a ticket: SlotTicket::indexOf()/generationOf()
$slots->complete($ticket, $value): void; // completePanic($ticket, SharedError::capture(...))
$slots->await($ticket, $timeout): SlotResult; // readSlot() never blocks
$slots->releaseSlot($ticket): void; // settled + read => back on the free list
$slots->outstanding(); $slots->highWaterMark(); // what a soak watches plateau

// shared closures (registration is the acceptance test; everything else is refused)
$closures = ClosureProvenance::create($allocator, $store); // pre-fork
Expand Down
9 changes: 7 additions & 2 deletions docs/shared-memory-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,13 @@ sentence.
cross-process rendezvous; `close()` crosses processes;
- `SharedArray` — fixed-capacity vector of records, per-instance stripe: the container a
`zend_array` cannot be (§4);
- `ResultSlotTable` — futures. A slot settles exactly once, carrying either a value record or
a `SharedError` (a persisted three-string object; a `Throwable` can never be shared);
- `ResultSlotTable` — futures. A slot settles exactly once **per generation**, carrying either
a value record or a `SharedError` (a persisted three-string object; a `Throwable` can never be
shared). Slots are **recycled in place** through a free list threaded through the slot records
— nothing is freed, because nothing here ever can be (§6) — and a slot id is a `SlotTicket`,
index and generation packed into the 32 bits a wake event has for it. Every verb checks the
generation, so a handle outliving its release is refused by name instead of being handed the
next task's answer;
- `SharedMutex` / `AtomicInt` / `SharedWaitGroup` — robust locking, an aligned word with
stripe-locked read-modify-write (FFI has no CAS), and a counter with waiters;
- `ClosureProvenance` — the register of closures the family may invoke by address. It stores
Expand Down
107 changes: 98 additions & 9 deletions src/Ipc/IpcException.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,26 +44,115 @@ public static function wakeRegistryNotInherited(): self
);
}

public static function slotTableFull(int $capacity): self
public static function slotTableFull(int $capacity, int $outstanding, int $retired): self
{
return new self(sprintf(
'All %d result slots are used. The slot table is pre-sized in the arena and never grows; ' .
'create it with a larger capacity before the workers fork.',
'All %d result slots are in use (%d outstanding, %d retired). Slots are recycled through ' .
'a free list, so a slot only comes back when its owner calls releaseSlot() - a handle ' .
'that is never awaited never gives its slot back. Either release what is settled, or ' .
'pre-size the table larger before the workers fork; it is allocated in the arena and ' .
'never grows.',
$capacity,
$outstanding,
$retired,
));
}

public static function unknownSlot(int $id, int $capacity): self
public static function unknownSlot(int $index, int $capacity): self
{
return new self(sprintf('Result slot %d does not exist; the table holds slots 0..%d', $id, $capacity - 1));
return new self(sprintf(
'Result slot %d does not exist; the table holds slots 0..%d',
$index,
$capacity - 1,
));
}

/**
* A handle that names a slot the table has already handed to somebody else
*
* This is the whole safety property of recycling: a slot id is only half a claim, and the
* generation is the other half. Answering such a handle with the slot's current contents
* would hand one task's result to another task's waiter, silently and plausibly.
*/
public static function staleSlot(int $index, int $held, int $current): self
{
return new self(sprintf(
'Result slot %d is at generation %d and this handle holds generation %d: the slot was ' .
'released and handed to another task. A recycled slot never answers an older handle - ' .
'read the result before releasing it, and do not keep the id afterwards.',
$index,
$current,
$held,
));
}

/**
* A slot that has been used up: its generation counter reached the end of the ticket layout
*/
public static function slotRetired(int $index): self
{
return new self(sprintf(
'Result slot %d is retired: its generation counter reached the end of the 16 bits a slot ' .
'ticket carries, so the slot was taken out of circulation instead of wrapping round to a ' .
'generation an old handle could match.',
$index,
));
}

public static function slotAlreadyCompleted(int $index, int $generation): self
{
return new self(sprintf(
'Result slot %d is already completed in generation %d. A slot is written exactly once per ' .
'generation - allocate a new one for the next result rather than reusing a settled slot.',
$index,
$generation,
));
}

/**
* A release of a slot whose answer has not been written yet
*
* Recycling a pending slot would hand a live record to the next task while the process that
* owes the answer is still going to write it - the one way this design could return another
* task's result. Refusing is the only correct answer.
*/
public static function slotNotSettled(int $index): self
{
return new self(sprintf(
'Result slot %d is still pending and cannot be released: the process that owes its answer ' .
'may still write it, and recycling the slot now would let that write land on another ' .
'task. Release a slot only once it has settled and its result has been read.',
$index,
));
}

public static function capacityTooLarge(string $structure, int $capacity, int $maximum): self
{
return new self(sprintf(
'%s capacity is %d, above the %d a slot ticket can address: an id carries the slot index ' .
'and its generation in the 32 bits a wake event has for it, and a wider table would ' .
'truncate ids rather than fail',
$structure,
$capacity,
$maximum,
));
}

public static function slotAlreadyCompleted(int $id): self
/**
* A table in the arena whose record shape is not the one this build reads
*
* `ResultSlotTable` is a consumer structure published in the roots directory, so it does not
* ride `Registry::LAYOUT_VERSION`; this word is its own guard, and it exists because reading
* the wrong slot geometry at the right address is silent rather than fatal.
*/
public static function slotTableFormat(int $found, int $expected): self
{
return new self(sprintf(
'Result slot %d is already completed. A slot is written exactly once - allocate a new one ' .
'for the next result rather than reusing a settled slot.',
$id,
'The result slot table in the arena is format %d and this build reads format %d. Slots ' .
'are addressed by offset, so a mismatched shape is read at the right address with the ' .
'wrong meaning - the whole family has to run one build of this package.',
$found,
$expected,
));
}

Expand Down
Loading
Loading