Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 16 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -323,18 +323,28 @@ 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 |
| --- | --- | --- |
| `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

Expand All @@ -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
```

Expand Down
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -543,17 +543,26 @@ 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 |
| --- | --- | --- |
| `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

Expand Down
Original file line number Diff line number Diff line change
@@ -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--
<?php

declare(strict_types=1);

use Lisachenko\NativePhpCoroutines\Exception\WorkerCrashedException;
use Lisachenko\NativePhpCoroutines\Runtime;
use Lisachenko\NativePhpCoroutines\TaskRuntime;
use Lisachenko\NativePhpCoroutines\Tests\Support\HoldResultSlotLockTask;

use function Lisachenko\NativePhpCoroutines\Tests\Support\parallelChildrenLeft;
use function Lisachenko\NativePhpCoroutines\Tests\Support\parallelDeadline;
use function Lisachenko\NativePhpCoroutines\Tests\Support\parallelWaitFor;
use function Lisachenko\NativePhpCoroutines\Tests\Support\resultSlotTableMutex;

include __DIR__ . '/../../vendor/autoload.php';
include __DIR__ . '/../Support/parallel.php';
include __DIR__ . '/../Support/shared.php';

// Recovery is the substrate's job; *reporting* it is this package's, and the report is only truthful
// if the parent has actually taken the lock the dead worker held. Killing a worker that holds a
// stripe nothing in the bury path touches proves the waiter fails — it does not exercise the
// EOWNERDEAD branch, because the supervisor never recovers anything and says "killed by signal 9".
// So the worker here dies inside the one critical section the supervisor itself enters on the way to
// the grave: the result-slot table's. Its `refresh()` inherits the mutex as EOWNERDEAD, and the
// crash the waiter receives says so.
$runtime = new Runtime(workers: 1, arenaSize: 32 << 20);

$hold = new HoldResultSlotLockTask();
$runtime->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
66 changes: 66 additions & 0 deletions tests/Support/shared.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

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