From 9c29f1d6eed7346f68cf4495ae9d0c9d80b123fd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 00:15:03 +0000 Subject: [PATCH 1/2] fix(preemption): chain the interrupt handler before suspending Current PHP builds (8.4.28+, 8.5.13+ and 8.6.0) check EG(vm_interrupt) when an internal call returns. The flag Preemptor::onTick() raises is therefore taken while the tick handler is still running, inside ext-pcntl's signal dispatch, where the engine blocks every fiber switch. The callback consumed the request there, Fiber::suspend() threw a FiberError it swallows, and no coroutine was ever preempted: seven preemption tests failed on all three minors with current interpreter builds. The callback now chains proceed() first and decides afterwards, outside the dispatch frame, and shouldPreempt() declines while a tick is being dispatched, leaving the request pending for the outer invocation. Also adds PHP 8.6 to every CI job (z-engine ~8.6.0@dev, resolving 8.6.x-dev until it is tagged), and drops a null-coalesce on a value PHPStan 2.3 proves non-null. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FxhC1D34vSRsQVcgd3HwS6 --- .github/workflows/ci.yml | 15 ++++++---- AGENTS.md | 18 +++++++++--- README.md | 17 ++++++----- composer.json | 2 +- src/Preemption/InterruptBridge.php | 30 ++++++++++++------- src/Preemption/ItimerClock.php | 2 +- src/Preemption/Preemptor.php | 46 +++++++++++++++++++++++------- 7 files changed, 89 insertions(+), 41 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 74c8637..ba0dfcc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,9 +9,12 @@ on: permissions: contents: read -# z-engine tracks one PHP minor per release line; the "~8.4.2 || ~8.5.0" -# constraint lets Composer resolve the line matching each runner's PHP, so the -# suite runs on PHP 8.4 and 8.5 in parallel. +# z-engine tracks one PHP minor per release line; the +# "~8.4.2 || ~8.5.0 || ~8.6.0@dev" constraint lets Composer resolve the line +# matching each runner's PHP, so the suite runs on PHP 8.4, 8.5 and 8.6 in +# parallel. Every leg is required: PHP 8.6 is a GA release, not an allowed +# failure. Until z-engine tags 8.6.0 its leg resolves the 8.6.x-dev line +# (master); "prefer-stable" switches it to the tag as soon as one exists. jobs: tests: name: Tests (PHP ${{ matrix.php }}) @@ -19,7 +22,7 @@ jobs: strategy: fail-fast: false matrix: - php: ['8.4', '8.5'] + php: ['8.4', '8.5', '8.6'] steps: - uses: actions/checkout@v7 @@ -43,7 +46,7 @@ jobs: strategy: fail-fast: false matrix: - php: ['8.4', '8.5'] + php: ['8.4', '8.5', '8.6'] steps: - uses: actions/checkout@v7 - uses: shivammathur/setup-php@v2 @@ -68,7 +71,7 @@ jobs: strategy: fail-fast: false matrix: - php: ['8.4', '8.5'] + php: ['8.4', '8.5', '8.6'] steps: - uses: actions/checkout@v7 - uses: shivammathur/setup-php@v2 diff --git a/AGENTS.md b/AGENTS.md index e2ff62f..7b3ebbe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -125,7 +125,14 @@ The mechanism was selected by experiment, and the negative result is the load-be happens inside the z-engine `InterruptHook` callback. - **The whole callback body must be `try`/`catch`-wrapped.** A throwable escaping an FFI callback is an uncatchable "Throwing from FFI callbacks is not allowed" fatal — no `catch` upstream ever runs. -- **Always chain `proceed()`** so a previously installed handler still runs. +- **Always chain `proceed()`, and chain it *before* deciding to suspend.** A previously installed + handler must still run — ext-pcntl's is where SIGALRM reaches the PHP-level tick handler. Chaining + first is also what makes preemption work at all on current PHP builds (8.4.28+, 8.5.13+, 8.6): + they check for an interrupt when an internal call returns, so the flag the tick handler raises is + taken *inside* that handler, under pcntl's fiber-switch block. `Preemptor::shouldPreempt()` + declines there (`dispatchingTick`) without consuming the request, and the outer callback takes + it once `proceed()` has returned. Suspending first and chaining second lost every request this + way: `Fiber::suspend()` threw a swallowed `FiberError` and no coroutine was ever preempted. - **No autoloading inside the callback.** Preload every class the callback touches; triggering the autoloader from an engine hook re-enters the compiler. - **Only ever `resume(null)` a preempt-suspended fiber. Never `Fiber::throw()` into one** — the spike @@ -311,7 +318,9 @@ in every process. ### z-engine's line must match the running PHP minor z-engine reads engine structures by byte offset and those offsets change on every PHP minor, so the -constraint is `~8.4.2 || ~8.5.0` — Composer resolves the stable line matching the running PHP. +constraint is `~8.4.2 || ~8.5.0 || ~8.6.0@dev` — Composer resolves the line matching the running PHP: +the stable tags on 8.4 and 8.5, and z-engine's `8.6.x-dev` (`master`) on 8.6 until z-engine tags +8.6.0, at which point `"prefer-stable"` moves it onto the tag and the `@dev` flag can go. `ZEngine\Core::init()` enforces the exact match and refuses to boot on a mismatch. **Never loosen the constraint, skip `Core::init()`, or defeat the guard to make a failure go away.** A refusal is the guard working. @@ -334,7 +343,7 @@ Those two, and nothing else. A third line, `error_reporting=E_ALL & ~E_DEPRECATE alongside them: PHPUnit's `.phpt` runner forces `display_errors=1`, so a deprecation raised by the **dependency** — z-engine, back when it was consumed from a development branch — was prepended to a test's captured output and failed an `--EXPECT--` block over noise. The stable releases now required -(`~8.4.2 || ~8.5.0`) raise none, and the suppression was hiding **this package's own** deprecations +(`~8.4.2 || ~8.5.0`, and the 8.6 line) raise none, and the suppression was hiding **this package's own** deprecations too: that is how the `SplObjectStorage::contains()` call PHP 8.5 deprecated (#39) sat green through 12 tests. The suite now runs at the runner's default `error_reporting`, so a deprecation from our code fails a test the day it appears. **Do not re-add a diagnostic filter to a `.phpt`** — the guard @@ -343,6 +352,7 @@ test rejects any `error_reporting` line in an `--INI--` section. ```bash php8.4 -d ffi.enable=1 -d opcache.jit=off vendor/bin/phpunit php8.5 -d ffi.enable=1 -d opcache.jit=off vendor/bin/phpunit +php8.6 -d ffi.enable=1 -d opcache.jit=off vendor/bin/phpunit ``` ### Coding standards are a local step, not a CI job @@ -353,7 +363,7 @@ composer cs:check # the same, without writing composer phpstan # level max, must be clean ``` -CI runs **`tests`, `static-analysis` and the bounded `preemption-soak`**, all across PHP 8.4 and 8.5. +CI runs **`tests`, `static-analysis` and the bounded `preemption-soak`**, all across PHP 8.4, 8.5 and 8.6 — every leg required, 8.6 included. The coding-standards job was deliberately removed: php-cs-fixer is a development tool here, and re-checking on a runner only turns a fixable formatting nit into a red build. **Do not re-add it.** diff --git a/README.md b/README.md index be208e3..4a52f7d 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,10 @@ fork-shared `mmap` arena and travel as addresses. composer require lisachenko/native-php-coroutines ``` -z-engine is required as `~8.4.2 || ~8.5.0` — one stable release line per supported PHP minor, -resolved by Composer to match the running PHP. `lisachenko/php-shared-data-extension` is still +z-engine is required as `~8.4.2 || ~8.5.0 || ~8.6.0@dev` — one release line per supported PHP +minor, resolved by Composer to match the running PHP. 8.4 and 8.5 are stable tags; on PHP 8.6 the +line is z-engine's `8.6.x-dev` (its `master` branch) until z-engine tags 8.6.0, which the same +`"minimum-stability": "dev"` / `"prefer-stable": true` pair below already admits. `lisachenko/php-shared-data-extension` is still consumed from `dev-main` (it has no tags yet), so this package keeps `"minimum-stability": "dev"` with `"prefer-stable": true` at its root, and a consuming project needs the same pair until that dependency is tagged — Composer only resolves development stability at the root level. @@ -526,11 +528,11 @@ z-engine requires it, and z-engine is a hard dependency of this package. ## Requirements -- PHP **8.4** or **8.5**, NTS. +- PHP **8.4**, **8.5** or **8.6**, NTS. - `ext-ffi` with `ffi.enable=1`, and `opcache.jit=off` — the JIT rewrites the executor internals the engine hooks depend on. -- `lisachenko/z-engine`, resolved per PHP minor (`8.4.x` on 8.4, `8.5.x` on 8.5, from the - `~8.4.2 || ~8.5.0` constraint) — engine structures are read by byte offset, so the line must +- `lisachenko/z-engine`, resolved per PHP minor (`8.4.x` on 8.4, `8.5.x` on 8.5, `8.6.x-dev` on 8.6, + from the `~8.4.2 || ~8.5.0 || ~8.6.0@dev` constraint) — engine structures are read by byte offset, so the line must match the running minor. `ZEngine\Core::init()` enforces it and refuses to boot on a mismatch. - `ext-pcntl` and `ext-posix` for the parallel and preemption layers (suggested, not required). @@ -596,14 +598,15 @@ z-engine requires it, and z-engine is a hard dependency of this package. ## Development ```bash -php8.4 -d ffi.enable=1 -d opcache.jit=off vendor/bin/phpunit # the suite, on both minors +php8.4 -d ffi.enable=1 -d opcache.jit=off vendor/bin/phpunit # the suite, on every minor php8.5 -d ffi.enable=1 -d opcache.jit=off vendor/bin/phpunit +php8.6 -d ffi.enable=1 -d opcache.jit=off vendor/bin/phpunit composer phpstan # level max composer cs:fix # PER-CS2.0, a local step ``` Coding standards are deliberately **not** a CI job — CI runs `tests`, `static-analysis` and a -bounded `preemption-soak` across PHP 8.4 and 8.5. A segfault is an engine-level bug, never a flaky test: capture the command, the PHP +bounded `preemption-soak` across PHP 8.4, 8.5 and 8.6, every leg required. A segfault is an engine-level bug, never a flaky test: capture the command, the PHP version and a minimal reproducer instead of retrying. Contributor rules — the engine contracts, the shared-memory disciplines, the preemption obligations diff --git a/composer.json b/composer.json index 6b82f6f..0ead477 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "php": "^8.4", "ext-ffi": "*", "lisachenko/php-shared-data-extension": "dev-main", - "lisachenko/z-engine": "~8.4.2 || ~8.5.0" + "lisachenko/z-engine": "~8.4.2 || ~8.5.0 || ~8.6.0@dev" }, "minimum-stability": "dev", "prefer-stable": true, diff --git a/src/Preemption/InterruptBridge.php b/src/Preemption/InterruptBridge.php index d6f722e..c85d69f 100644 --- a/src/Preemption/InterruptBridge.php +++ b/src/Preemption/InterruptBridge.php @@ -131,32 +131,40 @@ public function requestInterrupt(): void /** * The engine callback. Runs inside the interrupted frame, in the interrupted coroutine's fiber. * - * Read the two `try` blocks as one rule each: the first must never let a throwable out, and the - * second must never let a chained handler be skipped — including when the first one suspended - * and the coroutine was resumed seconds later, which is exactly where control returns to. + * Read the two `try` blocks as one rule each: the first must never let a chained handler be + * skipped, and the second must never let a throwable out. + * + * The chained handler runs **first**. ext-pcntl's is where the slice timer's SIGALRM is + * dispatched to {@see Preemptor}, so chaining first means the tick that brought control here is + * already recorded when the policy is asked, and the suspend happens after pcntl's dispatch has + * returned — that dispatch blocks every fiber switch for as long as it runs. Current PHP builds + * (8.4.28+, 8.5.13+, 8.6) also check for an interrupt when an internal call returns, so this + * callback is re-entered from *inside* the PHP signal handler as well; the policy declines there + * without consuming the request, and this outer invocation takes it once `proceed()` returns. */ private function onInterrupt(InterruptHook $hook): void { + try { + if ($hook->hasOriginalHandler()) { + $hook->proceed(); + } + } catch (\Throwable) { + } + try { if (\Fiber::getCurrent() !== null && ($this->shouldPreempt)()) { $this->preemptions++; // Control leaves the process's PHP stack here and comes back in // Scheduler::runNext(), which sees SuspendCommand::PREEMPT and re-queues the - // coroutine. Execution resumes on the next line when it gets the CPU again. + // coroutine. Execution resumes on the next line when it gets the CPU again, with + // nothing left to do: the chained handler has already run. \Fiber::suspend(SuspendCommand::PREEMPT); } } catch (\Throwable) { // Deliberately swallowed and deliberately not logged: logging is user code, user code // can throw, and a throw from here is an uncatchable fatal. } - - try { - if ($hook->hasOriginalHandler()) { - $hook->proceed(); - } - } catch (\Throwable) { - } } /** diff --git a/src/Preemption/ItimerClock.php b/src/Preemption/ItimerClock.php index 00d287a..35ae688 100644 --- a/src/Preemption/ItimerClock.php +++ b/src/Preemption/ItimerClock.php @@ -265,7 +265,7 @@ private static function bindLibc(): \FFI } throw new \RuntimeException( - 'could not bind setitimer(2) through FFI: ' . ($failure?->getMessage() ?? 'unknown reason'), + 'could not bind setitimer(2) through FFI: ' . $failure->getMessage(), 0, $failure, ); diff --git a/src/Preemption/Preemptor.php b/src/Preemption/Preemptor.php index d259106..3194b88 100644 --- a/src/Preemption/Preemptor.php +++ b/src/Preemption/Preemptor.php @@ -27,11 +27,17 @@ * # The path a preemption takes * * 1. `setitimer(ITIMER_REAL)` raises `SIGALRM` every slice. - * 2. ext-pcntl's C handler raises `EG(vm_interrupt)`; {@see self::onTick()} — the PHP-level handler - * — records that a preemption is *wanted* and raises the flag again, so the callback is reached - * outside pcntl's own dispatch frame. - * 3. The engine calls the interrupt callback at the next check (a loop back-edge or a function - * entry), the callback asks {@see self::shouldPreempt()}, and suspends if the answer is yes. + * 2. ext-pcntl's C handler raises `EG(vm_interrupt)`. The engine calls the interrupt callback at + * the next check (a loop back-edge, a function entry, or the return of an internal call), and + * the callback first chains to ext-pcntl, whose dispatch runs {@see self::onTick()} — the + * PHP-level handler — which records that a preemption is *wanted*. + * 3. Back in the callback, now outside pcntl's dispatch frame, it asks {@see self::shouldPreempt()} + * and suspends if the answer is yes. + * + * Current PHP builds (8.4.28+, 8.5.13+, 8.6) also check for an interrupt when an internal call + * returns, so the flag {@see self::onTick()} raises is taken *inside* the handler, where the engine + * blocks every fiber switch. {@see self::$dispatchingTick} makes that nested callback decline + * without consuming the request, and the outer callback takes it once the dispatch has returned. * * # What makes the answer "no" * @@ -111,6 +117,15 @@ final class Preemptor private int $criticalDepth = 0; + /** + * {@see self::onTick()} is running, i.e. control is inside ext-pcntl's signal dispatch. + * + * The engine refuses every fiber switch there, so an interrupt callback reached from inside the + * handler must leave the request pending instead of consuming it on a suspend that can only + * fail with `FiberError`. + */ + private bool $dispatchingTick = false; + /** * The clock is stopped because the process is blocked in the poller with nothing running. * @@ -380,7 +395,7 @@ public function withCriticalSection(\Closure $body): mixed */ public function shouldPreempt(): bool { - if (!$this->armed || !$this->requested || $this->criticalDepth > 0) { + if (!$this->armed || !$this->requested || $this->criticalDepth > 0 || $this->dispatchingTick) { return false; } @@ -402,18 +417,27 @@ public function shouldPreempt(): bool * The PHP-level SIGALRM handler. * * It may not suspend anything — the engine refuses fiber switches from signal dispatch, always - * and on every dispatch path — so it records the request and raises the VM interrupt flag, - * which gets the interrupt callback invoked outside pcntl's dispatch frame. + * and on every dispatch path — so it records the request and raises the VM interrupt flag. On + * the async path the interrupt callback that is dispatching this handler takes the request as + * soon as the dispatch returns; on current PHP builds the raised flag is also seen by a nested + * callback while this method still runs, and {@see self::$dispatchingTick} makes that one + * decline. * * @param int $signal The delivered signal, always SIGALRM here. * @param mixed $details ext-pcntl's siginfo payload; unused. */ private function onTick(int $signal, mixed $details = null): void { - $this->requested = true; + $this->dispatchingTick = true; - if ($this->criticalDepth === 0) { - $this->bridge->requestInterrupt(); + try { + $this->requested = true; + + if ($this->criticalDepth === 0) { + $this->bridge->requestInterrupt(); + } + } finally { + $this->dispatchingTick = false; } } From 499f6871df2e03c7873f9a20a119a249be0c8a99 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 11:57:35 +0000 Subject: [PATCH 2/2] chore(deps): require the stable z-engine 8.6.0 release z-engine tagged 8.6.0, so the PHP 8.6 line no longer needs its 8.6.x-dev branch: the constraint becomes ~8.4.2 || ~8.5.0 || ~8.6.0, every minor resolves a stable tag, and the docs drop the root-level workaround a consumer on PHP 8.6 needed until now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FxhC1D34vSRsQVcgd3HwS6 --- .github/workflows/ci.yml | 6 ++---- AGENTS.md | 6 ++---- README.md | 10 ++++------ composer.json | 2 +- 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba0dfcc..0f6a477 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,11 +10,9 @@ permissions: contents: read # z-engine tracks one PHP minor per release line; the -# "~8.4.2 || ~8.5.0 || ~8.6.0@dev" constraint lets Composer resolve the line +# "~8.4.2 || ~8.5.0 || ~8.6.0" constraint lets Composer resolve the stable line # matching each runner's PHP, so the suite runs on PHP 8.4, 8.5 and 8.6 in -# parallel. Every leg is required: PHP 8.6 is a GA release, not an allowed -# failure. Until z-engine tags 8.6.0 its leg resolves the 8.6.x-dev line -# (master); "prefer-stable" switches it to the tag as soon as one exists. +# parallel. Every leg is required. jobs: tests: name: Tests (PHP ${{ matrix.php }}) diff --git a/AGENTS.md b/AGENTS.md index 7b3ebbe..afb3fa2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -318,9 +318,7 @@ in every process. ### z-engine's line must match the running PHP minor z-engine reads engine structures by byte offset and those offsets change on every PHP minor, so the -constraint is `~8.4.2 || ~8.5.0 || ~8.6.0@dev` — Composer resolves the line matching the running PHP: -the stable tags on 8.4 and 8.5, and z-engine's `8.6.x-dev` (`master`) on 8.6 until z-engine tags -8.6.0, at which point `"prefer-stable"` moves it onto the tag and the `@dev` flag can go. +constraint is `~8.4.2 || ~8.5.0 || ~8.6.0` — Composer resolves the stable line matching the running PHP. `ZEngine\Core::init()` enforces the exact match and refuses to boot on a mismatch. **Never loosen the constraint, skip `Core::init()`, or defeat the guard to make a failure go away.** A refusal is the guard working. @@ -343,7 +341,7 @@ Those two, and nothing else. A third line, `error_reporting=E_ALL & ~E_DEPRECATE alongside them: PHPUnit's `.phpt` runner forces `display_errors=1`, so a deprecation raised by the **dependency** — z-engine, back when it was consumed from a development branch — was prepended to a test's captured output and failed an `--EXPECT--` block over noise. The stable releases now required -(`~8.4.2 || ~8.5.0`, and the 8.6 line) raise none, and the suppression was hiding **this package's own** deprecations +(`~8.4.2 || ~8.5.0 || ~8.6.0`) raise none, and the suppression was hiding **this package's own** deprecations too: that is how the `SplObjectStorage::contains()` call PHP 8.5 deprecated (#39) sat green through 12 tests. The suite now runs at the runner's default `error_reporting`, so a deprecation from our code fails a test the day it appears. **Do not re-add a diagnostic filter to a `.phpt`** — the guard diff --git a/README.md b/README.md index 4a52f7d..a18df58 100644 --- a/README.md +++ b/README.md @@ -24,10 +24,8 @@ fork-shared `mmap` arena and travel as addresses. composer require lisachenko/native-php-coroutines ``` -z-engine is required as `~8.4.2 || ~8.5.0 || ~8.6.0@dev` — one release line per supported PHP -minor, resolved by Composer to match the running PHP. 8.4 and 8.5 are stable tags; on PHP 8.6 the -line is z-engine's `8.6.x-dev` (its `master` branch) until z-engine tags 8.6.0, which the same -`"minimum-stability": "dev"` / `"prefer-stable": true` pair below already admits. `lisachenko/php-shared-data-extension` is still +z-engine is required as `~8.4.2 || ~8.5.0 || ~8.6.0` — one stable release line per supported PHP +minor, resolved by Composer to match the running PHP. `lisachenko/php-shared-data-extension` is still consumed from `dev-main` (it has no tags yet), so this package keeps `"minimum-stability": "dev"` with `"prefer-stable": true` at its root, and a consuming project needs the same pair until that dependency is tagged — Composer only resolves development stability at the root level. @@ -531,8 +529,8 @@ z-engine requires it, and z-engine is a hard dependency of this package. - PHP **8.4**, **8.5** or **8.6**, NTS. - `ext-ffi` with `ffi.enable=1`, and `opcache.jit=off` — the JIT rewrites the executor internals the engine hooks depend on. -- `lisachenko/z-engine`, resolved per PHP minor (`8.4.x` on 8.4, `8.5.x` on 8.5, `8.6.x-dev` on 8.6, - from the `~8.4.2 || ~8.5.0 || ~8.6.0@dev` constraint) — engine structures are read by byte offset, so the line must +- `lisachenko/z-engine`, resolved per PHP minor (`8.4.x` on 8.4, `8.5.x` on 8.5, `8.6.x` on 8.6, + from the `~8.4.2 || ~8.5.0 || ~8.6.0` constraint) — engine structures are read by byte offset, so the line must match the running minor. `ZEngine\Core::init()` enforces it and refuses to boot on a mismatch. - `ext-pcntl` and `ext-posix` for the parallel and preemption layers (suggested, not required). diff --git a/composer.json b/composer.json index 0ead477..569b304 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "php": "^8.4", "ext-ffi": "*", "lisachenko/php-shared-data-extension": "dev-main", - "lisachenko/z-engine": "~8.4.2 || ~8.5.0 || ~8.6.0@dev" + "lisachenko/z-engine": "~8.4.2 || ~8.5.0 || ~8.6.0" }, "minimum-stability": "dev", "prefer-stable": true,