diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..5888703 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,227 @@ +# Working on php-shared-data-extension + +This package gives PHP objects that outlive a request and, in arena mode, a **fork-shared +mutable object arena**: worker processes descended from one parent exchange real PHP values — +scalars, strings, objects, arrays, and closures registered before the fork — by **address**, +coordinated by IPC primitives that are themselves structures in shared memory. It is pure PHP +on top of [z-engine](https://github.com/lisachenko/z-engine) and FFI; there is no C extension +to compile, and every rule below exists because the engine punishes breaking it *silently*. + +Read [`docs/shared-memory-model.md`](docs/shared-memory-model.md) once before changing +anything under `src/Shm/`, `src/Ipc/` or the shared paths of `PersistentStore`. It is the +*why*, with measurements. This file is the *what you must do*, and it does not repeat the +evidence — it cites it. + +--- + +## 1. The Never-Serialize Rule — invariant #1 + +> No value crossing a worker boundary may pass through `serialize()`, igbinary, JSON, +> `var_export`, or any byte-encoding of PHP value graphs. Cross-worker data is exchanged as +> real PHP values: scalars inline, strings as arena-copied `zend_string` addresses, +> arrays/objects as addresses of shared objects living in a fork-shared mmap arena. Sockets +> may carry only wake bytes and fixed-size control records (opcode + tag + address/slot id) — +> signaling, not serialization. + +This is not a performance preference. A serialized graph is a *copy* with its own identity and +its own lifetime, and every guarantee in this package — one object, one address, one +lifecycle, visible mutation — dies with the first copy. If a value has no address-shaped form, +it is **refused** with the remedy named (`NotShareableValueException`), never encoded. + +The rule is tested, not asserted: `tests/Ipc/NotificationPlaneForkTest.php` shadows +`serialize`, `unserialize`, `igbinary_*`, `json_*` and `var_export` in the namespaces the data +path runs through, proves the shadows intercept a real call, and then measures a full +round trip at **zero** calls. Keep that guard passing; if you add a namespace to the data +path, add it to the guard. + +## 2. Sharing is fork-only + +- The arena is `mmap(MAP_SHARED|MAP_ANONYMOUS)`, created **before any fork**. Children inherit + the mapping at the same address; that is what makes eight bytes a portable value. +- **Attach from an unrelated process is permanently out of scope.** Do not add + `shm_open`/file-backed mappings "so it also works across the pool": the class entries, + `std_object_handlers` and the arena base would all differ, and none of that fails loudly. +- **Children never write module globals.** That page is copy-on-write: a child's write becomes + private and desynchronizes the family with no error. Only the creating process, before the + fork, writes `globals[0]`/`globals[1]`. +- **Children never free arena memory.** Every free path is armed to refuse + (`Reclaimer::protect()`), at the last line before the free, with a typed `ArenaException`. +- Classes whose instances travel through the arena must be **loaded before the fork**. + +## 3. Two modes, and they do not mix + +| Mode | Behaviour | +|---|---| +| **frozen** (default) | request-time mutations are rolled back at `detach()` from the persisted snapshot. Unchanged, byte for byte, from the pre-arena package | +| **shared-mutable** (`persist(..., mutable: true)`, arena only) | no rollback; the role is recorded in the **registry**, so every worker that attaches the address applies the same lifecycle | + +Rules for shared-mutable: + +- the **side table is mandatory** — `handle`, `ce` and `properties` are per-process fields + sitting inside a shared struct (model doc §3). Never trust the shared `handle`; identity is + `PersistentStore::sharedIdOf()`, the arena address; +- synchronized writes go through `PersistentStore::mutableHandle()`, which validates and + interns **before** taking the object's stripe lock; +- a direct `$object->prop = ...` remains legal and is **unsynchronized** — the object is + rewired to `std_object_handlers`, so there is no write hook to intercept it. Scalars are + racy-but-visible; a string/array/object written that way is repaired from the persisted + image at detach. Document this every time you touch that path rather than pretending it + cannot happen; +- one object may not belong to a frozen graph and a mutable graph at once — refuse + (`SharedMutationException::modeConflict()`), never resolve. + +## 4. The arData law + +**Never allow the engine to grow a shared `zend_array`.** A resize `perealloc`s the bucket +block into the private heap of whichever worker filled it *and writes that pointer into the +shared struct before it aborts* — siblings then read plausible garbage with no signal. + +- every arena-resident table is **pre-sized** at creation; an insert past capacity is + **refused** with the table named, never attempted; +- growth-capable user collections are **purpose-built containers** of fixed-size records + (`Ipc\SharedArray`), not `zend_array`s. Plain-array properties of shared objects stay sealed; +- **bounds-check on recovery**: re-derive `HT_GET_DATA_ADDR(ht) = arData - HT_HASH_SIZE(mask)` + and check it against the arena. Read `nTableMask` **signed** — the engine declares it + unsigned and uses it signed. + +## 5. Lock discipline + +- `EOWNERDEAD` (130) is handled at **every** lock site, with `pthread_mutex_consistent()` + before unlocking. Skip it once and the mutex is poisoned arena-wide with + `ENOTRECOVERABLE` (131), permanently. Never discard a lock result. +- All arena mutexes are `PTHREAD_PROCESS_SHARED | PTHREAD_MUTEX_ROBUST`. Robust is not + optional: a non-robust mutex whose owner was killed is eternal `EBUSY`. +- A critical section is **memcpys and pointer swaps only**. Inside one: no allocating engine + call, no userland callback, no channel operation, no Fiber suspension, nothing that can + throw. Encode before the lock, materialize after it. +- Atomicity contract: an aligned 8-byte read/write never tears; a 16-byte `zval` is two stores + and **does** tear (~1.3 % of unlocked reads). Take the lock whenever a slot's *type* can + change or more than one slot participates; a single aligned pointer read may skip it. + +## 6. Memory accounting: leak-until-teardown, on purpose + +- The arena is a bump allocator: one cursor, moved under a lock, never moved back. Blocks are + reclaimed when the region dies with the creating process. +- **Nothing unmaps the arena at request shutdown.** This was a real crash: the unmap used to + be armed as a shutdown function, and PHP destroys the symbol table, the object store and + every remaining zval *after* shutdown functions run, so a variable still holding a shared + object was released against unmapped memory — `OK (…)` followed by SIGSEGV, exit 139. No + ordering inside `Arena` can fix it. `destroy()` stays for a caller who owns the moment; a + child calling it is a deliberate no-op. Do not re-arm it. +- Every rewrite of a shared string costs a new arena block (a reader may be following the old + pointer right now). Exhaustion is a typed `ArenaException`, never a crash. +- Gate memory claims with the soaks, and watch the **watermark plateau** rather than the peak: + + ```bash + php -d ffi.enable=1 -d opcache.jit=off tools/soak.php 5000 # flat-memory gate + php -d ffi.enable=1 -d opcache.jit=off tools/soak-drop.php 5000 # reclamation gate + ``` + +## 7. LAYOUT_VERSION discipline + +`Registry::LAYOUT_VERSION` is **5** today. Any change to a record shape, a table's meaning or +what `globals[0]` points at **bumps it**, in the same commit as the change. Readers hard-fail +on a mismatch (`boot()`/`bootShared()` throw and tell the operator to restart the worker) — +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. + +## 8. Frozen-mode invariants that must survive every change + +The arena work must not cost the original package anything. Preserve: + +- **alias-safety ordering** — `drop()`/upsert check for live aliases *before* mutating + anything, and members of the new generation are share-incremented before the old one is + released, so an object in both never transits through a share count of zero; +- **the refcount pin** — `PIN_BASELINE` on every persistent clone, plus + `GC_PERSISTENT|GC_NOT_COLLECTABLE`; the same pin is what keeps a registered shared closure + alive for the whole family; +- **never free persistent strings** — a non-refcounted zval leaves no trace of a request-side + copy, so a freed string is a dangling pointer nobody can detect; +- **untrack before `persistentFree()`** — the tracked-block registry is a per-request PHP + static, and freeing a tracked block without untracking it invites a second free of a + recycled address. + +Frozen semantics are covered by tests that must stay byte-identical in behaviour; if a change +makes one of them "need updating", the change is wrong until proven otherwise. + +## 9. House rules + +- **Style is PER-CS2.0, applied by hand** — no php-cs-fixer is configured in this repository. + Match the surrounding file: aligned `=` in assignment blocks, one blank line between + members, trailing commas in multi-line calls, `declare(strict_types=1)` and the file header + docblock everywhere. +- **Explicit `(int)` casts on FFI field reads.** An `FFI\CData` integer field is not an `int` + until you say so, and comparisons against one silently do the wrong thing. +- **No public method returns `FFI\CData`.** Callers see integers and strings; pointer views are + bound once per process at map time. That is what keeps critical sections to word access. +- **Docblocks cite evidence.** A non-obvious rule names its source: a section of + `docs/shared-memory-model.md`, a numbered correction on + [EPIC #15](https://github.com/lisachenko/php-shared-data-extension/issues/15), or the test + that proves it. Prefer explaining the failure mode over restating the code. +- **The suite is PHPUnit, `.phpt`-free.** Cross-process claims are tested in **real forked + processes** through the harness in `tests/Ipc/IpcTestCase.php` and `tests/Shm/`: children + answer by **exit code**, never by printing; the parent is the only process that asserts; + values that must travel do so as arena words or fixed-size socket records. One arena, one + store and one notification plane per process — the plane must exist before any fork. +- **Both minors, every time.** PHP 8.4 and 8.5 are supported in parallel, each with its own + z-engine line (`8.4.x-dev || 8.5.x-dev`, resolved by Composer against the running PHP). + Run the suite on both before proposing a change: + + ```bash + php8.4 -d ffi.enable=1 -d opcache.jit=off vendor/bin/phpunit # assert exit code 0 + php8.5 -d ffi.enable=1 -d opcache.jit=off vendor/bin/phpunit # assert exit code 0 + ``` + + Check the **exit code**, not the summary line: a teardown segfault prints `OK (…)` and then + dies with 139. Run once under `MALLOC_CHECK_=3 MALLOC_PERTURB_=85` for anything touching + allocation, and `--order-by=random` for anything touching shared state. +- **Spikes are Composer-only.** Everything in `spikes/` bootstraps through + `vendor/autoload.php` and runs from the repository root against this package's own classes — + no external harness, no machine-bound paths. Spikes are not part of the suite; claims the + code depends on get promoted to tests. +- Commits are [Conventional Commits](https://www.conventionalcommits.org/); scopes in use: + `shm`, `store`, `registry`, `ipc`, `tests`, `ci`, `docs`. + +## 10. Closures + +- **Provenance-based acceptance only.** A closure may cross a worker boundary if and only if + it was **registered** with `Ipc\ClosureProvenance::registerSharedClosure()` by the + arena-owning process **before `markForkBarrier()`**. Registration is the entire acceptance + test. +- **Never validate a closure by shape.** Not its class entry, not its handlers, not its + op_array: spike S17 found a stale post-fork address holding a different, perfectly valid + `Closure` that then executed the **wrong function** (8.5) and segfaulted (8.4). Any check on + the object is an integrity check on our own record — say so in the code — and never a reason + to accept one. +- Captures follow the value contract; by-reference captures and declared `static` variables + are refused, because each worker copy-on-writes its own copy of those slots and the + divergence is silent. +- Arena-resident clones of post-fork closures are **Phase B** and not implemented. The + inventory, the two per-request pointers that decide it and the verdict are in + [`docs/closure-cloning.md`](docs/closure-cloning.md). + +--- + +## Repository map + +``` +src/PersistentStore.php boot()/bootShared(), persist/attach/drop/detach, side table, identity +src/Persister.php graph conversion; threads the arena allocator through EVERY mint +src/Registry.php named entries + process-wide object table, LAYOUT_VERSION +src/Reclaimer.php the only place that frees, and the place that refuses to +src/SharedObjectHandle.php the synchronized write path of a shared mutable object +src/SideTable.php the three per-process fields, keyed by arena address +src/Shm/ Arena (mmap + robust mutex bank + roots), allocator, libc, layout +src/Ipc/ value records, channel, shared array, slots, locks, wake plane, + closure provenance +tests/Ipc/, tests/Shm/ forking suites; IpcTestCase is the harness +tools/soak*.php memory gates; tools/request-boundary/ drives real FastCGI requests +spikes/ runnable evidence for the engine claims this package rests on +docs/shared-memory-model.md the model, the measurements and the failure modes +docs/closure-cloning.md Phase A/Phase B of closure exchange, with the Phase B verdict +``` diff --git a/README.md b/README.md index c69c9dc..8e1b28a 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,18 @@ Two features share one persistent module: surviving the request boundary — counters, flags, fixed-size tables. See `demo.php`. +### Feature map + +| What | Where | +|---|---| +| Persistent objects per worker, frozen by default | [How it works](#how-it-works), `PersistentStore::boot()` | +| One `mmap` arena shared by a whole fork tree | [Fork-shared arena mode](#fork-shared-arena-mode-opt-in-experimental), `PersistentStore::bootShared()` | +| Mutation the whole family sees, opt-in per graph | [Shared mutation](#shared-mutation-opt-in-per-graph), `mutableHandle()` | +| Channels, shared arrays, result slots, locks, counters, wait groups | [IPC primitives](#ipc-primitives-in-the-arena-experimental), `Lisachenko\SharedData\Ipc` | +| Closures invoked in several workers (registered before the fork) | [Shared closures](#shared-closures-registered-before-the-fork), `Ipc\ClosureProvenance` | +| Why any of it is shaped this way — the laws, the measurements, the failure modes | [docs/shared-memory-model.md](docs/shared-memory-model.md) | +| The rules a contributor (human or agent) must not break | [AGENTS.md](AGENTS.md) | + ## How it works `persist(ClassName::class, $object)` deep-converts the whole object **graph** @@ -122,7 +134,7 @@ identity or lifetime cannot outlive a request: | Rejected | Why | |---|---| | Resources | tied to request-scoped handles | -| Closures | internal class carrying request-bound scope | +| Closures | internal class carrying request-bound scope — share one with `Ipc\ClosureProvenance` instead of persisting it | | References | not supported yet | | Internal classes (`ArrayObject`, `stdClass`, …) | carry C state the engine frees per request | | Enums | enum case identity is per-request | @@ -332,11 +344,12 @@ $value = $results->await($slot)->value; // read straight out of 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`). A value with no -address-shaped form — a plain array, a resource, a closure, an object this family does not -share — is refused with `NotShareableValueException` naming the remedy. Nothing is ever -encoded: there is no `serialize()`, igbinary or JSON on any data path, and the test suite -proves it by shadowing every encoding function in the package's namespaces. +(an interned `zend_string`, a shared `zend_object`, a `SharedArray`, the record of a shared +closure). A value with no address-shaped form — a plain array, a resource, an object this +family does not share, a closure nobody registered — is refused with +`NotShareableValueException` naming the remedy. Nothing is ever encoded: there is no +`serialize()`, igbinary or JSON on any data path, and the test suite proves it by shadowing +every encoding function in the package's namespaces. The sockets carry **only** fixed 16-byte event records `{opcode, tag, slot/channel id, address}` — signalling, never payload; a scalar's record carries a zero where an address @@ -359,10 +372,54 @@ a package with no scheduler can offer: every primitive also exposes its non-bloc (`trySend()`/`tryRecv()`/`tryLock()`/`readSlot()`) plus `notificationStream()`, so a coroutine runtime can park a Fiber in its own event loop instead. +### Shared closures (registered before the fork) + +A closure compiled **before the fork** is valid in every worker: the family inherited the +memory it lives in, so its address means the same function everywhere. A closure compiled +*after* the fork is the opposite, and it does not fail loudly — a stale address was observed +holding a different, perfectly valid `Closure` that then executed the wrong function. Nothing +about the object tells the two apart, so this package decides on **provenance** and never on +inspection: a closure travels if, and only if, it was registered before the fork barrier. + +```php +use Lisachenko\SharedData\Ipc\ClosureProvenance; + +$closures = ClosureProvenance::create($allocator, $store); // pre-fork, like the arena +$factor = 3; + +$record = $closures->registerSharedClosure('scale', static fn (int $n): int => $n * $factor); +$closures->markForkBarrier(); // registration closes here + +if (pcntl_fork() === 0) { + $scale = $closures->resolve($record); // or ->closure('scale') + exit($scale(14) === 42 ? 0 : 1); // runs in this worker +} +$jobs->send($closures->closure('scale')); // travels as a record address +``` + +The record — closure address, function witness, name, bound `$this` — lives in the arena; the +closure itself is never copied. What is refused, with the reason named: registering after the +barrier or from a worker, a bound `$this` that is not a shared object, a captured plain array +or request object, a capture by reference and a declared `static` variable (each worker would +copy-on-write its own copy of those slots and diverge in silence). Cloning *post-fork* closures +into the arena is a separate problem with its own verdict — +[docs/closure-cloning.md](docs/closure-cloning.md). + ### Deployment model -- **Scope: one worker process.** This is per-process persistent memory, not - cross-process shared memory. Each FPM/RoadRunner worker has its own copy. +- **Scope: a fork tree, not a single process.** The default store is per-worker + persistent memory — each FPM/RoadRunner worker builds its own copy. Arena mode + widens that to **one family of processes descended from one parent**: the + region is mapped before the fork, so every worker sees the same objects at the + same addresses. Attaching from an *unrelated* process is permanently out of + scope — class entries, object handlers and the arena base would all differ, + and none of that fails loudly. +- **Frozen by default, mutable by opt-in.** A persisted graph rolls its + request-time mutations back at shutdown unless you pass `mutable: true`, which + trades the rollback for state the whole family keeps. +- **Signalling is separate from data.** IPC primitives (channels, shared arrays, + result slots, locks, counters, wait groups) live in the arena; sockets carry + fixed 16-byte event records only. - **Blessed setups**: worker loops (RoadRunner, FrankenPHP worker mode, Swoole) or classic FPM with **`opcache.preload`** (stable class entries). Without preload, classes are rebound by name on `attach()` and a property-layout @@ -422,6 +479,13 @@ $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 + +// shared closures (registration is the acceptance test; everything else is refused) +$closures = ClosureProvenance::create($allocator, $store); // pre-fork +$closures->registerSharedClosure($name, $closure): int; // returns the record address +$closures->markForkBarrier(): void; // closes registration for the family +$closures->closure($name): Closure; // resolve($address) by address +$codec = new ValueCodec($allocator, $store, $closures); // lets registered closures travel ``` ## Testing @@ -436,7 +500,9 @@ php -d ffi.enable=1 demos/demo-objects.php php -d ffi.enable=1 demo.php # original shared C data demo ``` -CI runs all of the above on every push and pull request. +CI runs all of the above on every push and pull request, on PHP 8.4 and 8.5. +`spikes/` holds the runnable evidence behind the engine claims this package +rests on; [AGENTS.md](AGENTS.md) states the rules a change has to keep. ## Requirements diff --git a/docs/closure-cloning.md b/docs/closure-cloning.md new file mode 100644 index 0000000..eaf61b9 --- /dev/null +++ b/docs/closure-cloning.md @@ -0,0 +1,135 @@ +# Closures across processes: what Phase A does, and what Phase B would take + +Closure exchange ([#20]) was split in two the moment the spikes came back, and the split is +not about effort — it is about which memory the closure lives in. This document records what +shipped (Phase A), the inventory that decides Phase B, and the verdict on Phase B with the +evidence behind it. + +Measurements below were taken on **PHP 8.4.19** and **8.5.9** (NTS, linux-x64) with +`spikes/s17-prefork-closures.php` and the op-array views z-engine exposes. + +[#20]: https://github.com/lisachenko/php-shared-data-extension/issues/20 + +--- + +## Phase A — pre-fork closures, shared by provenance (shipped) + +A closure compiled **before the fork** needs no cloning at all. The `zend_closure`, the +`zend_function` embedded in it, its opcodes, literals and captured values were all laid out by +the parent, so every child maps them at the same addresses; invoking one in a worker touches +that worker's own copy-on-write pages and nothing else. + +What the arena carries is therefore not the closure but the **record that vouches for it**: + +```text + closure address | zend_function address | name length | bound $this address | name[32] +``` + +`Ipc\ClosureProvenance` writes those records before the fork barrier and refuses to write any +afterwards — and refuses registration from a worker at all. That refusal is the entire safety +argument, because the alternative does not exist: spike S17 held a **post-fork** closure +address in a sibling and found a different, perfectly valid `Closure` there, which then +executed the wrong function (on 8.4 the same experiment segfaulted). No property of the object +distinguishes the two cases, so acceptance is registration and never inspection +([EPIC #15, correction #8][gate]). + +Consequences a caller sees, all of them tested in `tests/Ipc/SharedClosureForkTest.php`: + +| Rule | Why | +|---|---| +| registration happens in the arena-owning process, before `markForkBarrier()` | everything after it is worker-private memory | +| bound `$this` is null or an object of this store | the closure dereferences it in whichever worker invokes it | +| `use`d values follow the ordinary value contract | a capture is a value like any other crossing the boundary | +| by-reference captures and declared `static` variables are refused | both are per-request slots; after the fork each worker writes its own copy and nothing reports the divergence | +| a closure not in the register is refused by `ValueCodec` exactly as before | there is no second acceptance path | + +[gate]: https://github.com/lisachenko/php-shared-data-extension/issues/15#issuecomment-5303807403 + +## Phase B — the inventory + +Phase B is the other half of #20: a closure created **after** the fork, cloned into the arena +so that siblings can run it. The op-array graph it would have to copy is small and entirely +enumerable — this is a `static fn (int $n): int => $n * $factor`, the smallest capturing +closure there is: + +| Piece | 8.4.19 | 8.5.9 | Notes | +|---|---|---|---| +| `zend_closure` (object + embedded function) | 344 B | 344 B | `zend_object` 56 B of it | +| `zend_op_array` struct | 256 B | 256 B | identical between the minors | +| opcodes (`last` × `sizeof(zend_op)`) | 7 × 32 = 224 B | 5 × 32 = 160 B | `zend_op` is 32 B on both | +| literals (`last_literal` × `sizeof(zval)`) | 1 × 16 = 16 B | 0 B | compiler output differs per minor | +| **enumerable total** | **~496 B** | **~416 B** | plus `arg_info`, live ranges, and the `zend_string`s for names | + +z-engine already reads every one of those (`FunctionLikeTrait::getOpCodes()`, `getLiterals()`, +`getArguments()`, `getTryCatchElements()`, `getLiveRanges()`), and `FunctionBodySwap` is prior +art for writing a rebuilt function back into the engine. **Copying ~400–500 bytes into the +arena is not the problem.** + +## Phase B — the actual blocker + +Two fields of the op-array are **per-request slots**, not data: + +```text + run_time_cache__ptr polymorphic-call caches, method/property lookup slots, ... + static_variables_ptr__ptr the LIVE static-variable table of this execution context +``` + +Measured on the same closure, they behave exactly as the design fears: + +- `run_time_cache__ptr` is already non-null when the closure is created (8.5 also reports + `cache_size = 8` where 8.4 reports `0`), and it points into request memory; +- on 8.5, `static_variables_ptr__ptr` (`0x7f3f08734cb0`, request memory) is a **different + table** from `static_variables` (`0x55ac318da280`, the immutable declaration defaults). The + live table is per execution context by construction; the defaults are shared and read-only. + +Move the struct that holds those two pointers into the arena and both slots become **shared +between processes**. That is not a leak or a slowdown, it is a correctness failure of the +worst kind available here: two workers would write each other's cache slots and each other's +static variables with no lock, no signal and no way to notice — the same class of silent +corruption as an engine-grown `arData` (§4 of [the shared-memory model](shared-memory-model.md)). + +So Phase B is not "clone the op_array". Phase B is **clone the op_array and re-mint the two +per-process slots in every process that attaches it**, which is precisely the mechanism E2 +already built for objects: a side table keyed by arena address, holding the fields that +describe the reader rather than the thing being read +([`SideTable`](../src/SideTable.php), §3 of the model document). A cloned closure would carry: + +- an arena-resident, immutable half — struct bytes, opcodes, literals, arg_info, interned + strings — written once and never mutated; +- a per-process half — run-time cache block, live static-variable table — allocated by each + attaching process out of **its own** memory and bound before the first call, dropped at + detach with everything else per-process. + +## Verdict + +**Achievable, and scoped as a follow-up.** Nothing in the engine layout forbids it: the +graph is enumerable, its size is trivial, z-engine already reads and writes every piece, and +the per-process problem it raises has a solved precedent in this repository. What it needs is +a mechanism of its own — cloning, re-minting, an attach/detach path for closures, plus the +conservative rejection matrix #20 sketches (no first-class-callable of a non-shared instance +method, no references in statics) — and that is a body of work with its own failure modes, +not a variation on Phase A. + +**#20 therefore stays open for Phase B.** Phase A is complete and in use; this section is the +documented verdict its acceptance criteria call for, and the starting point for whoever picks +Phase B up. + +### If you are picking it up + +1. Start from `ZEngine\Type\ClosureEntry` and `ZEngine\Reflection\FunctionLikeTrait` — every + read you need already exists; `FunctionBodySwap` shows how a rebuilt function is installed. +2. Decide the per-process binding first, not the copy: without a story for + `run_time_cache__ptr` and `static_variables_ptr__ptr`, a correct copy is still unusable. + `ZEND_MAP_PTR` indirection (the slot may be a real pointer or a map-ptr offset with the low + bit set — see `getStaticVariables()`) is part of that story and differs per minor. +3. Keep the acceptance rule of Phase A: a cloned closure is legal because the *cloning + mechanism* vouches for it, never because it passed an inspection. +4. Bump `Registry::LAYOUT_VERSION` if a cloned closure gains a persisted record — Phase A did + not, because its table is a consumer structure in the arena payload and adds no field to + any registry record. + +--- + +*Evidence: `spikes/s17-prefork-closures.php` (13 checks, GREEN on 8.4.19 and 8.5.9), +`tests/Ipc/SharedClosureForkTest.php`, and the [spike-gate record on #15][gate] +(corrections #8 and #9).* diff --git a/docs/shared-memory-model.md b/docs/shared-memory-model.md index 89ced82..d4173b7 100644 --- a/docs/shared-memory-model.md +++ b/docs/shared-memory-model.md @@ -178,8 +178,19 @@ What that costs, concretely: processes; they must be re-minted per process, by the same side-table mechanism §3 describes for objects. -Tracked as closure exchange in [#20]. Until then, cross-process work is passed as Task -objects (data), not as callables. +That is why provenance is **recorded rather than inferred**: `Ipc\ClosureProvenance` is a +pre-sized table in the arena where the arena-owning process registers closures by name before +it calls `markForkBarrier()`, and every registration after that moment — or from a worker — is +refused. A registered closure travels as the address of its **record**; the closure object +itself is never copied, because a pre-fork one needs no copy. Captures are held to the value +contract at registration, and by-reference captures and declared statics are refused outright: +after the fork each worker writes its own copy-on-write copy of such a slot, so the divergence +would be silent. + +Arena-resident clones of **post-fork** closures remain out of scope; the inventory, the +per-process slots that decide it and the verdict are in +[closure-cloning.md](closure-cloning.md), tracked as Phase B of [#20]. Work created after the +fork still travels as Task objects (data), not as callables. [#20]: https://github.com/lisachenko/php-shared-data-extension/issues/20 @@ -243,9 +254,10 @@ request end is repaired from the frozen image rather than left for a sibling to Everything crossing a worker boundary is a **16-byte tagged record** — `uint8 tag | 7 pad | uint64 payload` — where the payload is the value itself for scalars and an *address* for -strings, objects and shared arrays. A value with no address-shaped form (plain array, -resource, non-shared object, closure) is refused with the remedy named, never encoded: that -is the Never-Serialize Rule in one sentence. +strings, objects, shared arrays and the records of registered closures. A value with no +address-shaped form (plain array, resource, non-shared object, unregistered closure) is +refused with the remedy named, never encoded: that is the Never-Serialize Rule in one +sentence. - `SharedChannel` — a ring of records plus sender/receiver waiter tables under its **own** dedicated mutex (a structure locked on every operation does not belong on a shared stripe). @@ -257,6 +269,8 @@ is the Never-Serialize Rule in one sentence. a `SharedError` (a persisted three-string object; a `Throwable` can never be shared); - `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 + provenance, not code: records in the arena, closures wherever they were compiled (§7); - `WakeRegistry` — one inherited socket pair per process. Sockets carry a fixed 16-byte event record (`opcode | tag | id | address`) and never a payload: **signalling, not serialization**. Waking is level-triggered and re-checked inside the critical section, so a @@ -286,7 +300,7 @@ is the Never-Serialize Rule in one sentence. | String rewrites leak the previous bytes | consequence of §6; a content-keyed persistent intern table is the next iteration | | Direct `$obj->prop = ...` writes are unsynchronized | by design: the extension rewires shared objects to `std_object_handlers`, so there is no write hook. Scalar writes are visible but racy; a string/array/object written that way stores a request-heap pointer and is restored from the persisted image at detach. The synchronized path is `PersistentStore::mutableHandle()` | | The shared `handle` field is not the sentinel for a few instructions while a process detaches | inherent: recycling an object-store slot is an engine call and engine calls cannot run under an arena mutex. Nothing in the package reads that field — identity is `sharedIdOf()` (§3) | -| Post-fork closures cannot be shared | [#20] (§7) | +| Only closures registered before the fork barrier can be shared | by design (§7); post-fork closures need arena cloning — verdict and inventory in [closure-cloning.md](closure-cloning.md), Phase B of [#20] | | A borrowed `PersistentHashTable` view cannot re-adopt the external storage block it sits on, so the growth guard is re-derived in this package | z-engine seam follow-up; see the `TODO` in `Registry::assertRegistryRoom()` and [z-engine#223](https://github.com/lisachenko/z-engine/pull/223) | --- diff --git a/spikes/README.md b/spikes/README.md index e4b7021..1474deb 100644 --- a/spikes/README.md +++ b/spikes/README.md @@ -13,6 +13,7 @@ through Composer's autoloader and nothing else. ```bash php8.4 -d ffi.enable=1 -d opcache.jit=off spikes/s8-robust-pshared-mutex.php php8.4 -d ffi.enable=1 -d opcache.jit=off spikes/s15-concurrent-bump-allocation.php +php8.4 -d ffi.enable=1 -d opcache.jit=off spikes/s17-prefork-closures.php ``` ## Arena spikes (E1) @@ -22,8 +23,18 @@ php8.4 -d ffi.enable=1 -d opcache.jit=off spikes/s15-concurrent-bump-allocation. | `s8-robust-pshared-mutex.php` | Do the arena's `PTHREAD_PROCESS_SHARED` + `PTHREAD_MUTEX_ROBUST` mutexes exclude another process, survive a SIGKILLed owner (`EOWNERDEAD` → `pthread_mutex_consistent`) and stay usable afterwards? | GREEN — all three | | `s15-concurrent-bump-allocation.php` | Four children, 8000 blocks through one shared bump cursor: any overlap, any block written through by a foreign process? | GREEN — zero overlaps, zero foreign markers | -Both run against this package's own `Arena`, so they double as end-to-end checks of the -class the rest of the epic builds on. +## Closure spikes (E5) + +| File | Question | Verdict | +|---|---|---| +| `s17-prefork-closures.php` | Can four children invoke closures registered before the fork barrier, by address, with correct results — and are the two ways of getting it wrong (registering after the barrier, registering from a worker) refused rather than resolved? | GREEN — 13 checks, both minors | + +All three run against this package's own `Arena`, so they double as end-to-end checks of the +classes the rest of the epic builds on. `s17` is the mechanism that came out of the original +S17 experiment rather than the experiment itself: the sweep held **post-fork** addresses on +purpose and found a valid `Closure` of a different function behind one, which is why nothing +here validates a closure by inspecting it. The Phase B verdict that experiment leads to is +written up in [docs/closure-cloning.md](../docs/closure-cloning.md). ## The wider validation sweep (not in this repository) @@ -52,7 +63,7 @@ The findings that bind the implementation, restated here so the code has somethi never by handle. Moving those fields into a per-process side table is E2's job (#17); until then arena mode carries the limitations listed in `PersistentStore::bootShared()`. - **S16/S17** — arena-interned strings swap safely under a pointer store; closures are only - fork-safe when they existed before the fork (E5). + fork-safe when they existed before the fork (E5, shipped as `Ipc\ClosureProvenance`). The claims that this package depends on are not left resting on that sweep: S12/S14/S16 are promoted to real tests in `tests/Shm/` (mutation visibility, per-process side table, unlocked diff --git a/spikes/s17-prefork-closures.php b/spikes/s17-prefork-closures.php new file mode 100644 index 0000000..ce4e285 --- /dev/null +++ b/spikes/s17-prefork-closures.php @@ -0,0 +1,229 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +/** + * S17 - can a closure compiled before the fork be invoked by address in several workers? + * + * The question behind Phase A of closure exchange (#20). A `zend_closure` is an object with a + * `zend_function` embedded in it, pointing at opcodes, literals, a run-time cache and a table + * of static variables. None of that is in the arena and none of it can be: what makes it work + * is the fork itself - every child inherits the parent's address space, so a closure that + * already existed maps at the same address, with the same op_array behind it, in every worker. + * + * The spike therefore checks the property that this package builds on, and the boundary that + * it refuses to cross: + * + * - three closures registered before the fork (pure, capturing a scalar, capturing a shared + * object) are invoked ROUNDS times in each of CHILDREN workers, and every result is + * verified against the value the parent computed for itself; + * - the closures' addresses are outside the arena, and the RECORDS naming them are inside it: + * nothing was copied, the arena carries the provenance and not the code; + * - the two ways of getting it wrong are refused rather than resolved: registering after the + * fork barrier, and registering from a worker (the case that produced the wrong-function + * execution S17 originally found). + * + * Nothing here is expected to crash - unlike the sweep this spike is named after, which held + * post-fork addresses on purpose. That experiment is recorded on the gate for #15; this file + * is the mechanism that came out of it, runnable from a checkout. + * + * Run: php -d ffi.enable=1 -d opcache.jit=off spikes/s17-prefork-closures.php + */ + +use Lisachenko\SharedData\Ipc\ClosureProvenance; +use Lisachenko\SharedData\Ipc\ClosureProvenanceException; +use Lisachenko\SharedData\Ipc\NotShareableValueException; +use Lisachenko\SharedData\Ipc\ValueCodec; +use Lisachenko\SharedData\Ipc\ValueTag; +use Lisachenko\SharedData\PersistentStore; +use Lisachenko\SharedData\Shm\Arena; +use Lisachenko\SharedData\Shm\ArenaAllocator; +use ZEngine\Core; + +require __DIR__ . '/../vendor/autoload.php'; + +const CHILDREN = 4; +const ROUNDS = 50_000; +const FACTOR = 7; + +/** + * A class whose instances travel through the arena must exist before the fork, like any other + */ +final class SpikeConfig +{ + public string $release = 'unset'; + + public int $workers = 0; +} + +$failures = 0; +$checks = 0; + +function check(string $claim, bool $holds): void +{ + global $failures, $checks; + + $checks++; + if (!$holds) { + $failures++; + } + printf("[%s] %s\n", $holds ? ' OK ' : 'FAIL', $claim); +} + +Core::init(); + +$arena = Arena::create(32 << 20); +$store = PersistentStore::bootShared($arena, null, 's17_closures'); +$allocator = new ArenaAllocator($arena); +$register = ClosureProvenance::create($allocator, $store, 8); +$codec = new ValueCodec($allocator, $store, $register); + +$config = new SpikeConfig(); +$config->release = '2026.8'; +$config->workers = CHILDREN; +$shared = $store->persist(SpikeConfig::class, $config); + +// --------------------------------------------------------------------------------------- +// Registration: the whole of Phase A's acceptance test, and it happens before the fork +// --------------------------------------------------------------------------------------- + +$factor = FACTOR; + +$pure = $register->registerSharedClosure('pure', static fn (int $value): int => $value * $value); +$captures = $register->registerSharedClosure('captures', static fn (int $value): int => $value * $factor); +$reads = $register->registerSharedClosure('reads', static fn (): string => $shared->release); + +check('three pre-fork closures were registered', $register->count() === 3); +check( + 'the records live in the arena', + $arena->contains($pure, 8) && $arena->contains($captures, 8) && $arena->contains($reads, 8), +); +check( + 'the closures themselves were NOT copied into the arena', + !$arena->contains($register->closureAddressOf('pure'), 8) + && !$arena->contains($register->closureAddressOf('captures'), 8), +); +check( + 'a closure that CAPTURES a shared object stays unbound, so its record carries no $this', + $register->boundThisAddressOf('reads') === 0, +); + +[$tag, $payload] = $codec->encode($register->closure('pure')); +check('a registered closure encodes as an address-shaped record', $tag === ValueTag::Closure && $tag->isAddress()); +check('the payload is the record address, not the closure address', $payload === $pure); + +$unregistered = static fn (): int => 1; +try { + $codec->encode($unregistered); + check('an unregistered closure is refused by the codec', false); +} catch (NotShareableValueException $exception) { + check( + 'an unregistered closure is refused by the codec, naming registerSharedClosure()', + str_contains($exception->getMessage(), 'registerSharedClosure'), + ); +} + +$register->markForkBarrier(); + +try { + $register->registerSharedClosure('too-late', static fn (): int => 2); + check('registering after the fork barrier is refused', false); +} catch (ClosureProvenanceException) { + check('registering after the fork barrier is refused', true); +} + +// --------------------------------------------------------------------------------------- +// Invocation: every worker runs the same code, against its own copy-on-write engine state +// --------------------------------------------------------------------------------------- + +$expectedSquares = 0; +$expectedScaled = 0; +for ($round = 0; $round < ROUNDS; $round++) { + $expectedSquares += $round * $round; + $expectedScaled += $round * FACTOR; +} + +$results = $arena->allocate(CHILDREN * 16); +$children = []; + +for ($worker = 0; $worker < CHILDREN; $worker++) { + $pid = pcntl_fork(); + if ($pid === -1) { + fwrite(STDERR, "cannot fork\n"); + + exit(1); + } + if ($pid === 0) { + $squares = $register->resolve($pure); + $scaled = $register->closure('captures'); + $reader = $register->closure('reads'); + + $sumSquares = 0; + $sumScaled = 0; + for ($round = 0; $round < ROUNDS; $round++) { + $sumSquares += $squares($round); + $sumScaled += $scaled($round); + } + + $arena->writeWord($results + $worker * 16, $sumSquares); + $arena->writeWord($results + $worker * 16 + 8, $sumScaled); + + // A worker may never register: its own closures are private to it, whatever it calls them + $ownVerdict = 0; + try { + $register->registerSharedClosure('from-worker', static fn (): int => 3); + } catch (ClosureProvenanceException) { + $ownVerdict = 1; + } + + exit($reader() === '2026.8' && $ownVerdict === 1 ? 0 : 9); + } + $children[] = $pid; +} + +$exited = 0; +foreach ($children as $pid) { + $status = 0; + pcntl_waitpid($pid, $status); + $exited += pcntl_wifexited($status) && pcntl_wexitstatus($status) === 0 ? 1 : 0; + if (pcntl_wifsignaled($status)) { + printf("[FAIL] worker %d died from signal %d\n", $pid, pcntl_wtermsig($status)); + $failures++; + } +} + +check( + sprintf('%d workers read the captured shared object and were refused registration', CHILDREN), + $exited === CHILDREN, +); + +$allSquares = true; +$allScaled = true; +for ($worker = 0; $worker < CHILDREN; $worker++) { + $allSquares = $allSquares && $arena->readWord($results + $worker * 16) === $expectedSquares; + $allScaled = $allScaled && $arena->readWord($results + $worker * 16 + 8) === $expectedScaled; +} + +check(sprintf('every worker computed the same %d squares', ROUNDS), $allSquares); +check(sprintf('every worker computed the same %d captured-scalar products', ROUNDS), $allScaled); +check('no worker left a record behind', $register->count() === 3); +check('no stripe lock had to be recovered', !$register->wasLockRecovered()); + +printf( + "\n%s - %d checks, %d failures (arena watermark %d bytes)\n", + $failures === 0 ? 'S17 GREEN' : 'S17 RED', + $checks, + $failures, + $arena->watermark(), +); + +exit($failures === 0 ? 0 : 1); diff --git a/src/Ipc/ClosureProvenance.php b/src/Ipc/ClosureProvenance.php new file mode 100644 index 0000000..feb5291 --- /dev/null +++ b/src/Ipc/ClosureProvenance.php @@ -0,0 +1,745 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Lisachenko\SharedData\Ipc; + +use Lisachenko\SharedData\PersistentStore; +use Lisachenko\SharedData\Shm\Arena; +use Lisachenko\SharedData\Shm\ArenaAllocator; +use ZEngine\Core; +use ZEngine\Generated\zend_closure; +use ZEngine\Generated\zend_object; +use ZEngine\Reflection\ReflectionFunction; +use ZEngine\Reflection\ReflectionValue; +use ZEngine\Type\ClosureEntry; +use ZEngine\Type\PersistentObjectFactory; + +/** + * The register of closures a worker family may invoke by address - Phase A of closure exchange + * + * ## Why registration, and nothing but registration, is the acceptance test + * + * A closure compiled BEFORE the fork is safe in every worker: the `zend_closure`, its embedded + * `zend_function` and every pointer inside them were laid out by the parent, so the whole + * family maps them at the same addresses, copy-on-write. A closure compiled AFTER the fork is + * the opposite, and it does not fail loudly: spike S17 held a stale address in a sibling and + * found a different, perfectly valid `Closure` there, which then executed the WRONG FUNCTION + * (EPIC #15, correction #8; docs/shared-memory-model.md, §7). On 8.4 the same experiment + * segfaulted. Nothing about the object distinguishes the two cases - not its class entry, not + * its handlers, not its op_array - so this class never looks at one to decide. + * + * What it does instead is trivially sound: the process that owns the arena registers closures + * by name BEFORE it forks, each registration writing a record into the arena; the fork barrier + * is then marked, and every later registration is refused. A record therefore exists only for + * a closure that was already compiled when the family was created, which is precisely the + * property that makes the address portable. Everything else stays refused by ValueCodec. + * + * ```text + * header (8 words, 64 bytes) magic | capacity | count | creator pid | barrier pid + * records (64 bytes each) closure address | zend_function address | name length | + * bound $this address | name[32] + * ``` + * + * The records live in the arena; the closures themselves do NOT. There is no copy: a shared + * closure is the parent's own object, inherited by every child at the same address, and the + * record is the arena-resident proof that it was there before the fork. That is also why the + * table is a consumer structure with its own roots-directory name rather than part of the + * registry layout - it adds no field to any persisted record, so `Registry::LAYOUT_VERSION` + * is unchanged by it. + * + * ## What a shared closure may capture + * + * A worker invokes the closure against ITS OWN copy-on-write copy of everything the closure + * points at, so anything mutable that is not in the arena diverges per process, silently: + * + * - **bound `$this`** must be null or an object of this store (an arena address every worker + * resolves to the same object); + * - **`use`d values** follow the ordinary value contract - null, bool, int, float, string, + * a shared object or a SharedArray. A plain array or a request object is refused with the + * remedy named, exactly as it would be on a channel; + * - **by-reference captures** (`use (&$x)`) and **declared statics** (`static $n = 0`) are + * refused outright: both are per-request slots, and a write to one after the fork is + * invisible to every other process with nothing to report the divergence. + * + * Static variables are read through the engine (z-engine's op-array view) rather than guessed + * from the source: the table is where `use` values, by-reference captures and declared statics + * all live, and the reference flag on a slot is what tells them apart. + * + * ## Invocation + * + * A receiver resolves a record - by name, or by an address that arrived in a value record - + * and gets a `Closure` bound to the inherited object. Calls run entirely inside the calling + * process: the run-time cache and the static-variable table the engine touches are per-process + * copies from the moment anything writes them, which is what makes concurrent invocation in + * several workers safe and what keeps Phase B (arena-resident closures) a separate problem - + * see docs/closure-cloning.md. + */ +final class ClosureProvenance +{ + /** + * 'SHMCLOSR' - the first word of the table, so a wrong address is refused, not read + */ + public const int MAGIC = 0x53484D434C4F5352; + + public const int DEFAULT_CAPACITY = 64; + + /** + * Longest closure name that fits inline in a record (bytes) + */ + public const int MAX_NAME = 32; + + public const int HEADER_SIZE = 64; + + public const int RECORD_SIZE = 64; + + /** + * Roots-directory name the table publishes itself under by default + */ + public const string DEFAULT_ROOT = 'closures'; + + private const int WORD_MAGIC = 0; + private const int WORD_CAPACITY = 1; + private const int WORD_COUNT = 2; + private const int WORD_CREATOR_PID = 3; + private const int WORD_BARRIER_PID = 4; + + private const int RECORD_WORD_CLOSURE = 0; + private const int RECORD_WORD_FUNCTION = 1; + private const int RECORD_WORD_NAME_LENGTH = 2; + private const int RECORD_WORD_BOUND_THIS = 3; + private const int RECORD_NAME_OFFSET = 32; + + private readonly Arena $arena; + + private readonly int $capacity; + + private readonly int $stripe; + + /** + * Closures this process registered, kept alive for the lifetime of the process + * + * The refcount pin below is what guarantees the object survives; this array is what + * guarantees nothing ever wants to reclaim it in the first place. + * + * @var array + */ + private array $registered = []; + + /** + * Closures materialized in THIS process, keyed by record address + * + * @var array + */ + private array $resolved = []; + + /** + * Reverse index for the encode path: closure object address => record address + * + * @var array + */ + private array $byObject = []; + + private int $indexedRecords = 0; + + private bool $recoveredLock = false; + + private function __construct( + private readonly ArenaAllocator $allocator, + private readonly ?PersistentStore $store, + private readonly int $address, + ) { + $this->arena = $allocator->arena(); + if (!$this->arena->contains($address, self::HEADER_SIZE)) { + throw IpcException::notShared('closure table', $address); + } + if ($this->arena->readWord($address + self::WORD_MAGIC * 8) !== self::MAGIC) { + throw ClosureProvenanceException::notARecord($address); + } + $this->capacity = $this->arena->readWord($address + self::WORD_CAPACITY * 8); + $this->stripe = $this->arena->stripeFor($address); + } + + /** + * Creates the closure table of a worker family - in the parent, before any fork + * + * @param int $capacity Records reserved for the lifetime of the arena + * @param string|null $name Roots-directory name a child can find the table by + */ + public static function create( + ArenaAllocator $allocator, + ?PersistentStore $store = null, + int $capacity = self::DEFAULT_CAPACITY, + ?string $name = self::DEFAULT_ROOT, + ): self { + if ($capacity <= 0) { + throw IpcException::invalidCapacity('Closure table', $capacity); + } + $arena = $allocator->arena(); + $address = $arena->allocate(self::HEADER_SIZE + $capacity * self::RECORD_SIZE, 64); + + // Kernel-zeroed memory already reads as an empty table; the magic is written last, + // so a reader that finds it finds a complete header behind it + $arena->writeWord($address + self::WORD_CAPACITY * 8, $capacity); + $arena->writeWord($address + self::WORD_CREATOR_PID * 8, (int) getmypid()); + $arena->writeWord($address + self::WORD_MAGIC * 8, self::MAGIC); + + if ($name !== null) { + $arena->putRoot($name, $address); + } + + return new self($allocator, $store, $address); + } + + /** + * Binds the table another process created, by address + */ + public static function attach(ArenaAllocator $allocator, ?PersistentStore $store, int $address): self + { + return new self($allocator, $store, $address); + } + + /** + * Binds the table published in the arena roots directory + */ + public static function open( + ArenaAllocator $allocator, + ?PersistentStore $store = null, + string $name = self::DEFAULT_ROOT, + ): self { + return new self($allocator, $store, $allocator->arena()->requireRoot($name)); + } + + /** + * Address of the table header - what a child needs to attach() + */ + public function address(): int + { + return $this->address; + } + + public function capacity(): int + { + return $this->capacity; + } + + /** + * Registered closures so far (a single aligned word: no lock, correction #2) + */ + public function count(): int + { + return $this->arena->readWord($this->address + self::WORD_COUNT * 8); + } + + /** + * The process that mapped the arena and owns registration + */ + public function creatorPid(): int + { + return $this->arena->readWord($this->address + self::WORD_CREATOR_PID * 8); + } + + /** + * Whether a stripe lock of this table was ever recovered from a worker that died holding it + */ + public function wasLockRecovered(): bool + { + return $this->recoveredLock; + } + + /** + * Closes registration: from here on, code is fork material and nothing else + * + * The runtime calls this once, immediately before it forks its workers. The moment is + * recorded in the ARENA rather than in this process, so a worker that boots its own view + * of the table still sees a closed register and cannot talk itself into registering the + * closures it compiled after the fork - which are exactly the unsafe ones. + * + * Idempotent: marking an already-marked barrier keeps the first process's mark. + */ + public function markForkBarrier(): void + { + if ($this->barrierPid() !== 0) { + return; + } + $this->arena->writeWord($this->address + self::WORD_BARRIER_PID * 8, (int) getmypid()); + } + + public function isForkBarrierPassed(): bool + { + return $this->barrierPid() !== 0; + } + + /** + * Pid of the process that marked the fork barrier, or 0 while registration is open + */ + public function barrierPid(): int + { + return $this->arena->readWord($this->address + self::WORD_BARRIER_PID * 8); + } + + /** + * Makes one pre-fork closure shareable, under a name, and returns its record address + * + * The only way a closure ever becomes a legal cross-worker value. Call it from the process + * that created the arena, before markForkBarrier() - both are enforced, and both refusals + * are the mechanism working rather than a limitation to route around. + * + * @param string $name Up to MAX_NAME bytes; unique for the life of the arena + * + * @return int Address of the arena record - the eight bytes that travel to a worker + */ + public function registerSharedClosure(string $name, \Closure $closure): int + { + $length = \strlen($name); + if ($length === 0 || $length > self::MAX_NAME) { + throw ClosureProvenanceException::invalidName($name, self::MAX_NAME); + } + if ($this->isForkBarrierPassed()) { + throw ClosureProvenanceException::afterBarrier($name, $this->barrierPid()); + } + $currentPid = (int) getmypid(); + if ($currentPid !== $this->creatorPid()) { + throw ClosureProvenanceException::notCreator($name, $this->creatorPid(), $currentPid); + } + if ($this->addressOfName($name) !== null) { + throw ClosureProvenanceException::duplicateName($name); + } + + $boundThis = $this->assertShareableBinding($name, $closure); + $this->assertShareableCaptures($name, $closure); + + $closureAddress = $this->pinClosure($closure); + $functionAddress = self::functionAddressOf($closureAddress); + + $slot = $this->claimSlot(); + $this->writeRecord($slot, $name, $closureAddress, $functionAddress, $boundThis); + + // Held for the lifetime of this process, so nothing ever asks to reclaim the object + // whose address the whole family is about to inherit + $this->registered[$name] = $closure; + + return $this->recordAddress($slot); + } + + /** + * Record address of a registered name, or null when nothing was registered under it + */ + public function addressOfName(string $name): ?int + { + foreach ($this->records() as $slot => $record) { + if ($record['name'] === $name) { + return $this->recordAddress($slot); + } + } + + return null; + } + + /** + * Record address of a closure this family shares, or null when it is not registered + * + * The predicate the value codec asks before a closure may travel: a null answer means the + * closure has no provenance here, and no amount of inspecting it can produce one. + */ + public function addressOfClosure(\Closure $closure): ?int + { + $objectAddress = self::objectAddressOf($closure); + $this->refreshIndex(); + + return $this->byObject[$objectAddress] ?? null; + } + + public function isShared(\Closure $closure): bool + { + return $this->addressOfClosure($closure) !== null; + } + + /** + * The closure registered under $name, ready to invoke in THIS process + */ + public function closure(string $name): \Closure + { + $address = $this->addressOfName($name) ?? throw ClosureProvenanceException::unknownName($name); + + return $this->resolve($address); + } + + /** + * Materializes the closure a record describes - the receiving half of the exchange + * + * Everything that can refuse does so before the object is touched: the address must be a + * record slot of this table, the record must carry a closure address, and the object there + * must still be a `Closure` carrying the very `zend_function` the record witnessed. None of + * that is the acceptance test (registration is), it is a bounds-and-integrity check on our + * own bookkeeping - which is why a failure throws instead of invoking something plausible. + * + * @param int $address Record address from registerSharedClosure(), a value record or a + * roots lookup - the same eight bytes in every process of the family + */ + public function resolve(int $address): \Closure + { + if (isset($this->resolved[$address])) { + return $this->resolved[$address]; + } + $slot = $this->slotAt($address); + if ($slot === null) { + throw ClosureProvenanceException::notARecord($address); + } + $record = $this->readRecord($slot); + if ($record['closure'] === 0) { + throw ClosureProvenanceException::notARecord($address); + } + // Class entry first, zend_function second: the second reads THROUGH the object as a + // zend_closure, which is only meaningful once the first has said that it is one + $isIntact = self::isClosureObject($record['closure']) + && self::functionAddressOf($record['closure']) === $record['function']; + if (!$isIntact) { + throw ClosureProvenanceException::recordDrifted($address); + } + + return $this->resolved[$address] = self::closureAt($record['closure']); + } + + /** + * Every registered name, in registration order + * + * @return list + */ + public function names(): array + { + $names = []; + foreach ($this->records() as $record) { + $names[] = $record['name']; + } + + return $names; + } + + /** + * Bound $this of a registered closure as an arena address, 0 for an unbound one + */ + public function boundThisAddressOf(string $name): int + { + return $this->recordNamed($name)['boundThis']; + } + + /** + * Where the closure object itself lives - deliberately NOT in the arena + * + * Phase A shares no closure memory at all: the object stays in the pages the family + * inherited from the process that compiled it, and only the record vouching for it is + * arena-resident. Exposed because that distinction is the whole design and is worth being + * able to observe (see docs/closure-cloning.md for what moving it would take). + */ + public function closureAddressOf(string $name): int + { + return $this->recordNamed($name)['closure']; + } + + /** + * @return array{name: string, closure: int, function: int, boundThis: int} + */ + private function recordNamed(string $name): array + { + foreach ($this->records() as $record) { + if ($record['name'] === $name) { + return $record; + } + } + + throw ClosureProvenanceException::unknownName($name); + } + + /** + * @return int Arena address of a bound $this, or 0 when the closure is unbound + */ + private function assertShareableBinding(string $name, \Closure $closure): int + { + $boundThis = (new \ReflectionFunction($closure))->getClosureThis(); + if ($boundThis === null) { + return 0; + } + $address = $this->store?->addressOfInstance($boundThis); + if ($address === null) { + throw ClosureProvenanceException::boundThisNotShared($name, $boundThis::class); + } + + return $address; + } + + /** + * Refuses every capture that would mean something different in the receiving worker + * + * Two passes, because they answer two different questions. The engine's static-variable + * table says HOW a name is captured - a slot holding a reference is either `use (&$x)` or a + * bound `static $n`, both per-request state - while native reflection says WHAT the + * by-value captures are, which is the ordinary value contract every record on a channel + * has to satisfy. + */ + private function assertShareableCaptures(string $name, \Closure $closure): void + { + $used = (new \ReflectionFunction($closure))->getClosureUsedVariables(); + + $closureEntry = new ClosureEntry($closure); + $statics = ReflectionFunction::fromCData($closureEntry->getRawFunction())->getStaticVariables(); + if ($statics !== null) { + foreach ($statics as $variable => $value) { + $variable = (string) $variable; + if (!\array_key_exists($variable, $used)) { + throw ClosureProvenanceException::carriesStaticState($name, $variable); + } + if (($value->getType() & 0xFF) === ReflectionValue::IS_REFERENCE) { + throw ClosureProvenanceException::capturedByReference($name, $variable); + } + } + } + + foreach ($used as $variable => $value) { + $this->assertShareableCapture($value); + } + } + + /** + * The value contract, applied to one captured value without allocating anything + * + * Deliberately NOT ValueCodec::encode(): encoding a string interns it into the arena, and a + * capture is not a value being sent - it is a value being vouched for. The answers are the + * same, and so are the exceptions, so a rejected capture reads exactly like a rejected send. + */ + private function assertShareableCapture(mixed $value): void + { + match (true) { + $value === null, + \is_bool($value), + \is_int($value), + \is_float($value), + \is_string($value) => null, + $value instanceof SharedArray => null, + $value instanceof \Closure => throw NotShareableValueException::closure(), + \is_array($value) => throw NotShareableValueException::plainArray(), + \is_resource($value) => throw NotShareableValueException::resource(), + \is_object($value) => $this->store?->addressOfInstance($value) !== null + ? null + : throw NotShareableValueException::foreignObject($value::class), + default => throw NotShareableValueException::unsupportedType(\gettype($value)), + }; + } + + /** + * Pins the closure object so no process of the family can ever reclaim it + * + * The same pin every persistent clone carries (`PIN_BASELINE`), for the same reason: the + * address is about to be inherited by processes this one knows nothing about, and a + * refcount that reaches zero in any of them would free memory the rest are still reading. + * The pin is written BEFORE the fork, so every worker inherits an object that cannot be + * released; request shutdown of the creating process still tears it down with everything + * else, which is exactly when the family is gone anyway. + * + * @return int Address of the closure's zend_object + */ + private function pinClosure(\Closure $closure): int + { + $value = new ReflectionValue($closure); + + try { + $rawObject = $value->getRawObject(); + $rawObject->gc->refcount = PersistentObjectFactory::PIN_BASELINE; + + return Core::addressOf($rawObject); + } finally { + $value->release(); + } + } + + /** + * Reserves the next record slot under the table's stripe lock + */ + private function claimSlot(): int + { + $countAddress = $this->address + self::WORD_COUNT * 8; + + $recovered = $this->arena->lockStripe($this->stripe); + + $slot = $this->arena->readWord($countAddress); + $fits = $slot < $this->capacity; + if ($fits) { + $this->arena->writeWord($countAddress, $slot + 1); + } + + $this->arena->unlockStripe($this->stripe); + + $this->recoveredLock = $this->recoveredLock || $recovered; + + if (!$fits) { + throw ClosureProvenanceException::tableFull($this->capacity); + } + + return $slot; + } + + private function writeRecord(int $slot, string $name, int $closure, int $function, int $boundThis): void + { + $record = $this->recordAddress($slot); + + $recovered = $this->arena->lockStripe($this->stripe); + + $this->arena->writeBytes($record + self::RECORD_NAME_OFFSET, $name); + $this->arena->writeWord($record + self::RECORD_WORD_NAME_LENGTH * 8, \strlen($name)); + $this->arena->writeWord($record + self::RECORD_WORD_BOUND_THIS * 8, $boundThis); + $this->arena->writeWord($record + self::RECORD_WORD_FUNCTION * 8, $function); + // Written last: a reader that sees a closure address sees a finished record behind it + $this->arena->writeWord($record + self::RECORD_WORD_CLOSURE * 8, $closure); + + $this->arena->unlockStripe($this->stripe); + + $this->recoveredLock = $this->recoveredLock || $recovered; + } + + /** + * @return array{name: string, closure: int, function: int, boundThis: int} + */ + private function readRecord(int $slot): array + { + $record = $this->recordAddress($slot); + + $recovered = $this->arena->lockStripe($this->stripe); + + $closure = $this->arena->readWord($record + self::RECORD_WORD_CLOSURE * 8); + $function = $this->arena->readWord($record + self::RECORD_WORD_FUNCTION * 8); + $length = $this->arena->readWord($record + self::RECORD_WORD_NAME_LENGTH * 8); + $boundThis = $this->arena->readWord($record + self::RECORD_WORD_BOUND_THIS * 8); + $name = $length > 0 ? $this->arena->readBytes($record + self::RECORD_NAME_OFFSET, $length) : ''; + + $this->arena->unlockStripe($this->stripe); + + $this->recoveredLock = $this->recoveredLock || $recovered; + + return ['name' => $name, 'closure' => $closure, 'function' => $function, 'boundThis' => $boundThis]; + } + + /** + * Every written record, slot => record + * + * @return array + */ + private function records(): array + { + $records = []; + $count = min($this->count(), $this->capacity); + for ($slot = 0; $slot < $count; $slot++) { + $record = $this->readRecord($slot); + if ($record['closure'] !== 0) { + $records[$slot] = $record; + } + } + + return $records; + } + + /** + * Keeps the encode-path index in step with the table + * + * Registration is a pre-fork, single-process affair, so the table is immutable by the time + * any worker asks - one scan per process is normally the whole cost, and a changed count + * is the only thing that can invalidate it. + */ + private function refreshIndex(): void + { + $count = min($this->count(), $this->capacity); + if ($count === $this->indexedRecords) { + return; + } + $this->byObject = []; + foreach ($this->records() as $slot => $record) { + $this->byObject[$record['closure']] = $this->recordAddress($slot); + } + $this->indexedRecords = $count; + } + + private function recordAddress(int $slot): int + { + return $this->address + self::HEADER_SIZE + $slot * self::RECORD_SIZE; + } + + /** + * Slot number an address identifies, or null when it is not a record of this table + */ + private function slotAt(int $address): ?int + { + $offset = $address - $this->address - self::HEADER_SIZE; + if ($offset < 0 || $offset % self::RECORD_SIZE !== 0) { + return null; + } + $slot = intdiv($offset, self::RECORD_SIZE); + + return $slot < min($this->count(), $this->capacity) ? $slot : null; + } + + /** + * Whether the object at $address is a Closure in THIS process's class table + * + * Not an acceptance test and never used as one - acceptance is registration (correction + * #8), which is precisely the finding that a stale address can hold a valid Closure of a + * different function. This is the cheap structural guard that runs before the record's + * zend_function witness is read through the object. + */ + private static function isClosureObject(int $address): bool + { + $classEntry = Core::pointerAtAddress(zend_object::class, $address)->ce; + if ($classEntry === null) { + return false; + } + $closureClass = Core::$executor->classTable->find('closure'); + if ($closureClass === null) { + return false; + } + + return Core::addressOf($closureClass->getRawClass()) === Core::addressOf($classEntry); + } + + /** + * Address of the zend_function embedded in the closure object at $address + */ + private static function functionAddressOf(int $address): int + { + $closureEntry = ClosureEntry::fromCData(Core::pointerAtAddress(zend_closure::class, $address)); + + return Core::addressOf($closureEntry->getRawFunction()); + } + + private static function objectAddressOf(\Closure $closure): int + { + $value = new ReflectionValue($closure); + + try { + return Core::addressOf($value->getRawObject()); + } finally { + $value->release(); + } + } + + /** + * Materializes the PHP value of the closure object living at $address (+1 ref, pinned) + */ + private static function closureAt(int $address): \Closure + { + $rawObject = Core::pointerAtAddress(zend_object::class, $address); + $value = ReflectionValue::newEntry(ReflectionValue::IS_OBJECT, $rawObject[0]); + $value->getNativeValue($instance); + $value->release(); + + \assert($instance instanceof \Closure); + + return $instance; + } +} diff --git a/src/Ipc/ClosureProvenanceException.php b/src/Ipc/ClosureProvenanceException.php new file mode 100644 index 0000000..fdc41fb --- /dev/null +++ b/src/Ipc/ClosureProvenanceException.php @@ -0,0 +1,154 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Lisachenko\SharedData\Ipc; + +use Lisachenko\SharedData\PersistentStore; + +/** + * A closure was offered to - or recovered from - the shared area outside its contract + * + * Sharing a closure is decided by PROVENANCE and never by inspection: spike S17 observed a + * post-fork closure address that held a different, perfectly valid Closure and executed the + * wrong function (EPIC #15, correction #8), so no property of the object can establish that + * following its address is safe. The provenance this package accepts is registration before + * the fork barrier, and every failure below is a wiring mistake in that protocol - registering + * too late, registering from a worker instead of from the process that owns the arena, or + * capturing state that cannot mean the same thing in two processes. + */ +final class ClosureProvenanceException extends \RuntimeException +{ + public static function afterBarrier(string $name, int $barrierPid): self + { + return new self(sprintf( + 'Closure "%s" cannot be registered: process %d has already marked the fork barrier, and a ' . + 'closure compiled after it is exactly the case that cannot be shared - its op_array lives ' . + 'in one worker\'s private heap, where a sibling following the address may find unrelated ' . + 'memory that still passes for a Closure. Register every shared closure before ' . + 'markForkBarrier(), or hand the work over as a shared Task object.', + $name, + $barrierPid, + )); + } + + public static function notCreator(string $name, int $creatorPid, int $currentPid): self + { + return new self(sprintf( + 'Closure "%s" cannot be registered by process %d: the closure table belongs to process %d, ' . + 'which mapped the arena. Only that process registers, and only before it forks - a closure ' . + 'created in a worker is private to it however early the worker runs.', + $name, + $currentPid, + $creatorPid, + )); + } + + public static function duplicateName(string $name): self + { + return new self(sprintf( + 'Closure "%s" is already registered. A name is bound to one closure address for the life of ' . + 'the arena, because a sibling may be holding that address right now; register the second ' . + 'implementation under its own name.', + $name, + )); + } + + public static function invalidName(string $name, int $maxLength): self + { + return new self(sprintf( + 'A shared closure name must be 1..%d bytes, got %d ("%s"); the name is stored inline in a ' . + 'fixed-size arena record so that a child can find a closure with nothing but the mapping.', + $maxLength, + \strlen($name), + $name, + )); + } + + public static function tableFull(int $capacity): self + { + return new self(sprintf( + 'All %d closure records are used. The table is pre-sized in the arena and never grows ' . + '(growing a shared structure would move it into one worker\'s private heap); create it with ' . + 'a larger capacity before the workers fork.', + $capacity, + )); + } + + public static function unknownName(string $name): self + { + return new self(sprintf( + 'No closure is registered under the name "%s"; a worker can only reach closures the ' . + 'arena-owning process registered before the fork barrier.', + $name, + )); + } + + public static function notARecord(int $address): self + { + return new self(sprintf( + 'Address 0x%x is not a closure record of this table: only an address handed out by ' . + 'registerSharedClosure() (or read back from a value record) identifies a shared closure, ' . + 'and everything else is refused before anything is dereferenced.', + $address, + )); + } + + public static function recordDrifted(int $address): self + { + return new self(sprintf( + 'The closure record at 0x%x no longer describes the closure it was written for: the object ' . + 'at the recorded address carries a different zend_function. That witness is an INTEGRITY ' . + 'check on our own record, never the acceptance test - acceptance is registration - and a ' . + 'mismatch means the pre-fork image was torn down, so nothing is dereferenced.', + $address, + )); + } + + public static function boundThisNotShared(string $name, string $className): self + { + return new self(sprintf( + 'Closure "%s" is bound to an instance of %s that this family does not share. A bound $this ' . + 'is dereferenced by the closure in whichever worker invokes it, so it must be null or an ' . + 'object living in the arena: persist it first with %s::persist(%s::class, $object) and bind ' . + 'the instance that call returns.', + $name, + $className, + PersistentStore::class, + $className, + )); + } + + public static function capturedByReference(string $name, string $variable): self + { + return new self(sprintf( + 'Closure "%s" captures $%s by reference. A reference is a slot in the creating process\'s ' . + 'request memory: after the fork every worker writes its own copy-on-write copy of it, so ' . + 'the write is silently invisible everywhere else. Capture the value instead and publish ' . + 'changes through a shared object, a SharedArray or an AtomicInt.', + $name, + $variable, + )); + } + + public static function carriesStaticState(string $name, string $variable): self + { + return new self(sprintf( + 'Closure "%s" declares the static variable $%s. Static state lives in the function\'s own ' . + 'per-request table, which every worker copy-on-writes separately, so a counter kept there ' . + 'would count each process on its own with nothing reporting the divergence. Keep the state ' . + 'in the arena (AtomicInt, SharedArray, a shared mutable object) and let the closure be pure.', + $name, + $variable, + )); + } +} diff --git a/src/Ipc/NotShareableValueException.php b/src/Ipc/NotShareableValueException.php index ba9923d..9b7e18a 100644 --- a/src/Ipc/NotShareableValueException.php +++ b/src/Ipc/NotShareableValueException.php @@ -38,14 +38,17 @@ public static function plainArray(): self public static function closure(): self { - return new self( - 'A Closure cannot be shared. Sharing one by address is only safe when the function was ' . - 'compiled BEFORE the fork barrier, and that provenance cannot be recovered from the object ' . - 'itself: spike S17 observed a post-fork closure address that held a different, perfectly ' . - 'valid Closure and executed the wrong function. Until closure exchange lands ' . - '(lisachenko/php-shared-data-extension#20), pass a shared Task object naming the work ' . - 'instead of the callable that performs it.', - ); + return new self(sprintf( + 'This Closure is not registered as a shared one. Sharing a closure by address is only safe ' . + 'when the function was compiled BEFORE the fork barrier, and that provenance cannot be ' . + 'recovered from the object itself: spike S17 observed a post-fork closure address that held ' . + 'a different, perfectly valid Closure and executed the wrong function. So provenance is ' . + 'recorded rather than inferred - call %s::registerSharedClosure($name, $closure) in the ' . + 'process that owns the arena, before it forks, and the closure travels as a record address ' . + 'from then on. A closure created after the fork cannot be registered at all: hand that work ' . + 'over as a shared Task object naming what to do instead of the callable that does it.', + ClosureProvenance::class, + )); } public static function resource(): self diff --git a/src/Ipc/ValueCodec.php b/src/Ipc/ValueCodec.php index 57b12c4..9cbe035 100644 --- a/src/Ipc/ValueCodec.php +++ b/src/Ipc/ValueCodec.php @@ -27,8 +27,14 @@ * it that produces bytes describing a value: a scalar IS the payload word, a string becomes * an arena-resident zend_string and the payload is its address, an object and a shared array * contribute nothing but their address. Anything that has no address-shaped form - a plain - * array, a resource, a closure, an object this worker family does not share - is refused - * with NotShareableValueException rather than quietly encoded. + * array, a resource, an object this worker family does not share - is refused with + * NotShareableValueException rather than quietly encoded. + * + * A closure is the one value whose shareability is not decided by its type at all: it travels + * only if it was REGISTERED before the fork barrier (ClosureProvenance), and the payload is + * then the address of its arena record. Everything else about it - its class, its handlers, + * its op_array - is deliberately never examined, because a stale post-fork address was + * observed holding a valid Closure of a different function (EPIC #15, correction #8). * * ## Sending a string costs arena bytes * @@ -51,13 +57,16 @@ final class ValueCodec { /** - * @param ArenaAllocator $allocator Source of arena memory for string records - * @param PersistentStore|null $store Registry that decides which objects are shared; - * without one, object records cannot be built + * @param ArenaAllocator $allocator Source of arena memory for string records + * @param PersistentStore|null $store Registry that decides which objects are shared; + * without one, object records cannot be built + * @param ClosureProvenance|null $closures Register of closures compiled before the fork + * barrier; without one, every closure is refused */ public function __construct( private readonly ArenaAllocator $allocator, private readonly ?PersistentStore $store = null, + private readonly ?ClosureProvenance $closures = null, ) { } @@ -76,6 +85,11 @@ public function store(): ?PersistentStore return $this->store; } + public function closures(): ?ClosureProvenance + { + return $this->closures; + } + /** * Converts a PHP value into the tag and payload of a record * @@ -111,13 +125,14 @@ public function decode(ValueTag $tag, int $payload): mixed { return match ($tag) { ValueTag::Nil, ValueTag::Close => null, - ValueTag::True => true, - ValueTag::False => false, - ValueTag::Int => $payload, - ValueTag::Float => self::bitsToFloat($payload), - ValueTag::Str => $this->readString($payload), - ValueTag::Obj => $this->attachObject($payload), - ValueTag::Arr => SharedArray::attach($this->allocator, $this, $payload), + ValueTag::True => true, + ValueTag::False => false, + ValueTag::Int => $payload, + ValueTag::Float => self::bitsToFloat($payload), + ValueTag::Str => $this->readString($payload), + ValueTag::Obj => $this->attachObject($payload), + ValueTag::Arr => SharedArray::attach($this->allocator, $this, $payload), + ValueTag::Closure => $this->resolveClosure($payload), }; } @@ -152,8 +167,15 @@ private function encodeObject(object $value): array if ($value instanceof \Closure) { // Provenance, never shape: a stale post-fork closure address can hold a valid // Closure of a DIFFERENT function (EPIC #15, correction #8), so inspection can - // never establish that sharing this one is safe - throw NotShareableValueException::closure(); + // never establish that sharing this one is safe. The one provenance that IS + // sound is registration before the fork barrier, and it is a table lookup - + // nothing about the object is examined here either way + $record = $this->closures?->addressOfClosure($value); + if ($record === null) { + throw NotShareableValueException::closure(); + } + + return [ValueTag::Closure, $record]; } if ($this->store === null) { throw NotShareableValueException::withoutStore($value::class); @@ -167,6 +189,24 @@ private function encodeObject(object $value): array return [ValueTag::Obj, $address]; } + /** + * Rebuilds the closure a record describes, in the process that received the record + * + * The payload is the address of the arena RECORD, not of the closure: the record is what + * lives in shared memory and what proves the closure predates the fork. Resolving it is a + * bounds-checked table lookup followed by an integrity check on the object the record + * points at - see ClosureProvenance::resolve(). + */ + private function resolveClosure(int $address): \Closure + { + $this->assertShared($address); + if ($this->closures === null) { + throw NotShareableValueException::closure(); + } + + return $this->closures->resolve($address); + } + private function attachObject(int $address): object { $this->assertShared($address); diff --git a/src/Ipc/ValueTag.php b/src/Ipc/ValueTag.php index 904f4bd..c886151 100644 --- a/src/Ipc/ValueTag.php +++ b/src/Ipc/ValueTag.php @@ -17,10 +17,14 @@ * What the eight payload bytes of a value record mean * * The tag is the entire type system of the shared area: a value that crosses a worker - * boundary is one of these nine shapes and nothing else. Three of them carry no payload at - * all, two carry the value itself, three carry an ADDRESS inside the arena, and one is the + * boundary is one of these ten shapes and nothing else. Three of them carry no payload at + * all, two carry the value itself, four carry an ADDRESS inside the arena, and one is the * control tag channels use to publish their end of stream. * + * The set is APPENDED to, never renumbered: the same numbers are the wire contract of the + * consumer runtime (`TaggedRecord` in native-php-coroutines), so a reader built against an + * older tag set still reads every record it knows and refuses the one it does not. + * * Deliberately absent: any tag that would mean "a byte encoding of a PHP value graph". * Serialization is what the arena exists to avoid - see ValueCodec. */ @@ -62,6 +66,16 @@ enum ValueTag: int */ case Close = 8; + /** + * Payload is the address of a CLOSURE RECORD in the arena - never a closure itself + * + * The record is the arena-resident proof that the closure was registered before the fork + * barrier, which is the only provenance under which following a closure address is safe + * (EPIC #15, correction #8). The closure object itself stays where it was compiled, in + * memory the whole family inherited; see ClosureProvenance. + */ + case Closure = 9; + /** * Whether the payload is an arena address rather than a value * @@ -70,6 +84,6 @@ enum ValueTag: int */ public function isAddress(): bool { - return $this === self::Str || $this === self::Obj || $this === self::Arr; + return $this === self::Str || $this === self::Obj || $this === self::Arr || $this === self::Closure; } } diff --git a/tests/Ipc/SharedClosureForkTest.php b/tests/Ipc/SharedClosureForkTest.php new file mode 100644 index 0000000..842ace8 --- /dev/null +++ b/tests/Ipc/SharedClosureForkTest.php @@ -0,0 +1,358 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Lisachenko\SharedData\Ipc; + +use Lisachenko\SharedData\Stub\GraphNode; + +/** + * Closure exchange, Phase A: a closure compiled before the fork, invoked in several workers + * + * The claim under test is narrow and it is the only one Phase A makes: a closure REGISTERED + * before the fork barrier can be reached by address in every process of the family and + * invoked there, concurrently, with correct results - and nothing else can. Registration is + * the whole acceptance test, so the refusals matter as much as the invocations: a closure the + * register does not know is refused by the codec exactly as it was before this feature + * existed, and a registration attempted after the barrier (or from a worker) is refused + * outright rather than resolved into something plausible. + * + * Everything the children answer with travels as an exit code or as an arena word. The record + * addresses themselves reach them either over a socket pair, as eight machine-order bytes, or + * inside a value record on a SharedChannel - never as a serialized value. + */ +final class SharedClosureForkTest extends IpcTestCase +{ + private const int ROUNDS = 100_000; + + private const int SCALE_FACTOR = 3; + + /** + * Register of this suite, created and filled ONCE per process, before anything forks + */ + private static ?ClosureProvenance $closures = null; + + /** + * A second register kept deliberately open, so the "workers never register" rule can be + * observed on its own instead of behind the barrier refusal + */ + private static ?ClosureProvenance $openRegister = null; + + private static ?ValueCodec $closureCodec = null; + + /** + * @var array name => record address + */ + private static array $records = []; + + /** + * The register every test shares: closures registered, barrier marked, nothing pending + * + * Test order is deliberately irrelevant here. Registration is a pre-fork, one-shot phase + * of a process's life, not something a test may re-open, so the whole phase runs once in + * this accessor and every case observes the same finished state. + */ + private function closures(): ClosureProvenance + { + if (self::$closures !== null) { + return self::$closures; + } + $register = ClosureProvenance::create($this->allocator(), $this->store(), 16, 'closures-suite'); + + $factor = self::SCALE_FACTOR; + $node = $this->sharedNode(); + + self::$records['scale'] = $register->registerSharedClosure( + 'scale', + static fn (int $value): int => $value * $factor, + ); + self::$records['square'] = $register->registerSharedClosure( + 'square', + static fn (int $value): int => $value * $value, + ); + self::$records['name'] = $register->registerSharedClosure( + 'name', + static fn (): string => $node->name, + ); + + $register->markForkBarrier(); + + return self::$closures = $register; + } + + private function openRegister(): ClosureProvenance + { + return self::$openRegister ??= ClosureProvenance::create( + $this->allocator(), + $this->store(), + 4, + 'closures-open', + ); + } + + /** + * A codec that knows the register - the only difference from the suite's default one + */ + private function closureCodec(): ValueCodec + { + return self::$closureCodec ??= new ValueCodec($this->allocator(), $this->store(), $this->closures()); + } + + public function testTwoChildrenInvokeAPreForkClosureAHundredThousandTimesEach(): void + { + $register = $this->closures(); + $record = self::$records['scale']; + $sums = $this->arena()->allocate(16); + + $expected = 0; + for ($round = 0; $round < self::ROUNDS; $round++) { + $expected += $round * self::SCALE_FACTOR; + } + + $children = []; + for ($worker = 0; $worker < 2; $worker++) { + $pair = []; + $this->assertTrue(socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $pair), 'no socket pair'); + + $slot = $sums + $worker * 8; + $children[] = $this->fork(function () use ($pair, $register, $slot): int { + socket_close($pair[0]); + $bytes = socket_read($pair[1], 8, PHP_BINARY_READ); + socket_close($pair[1]); + if ($bytes === false || \strlen($bytes) !== 8) { + return self::WRONG_STATE; + } + /** @var array{1: int} $address */ + $address = unpack('Q', $bytes); + + // Eight bytes arrived; the closure they name is invoked entirely in this process + $scale = $register->resolve($address[1]); + + $sum = 0; + for ($round = 0; $round < self::ROUNDS; $round++) { + $sum += $scale($round); + } + $this->arena()->writeWord($slot, $sum); + + return self::OK; + }); + + socket_close($pair[1]); + socket_write($pair[0], pack('Q', $record), 8); + socket_close($pair[0]); + } + + $this->awaitAll($children, 'a child could not invoke the shared closure'); + + $this->assertSame($expected, $this->arena()->readWord($sums), 'first worker computed a different sum'); + $this->assertSame($expected, $this->arena()->readWord($sums + 8), 'second worker computed a different sum'); + } + + public function testAClosureCrossesAChannelAsARecordAddressAndRunsInTheReceiver(): void + { + $codec = $this->closureCodec(); + $channel = SharedChannel::create($this->allocator(), $codec, $this->wake(), 4); + $answer = $this->arena()->allocate(8); + + $child = $this->fork(function () use ($channel, $answer): int { + [$closure, $received] = $channel->recv(5.0); + if (!$received || !$closure instanceof \Closure) { + return self::WRONG_STATE; + } + $this->arena()->writeWord($answer, $closure(12)); + + return self::OK; + }); + + $channel->send($this->closures()->closure('square'), 5.0); + + $this->assertSame(self::OK, $this->await($child), 'the child could not run the closure it received'); + $this->assertSame(144, $this->arena()->readWord($answer)); + } + + public function testAClosureCapturingASharedObjectReadsItInEveryWorker(): void + { + $register = $this->closures(); + $record = self::$records['name']; + $expected = $this->sharedNode()->name; + + $child = $this->fork(static function () use ($register, $record, $expected): int { + $describe = $register->resolve($record); + + return $describe() === $expected ? self::OK : self::WRONG_VALUE; + }); + + $this->assertSame(self::OK, $this->await($child), 'the captured shared object did not read back'); + } + + public function testTheRecordTravelsWhileTheClosureItselfStaysWhereItWasCompiled(): void + { + $closure = $this->closures()->closure('square'); + + [$tag, $payload] = $this->closureCodec()->encode($closure); + + $this->assertSame(ValueTag::Closure, $tag); + $this->assertTrue($tag->isAddress()); + $this->assertSame(self::$records['square'], $payload); + $this->assertTrue($this->arena()->contains($payload, 8), 'the record does not live in the arena'); + + // Phase A copies nothing: the object stays in the memory the family inherited, and only + // the RECORD that vouches for it is shared (docs/closure-cloning.md) + $this->assertFalse( + $this->arena()->contains($this->closures()->closureAddressOf('square'), 8), + 'the closure object itself was copied into the arena', + ); + + $decoded = $this->closureCodec()->decode($tag, $payload); + $this->assertInstanceOf(\Closure::class, $decoded); + $this->assertSame(49, $decoded(7)); + } + + public function testRegisteringAfterTheForkBarrierIsRefused(): void + { + $register = $this->closures(); + $this->assertTrue($register->isForkBarrierPassed()); + + $this->expectException(ClosureProvenanceException::class); + $this->expectExceptionMessageMatches('/already marked the fork barrier/'); + + $register->registerSharedClosure('too-late', static fn (): int => 1); + } + + public function testAWorkerNeverRegistersAClosureOfItsOwnEvenBeforeAnyBarrier(): void + { + $register = $this->openRegister(); + $this->assertFalse($register->isForkBarrierPassed(), 'this register is deliberately still open'); + + $child = $this->fork(static function () use ($register): int { + try { + $register->registerSharedClosure('from-a-worker', static fn (): int => 1); + } catch (ClosureProvenanceException) { + return self::OK; + } + + return self::WRONG_STATE; + }); + + $this->assertSame(self::OK, $this->await($child), 'a worker was allowed to register a closure'); + $this->assertNotContains('from-a-worker', $register->names(), 'a worker wrote a record into the table'); + } + + public function testAnUnregisteredClosureIsRefusedAndNamesTheRegistration(): void + { + $this->expectException(NotShareableValueException::class); + $this->expectExceptionMessageMatches('/registerSharedClosure/'); + + $this->closureCodec()->encode(static fn (): int => 1); + } + + public function testACodecWithoutARegisterRefusesEveryClosureExactlyAsBefore(): void + { + $this->expectException(NotShareableValueException::class); + $this->expectExceptionMessageMatches('/compiled BEFORE the fork barrier.+Task object/s'); + + $this->codec()->encode($this->closures()->closure('square')); + } + + public function testAnAddressThatIsNotARecordIsRefusedBeforeAnythingIsDereferenced(): void + { + $this->expectException(ClosureProvenanceException::class); + $this->expectExceptionMessageMatches('/is not a closure record/'); + + // Inside the table, but four bytes past the start of a record: a plausible address is + // still refused, because the check is arithmetic on our own layout and not a guess + $this->closures()->resolve(self::$records['scale'] + 8); + } + + public function testACaptureByReferenceIsRefused(): void + { + $counter = 0; + + $this->expectException(ClosureProvenanceException::class); + $this->expectExceptionMessageMatches('/captures \$counter by reference/'); + + $this->openRegister()->registerSharedClosure('by-reference', static function () use (&$counter): void { + $counter++; + }); + } + + public function testAStaticVariableInsideAClosureIsRefused(): void + { + $this->expectException(ClosureProvenanceException::class); + $this->expectExceptionMessageMatches('/declares the static variable \$seen/'); + + $this->openRegister()->registerSharedClosure('with-static', static function (): int { + static $seen = 0; + + return ++$seen; + }); + } + + public function testACapturedPlainArrayIsRefusedAndPointsAtSharedArray(): void + { + $rows = [1, 2, 3]; + + $this->expectException(NotShareableValueException::class); + $this->expectExceptionMessageMatches('/SharedArray/'); + + $this->openRegister()->registerSharedClosure('with-array', static fn (): int => \count($rows)); + } + + public function testACapturedRequestObjectIsRefusedAndNamesPersist(): void + { + $node = new GraphNode(); + + $this->expectException(NotShareableValueException::class); + $this->expectExceptionMessageMatches('/PersistentStore::persist\(/'); + + $this->openRegister()->registerSharedClosure('with-object', static fn (): string => $node->name); + } + + public function testAClosureBoundToARequestObjectIsRefused(): void + { + $node = new GraphNode(); + $bound = \Closure::bind(function (): string { + return $this->name; + }, $node, GraphNode::class); + + $this->expectException(ClosureProvenanceException::class); + $this->expectExceptionMessageMatches('/bound to an instance of/'); + + $this->openRegister()->registerSharedClosure('bound-to-request', $bound); + } + + public function testAClosureBoundToASharedObjectIsAcceptedAndRunsInAWorker(): void + { + $shared = $this->sharedNode(); + $bound = \Closure::bind(function (): int { + return $this->counter; + }, $shared, GraphNode::class); + + $register = $this->openRegister(); + $record = $register->registerSharedClosure('bound-to-shared', $bound); + + $this->assertSame( + $this->store()->sharedIdOf($shared), + $register->boundThisAddressOf('bound-to-shared'), + 'the record does not carry the arena address of the bound $this', + ); + + $expected = $shared->counter; + $child = $this->fork(static function () use ($register, $record, $expected): int { + $read = $register->resolve($record); + + return $read() === $expected ? self::OK : self::WRONG_VALUE; + }); + + $this->assertSame(self::OK, $this->await($child), 'the bound shared object did not read back in a worker'); + } +}