diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94312be..f278749 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,6 +55,31 @@ jobs: - uses: ramsey/composer-install@v4 - run: composer phpstan + # The one soak that runs on a runner. Preemption fails in ways a two-second test + # cannot show — a resume that loses a partial result, a fiber left parked inside + # the FFI callback — and those need thousands of slices, not hundreds. Twenty + # seconds buys ~2000 of them and keeps the job around a minute; the tool exits 2 + # (INCONCLUSIVE, a red job) rather than 0 if it was never preempted at all, so a + # runner where preemption silently stopped working cannot pass this quietly. + preemption-soak: + name: Preemption soak (PHP ${{ matrix.php }}) + runs-on: ubuntu-latest + timeout-minutes: 5 + strategy: + fail-fast: false + matrix: + php: ['8.4', '8.5'] + steps: + - uses: actions/checkout@v7 + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: ffi, pcntl + ini-values: ffi.enable=1, zend.assertions=1, opcache.jit=off + coverage: none + - uses: ramsey/composer-install@v4 + - run: php tools/soak-preemption.php --seconds=20 + # Coding standards are deliberately not a CI job. php-cs-fixer is a development # tool here: `composer cs:fix` is run locally before proposing a change, so the # style is already correct by the time anything reaches CI. Checking it again on diff --git a/AGENTS.md b/AGENTS.md index 0349c2e..67392f2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -283,9 +283,9 @@ composer cs:check # the same, without writing composer phpstan # level max, must be clean ``` -CI runs **`tests` and `static-analysis` only**, both across PHP 8.4 and 8.5. 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.** +CI runs **`tests`, `static-analysis` and the bounded `preemption-soak`**, all across PHP 8.4 and 8.5. +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.** ### A segfault is an engine-level bug, never a flaky test @@ -323,6 +323,7 @@ Not part of `composer test` — these run for a long time and are run deliberate php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-memory-flatness.php php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-no-leftover-children.php php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-arena-watermark.php +php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-preemption.php --seconds=30 ``` | Tool | Asserts | Exit codes | @@ -330,11 +331,20 @@ php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-arena-watermark.php | `tools/soak-memory-flatness.php` | RSS and `memory_get_usage(true)` stay flat over sustained spawn/park/resume cycles; a monotonic climb or growth past the tolerance fails | 0 flat, 1 climbing, 2 inconclusive | | `tools/soak-no-leftover-children.php` | no live child and no zombie survives a run | 0 clean, 1 leftovers, 2 inconclusive | | `tools/soak-arena-watermark.php` | the arena watermark **plateaus** under a steady state, process memory stays flat, and no child survives. Leak-until-teardown is the design, so the criterion is a plateau, not zero growth | 0 plateau, 1 climbing or a leftover child, 2 inconclusive | +| `tools/soak-preemption.php` | a continuous preemptive run of call-free burners, parkers and socket-pair IO: every burner's arithmetic matches the uninterrupted reference, memory stays flat, every coroutine finishes and none is left parked in the interrupt callback, and the process reaches its own verdict instead of a fatal | 0 correct and flat, 1 a check failed, 2 inconclusive — including a run that was never preempted, which measured a cooperative workload | Every one of them can produce its own failure on demand (`--inject-leak`, `--self-test`). Use that after changing the detection logic: a detector nobody has seen fail is a detector nobody knows works. `soak-arena-watermark.php --self-test` rewrites a shared string property every round, which is the -substrate's documented per-write arena cost, and must come back FAIL. +substrate's documented per-write arena cost, and must come back FAIL. `soak-preemption.php +--self-test` corrupts one burner's sum by a single unit — the smallest wrong answer a lost resume +could produce — and `--inject-leak` retains a block per round; both must come back FAIL. + +**The preemption soak is the exception to "CI runs tests and static-analysis only".** It runs there, +20 seconds per minor, because its subject is the one thing a two-second test cannot show: the suite's +longest continuous preemptive run is a few hundred slices, and a resume that loses a partial result +or a fiber left in the FFI callback is a defect that only surfaces over thousands. Keep it bounded — +a soak job that grows into minutes is a soak job somebody will delete. ## Repository map @@ -358,7 +368,8 @@ src/Parallel/Protocol/ Tag, TaggedRecord, Opcode, ControlRecord — the valu src/Exception/ the catchable failures, each naming its remedy tests/Functional/*.phpt the suite, one behaviour per file tests/Support/ fakes for the unit-shaped tests -tools/ soak tooling (memory flatness, process hygiene, arena watermark) +tools/ soak tooling (memory flatness, process hygiene, arena watermark, + preemption under a long continuous run) spikes/ the preemption experiments and their verdicts; not run by composer test ``` diff --git a/README.md b/README.md index 056f960..dd64ebb 100644 --- a/README.md +++ b/README.md @@ -528,8 +528,8 @@ composer phpstan # level max composer cs:fix # PER-CS2.0, a local step ``` -Coding standards are deliberately **not** a CI job — CI runs `tests` and `static-analysis` across -PHP 8.4 and 8.5. A segfault is an engine-level bug, never a flaky test: capture the command, the PHP +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 version and a minimal reproducer instead of retrying. Contributor rules — the engine contracts, the shared-memory disciplines, the preemption obligations @@ -543,6 +543,7 @@ Long-running checks, run deliberately, not part of `composer test`: php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-memory-flatness.php php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-no-leftover-children.php php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-arena-watermark.php +php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-preemption.php --seconds=30 ``` | Tool | Asserts | Exit codes | @@ -550,10 +551,18 @@ php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-arena-watermark.php | `soak-memory-flatness.php` | RSS and `memory_get_usage(true)` stay flat over sustained spawn/park/resume cycles; a monotonic climb, or growth past `--tolerance`, fails | 0 flat, 1 climbing, 2 inconclusive | | `soak-no-leftover-children.php` | no live child and no zombie survives a run | 0 clean, 1 leftovers, 2 inconclusive | | `soak-arena-watermark.php` | the arena watermark **plateaus** under a steady-state parallel workload, process memory stays flat, and no child survives. The arena is a bump allocator with no free list, so the criterion is a plateau and not zero growth | 0 plateau, 1 climbing or a leftover child, 2 inconclusive | +| `soak-preemption.php` | a `--seconds=N` preemptive run of call-free burners, parkers and socket-pair IO stays correct and flat: every burner's arithmetic matches the uninterrupted reference, memory is flat, every coroutine finishes with none left parked in the interrupt callback, and the process reaches its own verdict rather than a fatal | 0 correct and flat, 1 a check failed, 2 inconclusive (including "never preempted") | Each tool can produce its own failure on demand — `--inject-leak` and `--self-test` — so the detector itself is testable. `soak-arena-watermark.php --self-test` rewrites a shared string property every round, which costs an arena block per write by design, and must come back FAIL. +`soak-preemption.php --self-test` corrupts one burner's sum by a single unit and must fail the +arithmetic check; `--inject-leak` retains a block per round and must fail the memory check. + +`soak-preemption.php` is the only check in CI besides the suite and PHPStan: a 20-second run on each +minor, because the failures preemption is prone to — a resume that loses a partial result, a fiber +left parked in the FFI callback — need a long continuous run to appear at all, and the tests only +ever preempt for a second or two. ## License diff --git a/tests/Functional/testAWorkerKilledInsideACriticalSectionReportsTheRecoveredLock.phpt b/tests/Functional/testAWorkerKilledInsideACriticalSectionReportsTheRecoveredLock.phpt new file mode 100644 index 0000000..cf55923 --- /dev/null +++ b/tests/Functional/testAWorkerKilledInsideACriticalSectionReportsTheRecoveredLock.phpt @@ -0,0 +1,95 @@ +--TEST-- +A worker killed inside an arena critical section is reported as a recovered lock, not just a signal +--INI-- +ffi.enable=1 +opcache.jit=off +error_reporting=E_ALL & ~E_DEPRECATED +--FILE-- +publishTask($hold); + +$runtime->run(static function (TaskRuntime $self) use ($hold, $runtime): void { + parallelDeadline(20.0, 'the waiter on a slot that can never complete'); + + // Diagnostics are read off the concrete runtime, not the task surface — arena() and + // supervisor() are deliberately absent from TaskRuntime (see the surface guard test). + $arena = $runtime->arena(); + + if ($arena === null) { + throw new RuntimeException('this runtime mapped no arena'); + } + + $handle = $self->spawnParallel($hold, 0); + + $raw = $arena->arena(); + $mutex = resultSlotTableMutex($arena); + + // Wait for the worker to be genuinely inside the critical section before killing it. `tryLock` + // never blocks, so this poll cannot wedge the parent on a mutex a live worker holds — and a lock + // it does take is handed straight back. Once the poll reports "busy", the parent must not touch + // the mutex again: the next taker has to be the supervisor's own refresh(), whose recovery is + // the thing under test. + $held = parallelWaitFor(static function () use ($raw, $mutex): bool { + if ($raw->tryLockMutexAt($mutex)) { + $raw->unlockMutexAt($mutex); + + return false; + } + + return true; + }, 10.0); + + echo 'the worker holds the result-slot lock: ', $held ? 'yes' : 'no', PHP_EOL; + + $worker = $runtime->supervisor()?->worker(0); + $worker?->signal(SIGKILL); + + // Bounded, and outside the scheduler on purpose: awaiting the handle before the process is + // actually gone would park the parent on a lock its owner is still alive to hold. + $gone = parallelWaitFor(static fn(): bool => $worker?->isAlive() !== true, 10.0); + + echo 'the worker is gone before the parent reads a slot: ', $gone ? 'yes' : 'no', PHP_EOL; + + try { + $handle->await(); + + echo 'the await returned, which it must not', PHP_EOL; + } catch (WorkerCrashedException $crash) { + echo $crash->getMessage(), PHP_EOL; + } +}); + +echo 'children left: ', parallelChildrenLeft(), PHP_EOL; +?> +--EXPECT-- +the worker holds the result-slot lock: yes +the worker is gone before the parent reads a slot: yes +worker #0 died: it died holding an arena lock (EOWNERDEAD); the lock was recovered, but whatever it was writing is not an answer; 1 result slot(s) can never complete: #0 +children left: none diff --git a/tests/Support/shared.php b/tests/Support/shared.php index 6d623ee..6163f55 100644 --- a/tests/Support/shared.php +++ b/tests/Support/shared.php @@ -26,6 +26,7 @@ namespace Lisachenko\NativePhpCoroutines\Tests\Support; use Lisachenko\NativePhpCoroutines\Coroutine; +use Lisachenko\NativePhpCoroutines\Parallel\SharedArena; use Lisachenko\NativePhpCoroutines\Parallel\Task; use Lisachenko\NativePhpCoroutines\TaskRuntime; @@ -359,3 +360,68 @@ public function run(TaskRuntime $runtime): mixed return 0; } } + +/** + * The address of the result-slot table's own dedicated mutex. + * + * A stripe lock is the wrong lock to die on if the point is to watch the *supervisor* recover one: + * nothing the parent does while burying a worker takes a stripe, and stripe recovery is not tracked + * by anything {@see \Lisachenko\NativePhpCoroutines\Parallel\SharedArena::lockRecovered()} can + * consult. The lock the supervisor really depends on is the result-slot table's, which every + * `refresh()` takes — and which is exactly the lock a worker dying mid-`settle()` would hand on. + * + * The substrate documents the table header as `capacity | next slot | mutex address | reserved`, so + * the mutex address is the third word. Reading it here rather than adding an accessor to the runtime + * keeps a test-only need out of production; the containment check turns a future layout change into + * a named failure instead of a lock taken on somebody else's bytes. + */ +function resultSlotTableMutex(SharedArena $arena): int +{ + $raw = $arena->arena(); + $address = $raw->readWord($arena->slotTable()->address() + 2 * 8); + + if (!$raw->contains($address, 8)) { + throw new \LogicException( + 'the result-slot table header no longer keeps its mutex address in the third word; ' + . 'this helper is reading the substrate layout and has to follow it', + ); + } + + return $address; +} + +/** + * Takes the result-slot table's lock and never gives it back, so the supervisor recovers it. + * + * The worker is meant to be SIGKILLed while inside this critical section. Its death makes the very + * lock the parent's `refresh()` takes `EOWNERDEAD`, which is the state + * {@see \Lisachenko\NativePhpCoroutines\Parallel\WorkerSupervisor} turns into a crash that says the + * lock was recovered rather than one that only names the signal. + * + * A bounded spin, not a park: the process has to still be holding the mutex when it dies. + */ +final class HoldResultSlotLockTask implements Task +{ + public function run(TaskRuntime $runtime): mixed + { + // A deliberate downcast, as in HoldArenaLockTask: taking a raw lock in order to die holding + // it is machinery the task surface intentionally does not carry. + $arena = $runtime instanceof \Lisachenko\NativePhpCoroutines\Runtime ? $runtime->arena() : null; + + if ($arena === null) { + throw new \LogicException('this worker has no arena'); + } + + $arena->arena()->lockMutexAt(resultSlotTableMutex($arena)); + + // Never unlocked. Nothing else may run in this worker either — every result-slot operation + // would take the lock this fiber is already holding. + $deadline = microtime(true) + 30.0; + + while (microtime(true) < $deadline) { + usleep(5_000); + } + + return 0; + } +} diff --git a/tools/soak-preemption.php b/tools/soak-preemption.php new file mode 100644 index 0000000..080068a --- /dev/null +++ b/tools/soak-preemption.php @@ -0,0 +1,574 @@ + + * + * This source file is subject to the license that is bundled + * with this source code in the file LICENSE. + */ + +declare(strict_types=1); + +/** + * Preemption soak: does a long, busy, preemptive run stay correct and flat? + * + * php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-preemption.php + * php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-preemption.php --self-test + * php8.4 -d ffi.enable=1 -d opcache.jit=off tools/soak-preemption.php --inject-leak + * + * Preemption is the one part of this runtime that suspends a fiber from *inside an FFI callback*, + * on a signal the program never asked for, at an instruction the coroutine did not choose. Every + * test in the suite exercises that for a second or two. The failures it is prone to are the ones a + * second or two cannot show: + * + * - **a lost or duplicated partial result** — a resume that returns to the wrong place shows up as + * arithmetic that is subtly wrong, not as a crash. So the burners here are call-free arithmetic + * loops whose results are compared, every round, against the same computation run uninterrupted; + * - **a fiber that is preempted and never drained** — the scheduler holds a strong reference to + * every preempted coroutine, and one that is dropped is a fatal error at request shutdown, which + * is why the run counts what it spawned against what finished and drains the callback at the end; + * - **a slow climb** — one wait node, timer entry or coroutine retained per slice, invisible until + * an hour in. Same two metrics the other soaks watch, same warmup-then-trend verdict. + * + * The workload is a mix on purpose: call-free burners (the hard case for preemption — nothing in + * them ever reaches a cooperative suspension point), parkers on a rendezvous channel and on the + * timer heap, and real IO ping-ponging through the poller over socket pairs. A runnable coroutine + * keeps the scheduler out of its idle turn, so the IO wakeups land at the tail of each round rather + * than interleaved with the burning — that is the documented scheduler property, not a defect, and + * it still puts every descriptor through `stream_select()` under a live slice timer. + * + * # Why the verdict is a trend and not a threshold + * + * Identical to `soak-memory-flatness.php`, deliberately: a warmup prefix is dropped, and a metric + * fails either by climbing in *every* measured round or by ending more than `--tolerance` bytes + * above where it started. + * + * `--self-test` corrupts one burner's sum by one, which must FAIL the arithmetic check. + * `--inject-leak` retains a block per round, which must FAIL the memory check. A detector nobody + * has seen fail is a detector nobody knows works. + * + * Exit codes: 0 correct and flat, 1 a check failed, 2 the soak could not run (or never preempted, + * which measures nothing). + */ + +namespace Lisachenko\NativePhpCoroutines\Tools\Preemption; + +use Lisachenko\NativePhpCoroutines\Channel; +use Lisachenko\NativePhpCoroutines\Coroutine; +use Lisachenko\NativePhpCoroutines\Io; +use Lisachenko\NativePhpCoroutines\Preemption\Preemptor; +use Lisachenko\NativePhpCoroutines\Runtime; +use Lisachenko\NativePhpCoroutines\Scheduler; +use Lisachenko\NativePhpCoroutines\Sync\WaitGroup; +use Lisachenko\NativePhpCoroutines\TaskRuntime; + +require dirname(__DIR__) . '/vendor/autoload.php'; + +/** + * @return array{ + * seconds: float, burners: int, parkers: int, ioPairs: int, iterations: int, warmup: int, + * tolerance: int, slice: float, injectLeak: bool, selfTest: bool, + * } + */ +function options(): array +{ + $parsed = getopt('', [ + 'seconds:', + 'burners:', + 'parkers:', + 'io-pairs:', + 'iterations:', + 'warmup:', + 'tolerance:', + 'slice:', + 'inject-leak', + 'self-test', + 'help', + ]) ?: []; + + if (array_key_exists('help', $parsed)) { + echo 'usage: soak-preemption.php [--seconds=30] [--burners=8] [--parkers=8] [--io-pairs=4] ', + '[--iterations=3000000] [--warmup=] [--tolerance=1048576] ', + '[--slice=0.01] [--inject-leak] [--self-test]', PHP_EOL; + + exit(0); + } + + return [ + 'seconds' => max(1.0, (float) ($parsed['seconds'] ?? 30)), + 'burners' => max(1, (int) ($parsed['burners'] ?? 8)), + 'parkers' => max(0, (int) ($parsed['parkers'] ?? 8)), + 'ioPairs' => max(0, (int) ($parsed['io-pairs'] ?? 4)), + // Sized so a round is a few hundred milliseconds: long enough that every burner is sliced + // several times, short enough that a 30 s run is a readable number of rounds. + 'iterations' => max(1, (int) ($parsed['iterations'] ?? 3_000_000)), + // Resolved against the round count once the run is over: rounds are timed, not counted up + // front. -1 means "a quarter of them". + 'warmup' => isset($parsed['warmup']) ? max(0, (int) $parsed['warmup']) : -1, + 'tolerance' => max(0, (int) ($parsed['tolerance'] ?? 1024 * 1024)), + 'slice' => max(0.001, (float) ($parsed['slice'] ?? Preemptor::DEFAULT_SLICE_SECONDS)), + 'injectLeak' => array_key_exists('inject-leak', $parsed), + 'selfTest' => array_key_exists('self-test', $parsed), + ]; +} + +/** + * The burner: two interdependent accumulators, no call of any kind inside the loop. + * + * Both the reference and the coroutine run *this* function, so the comparison cannot drift apart + * the day one of them is edited. Being call-free is the point — such a loop never reaches a + * cooperative suspension point, so the only thing that can interrupt it is the slice timer, and the + * only thing that can corrupt the answer is preemption resuming it wrongly. + * + * @return array{int, int} The sum and the rolling hash. + */ +function burn(int $seed, int $iterations): array +{ + $sum = 0; + $rolling = 1; + + for ($index = 0; $index < $iterations; $index++) { + $sum += ($index + $seed) % 7; + $rolling = ($rolling * 31 + $index + $seed) % 1_000_003; + } + + return [$sum, $rolling]; +} + +/** + * Whether the run got as far as announcing its own verdict. + * + * A flag rather than a bare boolean because the shutdown guard has to read it *after* the run has + * set it, and an object property carries that across without a by-reference capture. + */ +final class Verdict +{ + public bool $reached = false; +} + +/** Resident set size in bytes, or null where `/proc/self/statm` is not readable. */ +function residentSetSize(): ?int +{ + $statm = @file_get_contents('/proc/self/statm'); + if (!is_string($statm)) { + return null; + } + + $fields = preg_split('/\s+/', trim($statm)) ?: []; + if (!isset($fields[1])) { + return null; + } + + $pageSize = 4096; + if (function_exists('posix_sysconf') && defined('POSIX_SC_PAGESIZE')) { + $reported = posix_sysconf(POSIX_SC_PAGESIZE); + if ($reported > 0) { + $pageSize = $reported; + } + } + + return ((int) $fields[1]) * $pageSize; +} + +/** + * The verdict for one metric, in the shape the other soaks report. + * + * @param list $samples The measured rounds only; warmup is already dropped. + * @return array{ok: bool, reason: string} + */ +function trendVerdict(array $samples, int $tolerance): array +{ + $first = $samples[0]; + $last = $samples[count($samples) - 1]; + $net = $last - $first; + + $monotonic = true; + for ($index = 1; $index < count($samples); ++$index) { + if ($samples[$index] <= $samples[$index - 1]) { + $monotonic = false; + + break; + } + } + + if ($monotonic) { + return ['ok' => false, 'reason' => sprintf('climbs in every measured round (+%s net)', bytes($net))]; + } + + if ($net > $tolerance) { + return [ + 'ok' => false, + 'reason' => sprintf('grew %s over the run, above the %s tolerance', bytes($net), bytes($tolerance)), + ]; + } + + return ['ok' => true, 'reason' => sprintf('net %s%s over the run', $net >= 0 ? '+' : '-', bytes(abs($net)))]; +} + +function bytes(int $value): string +{ + return sprintf('%.1f KiB', $value / 1024); +} + +$options = options(); + +if (!function_exists('pcntl_signal')) { + echo 'SOAK preemption: INCONCLUSIVE — ext-pcntl is required to receive the slice timer\'s SIGALRM', PHP_EOL; + + exit(2); +} + +/** + * The no-fatal check, and it has to be a shutdown function to be one. + * + * A preempt-suspended fiber that reaches request shutdown still parked inside the interrupt + * callback is `Throwing from FFI callbacks is not allowed` — a fatal that no catch block sees and + * that would otherwise end this process quietly, with the last round's line as the final output. So + * the run announces its own verdict, and anything that ends the process before then says so here. + */ +$verdict = new Verdict(); + +register_shutdown_function(static function () use ($verdict): void { + if ($verdict->reached) { + return; + } + + echo PHP_EOL, 'SOAK preemption: FAIL — the process ended before the verdict: a fatal error, or a ', + 'fiber left parked in the interrupt callback', PHP_EOL; + + exit(1); +}); + +/** @var list $sockets Kept open for the whole run; a round reuses them rather than churning fds. */ +$sockets = []; + +for ($pair = 0; $pair < $options['ioPairs']; ++$pair) { + $created = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, 0); + + if ($created === false) { + echo 'SOAK preemption: INCONCLUSIVE — stream_socket_pair() failed, so there is no IO to soak', PHP_EOL; + + $verdict->reached = true; + + exit(2); + } + + stream_set_blocking($created[0], false); + stream_set_blocking($created[1], false); + + $sockets[] = $created[0]; + $sockets[] = $created[1]; +} + +// One reference per burner seed, computed here in ordinary straight-line code that nothing +// interrupts. Every round compares against it, so a wrong answer is caught in the round it happens +// in rather than at the end of the run. +/** @var list $reference */ +$reference = []; + +for ($seed = 0; $seed < $options['burners']; ++$seed) { + $reference[] = burn($seed, $options['iterations']); +} + +echo 'PHP ', PHP_VERSION, ' — preemptive soak for ', sprintf('%.0fs', $options['seconds']), ': ', +$options['burners'], ' burners of ', $options['iterations'], ' iterations, ', $options['parkers'], +' parkers, ', $options['ioPairs'], ' IO pairs per round, ', sprintf('%.0f ms', $options['slice'] * 1000), +' slice', $options['selfTest'] ? ' (SELF-TEST: one burner is corrupted, this must FAIL)' : '', +$options['injectLeak'] ? ' (INJECT-LEAK: a block is retained per round, this must FAIL)' : '', +PHP_EOL, PHP_EOL; + +/** @var list $allocated */ +$allocated = []; +/** @var list $resident */ +$resident = []; + +$spawned = 0; +$finished = 0; +$mismatches = 0; +$checks = 0; +$rounds = 0; +$elapsed = 0.0; + +/** + * Retained deliberately by `--inject-leak`, exactly as in `soak-memory-flatness.php`. + * + * @var list $leaked + */ +$leaked = []; + +$runtime = new Runtime(preemptive: true, slice: $options['slice']); + +$runtime->run(static function (TaskRuntime $self) use ( + $options, + $reference, + $sockets, + &$allocated, + &$resident, + &$spawned, + &$finished, + &$mismatches, + &$checks, + &$rounds, + &$elapsed, + &$leaked, +): void { + $scheduler = $self->scheduler(); + $preemptor = $self->preemptor(); + $started = microtime(true); + $previous = 0; + + while (microtime(true) - $started < $options['seconds']) { + $group = new WaitGroup($scheduler); + $rendezvous = new Channel($scheduler); + $roundChecks = 0; + $roundWrong = 0; + + for ($seed = 0; $seed < $options['burners']; ++$seed) { + $group->add(); + ++$spawned; + + Coroutine::spawn(static function () use ( + $seed, + $options, + $reference, + $group, + &$finished, + &$roundChecks, + &$roundWrong, + ): void { + try { + [$sum, $rolling] = burn($seed, $options['iterations']); + + // The corruption --self-test injects: the arithmetic check has to be able to + // see a single wrong unit, or it is not checking anything. + if ($options['selfTest'] && $seed === 0) { + ++$sum; + } + + ++$roundChecks; + + if ([$sum, $rolling] !== $reference[$seed]) { + ++$roundWrong; + } + } finally { + ++$finished; + $group->done(); + } + }); + } + + // Parkers: half of them park on the timer heap and then hand a value over a rendezvous + // channel, one consumer takes exactly as many as were sent. Both wait queues are exercised, + // and the count is exact so nothing can park for the rest of the run. + if ($options['parkers'] > 0) { + $group->add(); + ++$spawned; + + Coroutine::spawn(static function () use ($rendezvous, $options, $group, &$finished): void { + try { + for ($taken = 0; $taken < $options['parkers']; ++$taken) { + $rendezvous->recv(); + } + } finally { + ++$finished; + $group->done(); + } + }); + + for ($parker = 0; $parker < $options['parkers']; ++$parker) { + $group->add(); + ++$spawned; + + Coroutine::spawn(static function () use ($rendezvous, $parker, $group, &$finished): void { + try { + Coroutine::sleep(0.001); + Coroutine::yield(); + $rendezvous->send($parker); + } finally { + ++$finished; + $group->done(); + } + }); + } + } + + // Real IO: a four-byte round trip per pair, every byte accounted for, so neither end can + // park on a readiness that never comes. + for ($pair = 0; $pair < $options['ioPairs']; ++$pair) { + $left = $sockets[$pair * 2]; + $right = $sockets[$pair * 2 + 1]; + + $group->add(); + ++$spawned; + + Coroutine::spawn(static function () use ($right, $group, &$finished): void { + try { + Io::awaitReadable($right); + fread($right, 4); + Io::awaitWritable($right); + fwrite($right, 'pong'); + } finally { + ++$finished; + $group->done(); + } + }); + + $group->add(); + ++$spawned; + + Coroutine::spawn(static function () use ($left, $group, &$finished): void { + try { + Io::awaitWritable($left); + fwrite($left, 'ping'); + Io::awaitReadable($left); + fread($left, 4); + } finally { + ++$finished; + $group->done(); + } + }); + } + + $group->wait(); + + if ($options['injectLeak']) { + $leaked[] = str_repeat('leak', 256 * 1024); + } + + // A leak must survive collection to be a leak; a cycle the GC has not visited yet is not. + gc_collect_cycles(); + + $checks += $roundChecks; + $mismatches += $roundWrong; + ++$rounds; + + $allocated[] = memory_get_usage(true); + + $rss = residentSetSize(); + if ($rss !== null) { + $resident[] = $rss; + } + + $total = $preemptor?->preemptions() ?? 0; + $elapsed = microtime(true) - $started; + + printf( + 'round %3d elapsed %5.1fs preemptions %6d (+%4d) allocated %10s rss %10s arithmetic %s%s', + $rounds, + $elapsed, + $total, + $total - $previous, + bytes($allocated[count($allocated) - 1]), + $rss === null ? 'n/a' : bytes($rss), + $roundWrong === 0 ? 'ok' : sprintf('WRONG x%d', $roundWrong), + PHP_EOL, + ); + + $previous = $total; + } +}); + +foreach ($sockets as $socket) { + fclose($socket); +} + +$preemptions = $runtime->preemptor()?->preemptions() ?? 0; +$scheduler = $runtime->scheduler(); + +// Nothing should be left parked inside the interrupt callback: `run()` drains what it discards. The +// count is reported rather than assumed, because a fiber still in there at request shutdown is a +// fatal error, and "none left" is the only answer that means the drain worked. +$drained = $scheduler instanceof Scheduler ? $scheduler->drainPreempted() : 0; + +$warmup = $options['warmup'] >= 0 ? $options['warmup'] : intdiv($rounds, 4); +$warmup = max(1, min($warmup, $rounds - 3)); + +$measured = ['allocated' => array_values(array_slice($allocated, $warmup))]; + +if ($resident !== []) { + $measured['rss'] = array_values(array_slice($resident, $warmup)); +} + +echo PHP_EOL; + +if ($rounds < 4 || $measured['allocated'] === []) { + printf( + 'SOAK preemption: INCONCLUSIVE — %d round(s) in %.1fs is not a trend; raise --seconds or ' . + 'lower --iterations%s', + $rounds, + $elapsed, + PHP_EOL, + ); + + $verdict->reached = true; + + exit(2); +} + +if ($preemptions === 0) { + printf( + 'SOAK preemption: INCONCLUSIVE — nothing was ever preempted in %.1fs, so this run measured ' . + 'a cooperative workload%s', + $elapsed, + PHP_EOL, + ); + + $verdict->reached = true; + + exit(2); +} + +printf( + 'preemption %s — %d suspensions over %.1fs of continuous run (%.0f/s), first %d round(s) dropped as warmup%s', + 'observed', + $preemptions, + $elapsed, + $preemptions / max($elapsed, 0.001), + $warmup, + PHP_EOL, +); + +printf( + 'arithmetic %s — %d burner results against the uninterrupted reference, %d wrong%s', + $mismatches === 0 ? 'correct' : 'CORRUPTED', + $checks, + $mismatches, + PHP_EOL, +); + +$failed = $mismatches !== 0; + +foreach ($measured as $metric => $samples) { + $trend = trendVerdict($samples, $options['tolerance']); + + printf('%-10s %s — %s%s', $metric, $trend['ok'] ? 'flat' : 'CLIMBING', $trend['reason'], PHP_EOL); + + $failed = $failed || !$trend['ok']; +} + +$fibersOk = $spawned === $finished && $drained === 0; + +printf( + 'fibers %s — %d spawned, %d finished, %d still parked in the interrupt callback%s', + $fibersOk ? 'clean' : 'LEAKED', + $spawned, + $finished, + $drained, + PHP_EOL, +); + +$failed = $failed || !$fibersOk; + +$disarmed = $runtime->preemptor()?->isArmed() === false; + +printf('timer %s after the run%s', $disarmed ? 'disarmed' : 'STILL ARMED', PHP_EOL); + +$failed = $failed || !$disarmed; + +echo PHP_EOL, 'SOAK preemption: ', $failed ? 'FAIL' : 'PASS', PHP_EOL; + +$verdict->reached = true; + +exit($failed ? 1 : 0);