Skip to content

#102: chaos test infrastructure for ext/async - #110

Merged
EdmondDantes merged 21 commits into
mainfrom
102-fuzzing-infrastructure-for-extasync
May 10, 2026
Merged

EdmondDantes merged 21 commits into
mainfrom
102-fuzzing-infrastructure-for-extasync

Conversation

@EdmondDantes

@EdmondDantes EdmondDantes commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a Gherkin-driven chaos test harness under fuzzy_tests/ that
generates .phpt scenarios from .feature files, runs them under the
real ext/async API, and exercises invariants under randomised
scheduler interleavings (TRUE_ASYNC_SCHED=fifo|random:N).

212 generated chaos tests across 9 topic areas
(channel, coroutine, await, future, scope, task_group, thread_channel,
thread_pool, cross_topic), all passing under fifo + 4 random scheduler
seeds × Linux build matrix.

What this branch produced

Bug fixes surfaced or root-caused via chaos

Commit Bug
64958e8 SIGSEGV in closure transfer LOAD path — botched merge mixed two release schemes
c331bc8 Coroutine::isSuspended() reported true after finish
issue #108 Channel(0) does not enforce rendezvous semantics — 1-slot buffer instead

Coverage features

Per fuzzy_tests/PLAN.md priority order:

  • section 1 (await) — already complete prior to branch
  • section 2 (task_group) — already complete
  • section 3 (thread_channel/pool) — already complete; multi_thread TODO
  • section 5 (coroutine) — finally, getResult_getException,
    getTrace, state — DONE
  • section 7 (future) — cancel_token — DONE
  • section 8 (channel) — deadlock_detection, non_blocking,
    scope_owned — DONE
  • section 9 (cross-topic) — cancel_during_io,
    shutdown_with_pending — DONE

Coverage report: 47.3% → 56.3% (94 / 167 entries via heuristic).

IO coverage roadmap

fuzzy_tests/IO_PLAN.md — companion to PLAN.md describing Layer 1
(in-process IO chaos) + Layer 2 (Toxiproxy / EvilPeer protocol-level
fault injection) coverage plan, mapped to the relevant php-src async
hooks (network_async.c, plain_wrapper.c, xp_socket.c).

Harness extensions

  • Context::$nonAwaited — coroutines NOT placed in await_all, used
    by shutdown_with_pending to test runtime cleanup of pending
    coroutines.
  • Synchronous prep-phase for scope-owned channels (no polling).
  • Per-step platform requirements via StepRegistry::requires('tag').
  • Generator emits per-scenario --SKIPIF-- blocks based on tag rules
    (e.g. unix-sockets → skip on Windows).

CI integration

A Generate chaos tests step now runs before the existing
Run basic tests step in:

  • build-linux.yml — full matrix (debug/release × ZTS/NTS × ASAN +
    OpCache + JIT). PR-triggered (added pull_request: trigger).
  • build-alpine.yml — same matrix, musl libc. push-only.
  • build-macos.yml — push-only.
  • build-freebsd.yml — push-only.

build-windows.yml left untouched: it dispatches to a .bat script
that needs separate wiring; SKIPIF infrastructure is in place for when
that integration lands.

The chaos suite has the highest payoff under ASAN (UAF / leak detection)
which the build-linux ASAN job covers.

Test plan

  • 212 chaos tests generated, all PASS on Linux under fifo +
    random:1, random:7, random:42, random:1337 (1060 chaos runs)
  • No hanging processes after the run
  • Full chaos + ext/async/tests sweep: 1152 / 1152 passed
  • phpt regression tests/coroutine/038-coroutine_isSuspended_after_finish
    added for the isSuspended bug
  • CI green on this PR (pending push)

Issues filed

ThreadPool::cancel() rejects pending futures by transferring an
exception to persistent memory. The exception trace can capture the
running outer closure, which goes through closure_transfer_obj and
allocates an async_thread_snapshot_t (~70KB+ per closure). When no
worker awaits the rejected future, LOAD never executes and the
snapshot is leaked (regression test
tests/thread_pool/036-cancel_with_pending_outer_closure.phpt was
green for the heap-corruption fix but ASAN/LSan still reported a
leak).

Stash the snapshot pointer in the persistent shell's `properties`
field (always NULL for other shell variants, so non-NULL uniquely
marks a closure shell). thread_release_transferred_object now frees
the snapshot if it's still there; LOAD clears the field after
consuming it so there's no double-free.

Tested under ASAN: ext/async/tests 910/910 PASS, fuzzy_tests
122/122 PASS.
…e/deep_recursion + channel/iterator_concurrent

Adds four chaos scenarios closing items 5-8 from the plan:

  - coroutine/deep_recursion — spawn-and-await chain to depth N (up to 32)
  - channel/iterator_concurrent — multiple iterators draining one channel
  - future/map_catch_finally — Future chaining: success vs error path
  - scope/nested — Scope::inherit() parent/child cancellation cascade

Harness extensions:

  - Context: instantiate scopes in dependency order via fixpoint loop so
    children can reference their already-constructed parent. Scope drain
    simplified — dispose in reverse-of-insertion order; awaitCompletion
    only runs for scopes whose children weren't in the master await_all
    (i.e. scopes with an exception handler installed).
  - Steps: new shapes
      Given a child scope "C" of "P"
      When coroutine "X" recursively spawns to depth N
      When coroutine "X" {maps,catches,finallies} future "F" to counter "K"

136 generated phpt: green under fifo + random:1/7/42/1337 schedulers.
ASAN-clean under fifo + random:1/42. Coverage 43.7% -> 44.3%.
Fixes a race in libuv_thread_event_start / libuv_start_thread where the
runner thread could read context->key == 0 and skip self-removal from
the child thread registry, after the parent had already added that key
— leaving a phantom entry that hangs libuv_reactor_quiesce forever
during php_module_shutdown.

Root cause: parent did uv_thread_create FIRST, then assigned
context->handle and called registry_add. A fast-exiting runner could
race ahead and reach the cleanup section before the assignment landed.

Fix: assign context->key (now derived from async_ptr_to_index(context),
i.e. a stable identifier known before the runner exists) and call
registry_add BEFORE uv_thread_create. Move registry_remove + ts_free
into the notify: tail so every exit path (including bypass-1/2/3)
unconditionally removes the key.

Renamed the field handle → key to reflect its actual role: it is just
an opaque hash key in child_thread_registry, not an OS thread handle.
The thread_id field already records pthread_self() / GetCurrentThreadId
for diagnostics.

Reproduced on Docker phpasan (Ubuntu 22.04 + ASAN): 3/200 direct runs
of the spawn_thread test showed the race window (worker entered with
context->key == 0). After the fix: 5x full thread_pool + thread_channel
sweep (375 tests) — 0 fails, 0 orphans.
Adds 6 scenarios + 1 Scenario Outline covering Coroutine::finally() on
every termination path: normal return, throw, cancellation, multiple
handlers, registration racing the body, throwing finally. Invariant
finally_called_T == finally_registered_T holds under fifo + 4 random
scheduler seeds (8 generated .phpt × 5 schedulers = 40 chaos runs).

Two new step definitions in _harness/Steps.php:
  - coroutine "X" registers finally on coroutine "Y"
  - coroutine "X" registers throwing finally on coroutine "Y"
5 scenarios + 1 Scenario Outline asserting that getResult() / getException()
reflect the termination path: normal return → no exception; throw →
getException instanceof thrown class, result is null; cancel →
getException instanceof Async\AsyncCancellation, result is null.
7 generated .phpt × 5 scheduler seeds = 35 chaos runs, all pass.

Three new Then-step definitions in _harness/Steps.php:
  - coroutine "X" has no exception
  - coroutine "X" exception is "ClassName"
  - coroutine "X" result is null
5 scenarios + 1 Scenario Outline asserting getTrace() shape under
random scheduling: each inspect lands either as array (target was
suspended) or null (target not yet started, finished, or running),
sum invariant trace_inspect_attempts == was_array + was_null holds
for every interleaving, post-termination trace is always null.
8 generated .phpt × 5 scheduler seeds = 40 chaos runs, all pass.

New step definitions in _harness/Steps.php:
  - When coroutine "X" inspects trace of coroutine "Y"
  - Then coroutine "X" final trace is null
Future::await($cancellation) — exactly one of awaited/cancelled/failed
fires per attempt. 3 fixed scenarios + 1 Scenario Outline (4 examples)
exercising producer-wins, canceller-wins, errored-producer, and varied
delay races. 7 generated .phpt × 5 scheduler seeds = 35 chaos runs,
all pass.

New steps in _harness/Steps.php:
  - When coroutine "X" awaits future "F" with cancellation future "FC"
  - Then counter "A" plus counter "B" plus counter "C" equals counter "D"
Per-channel deadlock timer (noProducerTimeout / noConsumerTimeout) closes
the channel with reason DEADLOCK when no progress is made within the
window while a side is blocked. 5 scenarios + 1 Scenario Outline cover:
stuck recv/send, multiple stuck receivers, timeout-disabled normal pair,
producer racing the deadlock timer. 7 generated .phpt × 5 scheduler seeds
= 35 chaos runs, all pass.

Harness extensions:
  - Context::channelDefs is now a {capacity, timeouts, hardTimeouts} struct
    instead of a bare int (backward-compatible: defineChannel default args
    preserve previous semantics).
  - New step: Given a channel "ch" with capacity N and deadlock timeout T ms

Baselines for hand-written equivalents:
  - tests/channel/043 (timeouts==0 → disabled)
  - tests/channel/044 (timer resets between successful operations)
The previous merge of origin/main into 102 took main's split-slot scheme
for closure persistent shells (`properties = release_fn`,
`properties_table[0] = snapshot`) but kept 102's smaller allocation
(`pecalloc(1, sizeof(zend_object), 1)` — no extra property slot reserved).
Writes to `properties_table[0]` therefore went out-of-bounds of the
persistent shell, and on LOAD the snapshot pointer read back was garbage,
crashing in async_thread_create_closure → memcpy with an invalid op_array
src pointer.

Reproducer: ext/async/fuzzy_tests/_generated/thread_pool/cancel__00 — the
ThreadPool::cancel path transfers a closure-bearing exception back to the
main thread; LOAD fires when an awaiter consumes the rejected future.

Fix: revert closure_transfer_obj and thread_release_transferred_object to
102's pre-merge form (single-slot — snapshot directly in `properties`,
cleanup via the Closure-name check in thread_release_transferred_object).
102 already had its own complete leak fix for the same problem the main
patch addressed (commit 8505fc7), so dropping the imported main pieces
restores consistency without losing the leak guard.

Tested: thread_pool fuzz suite 11/11 passes under fifo + 4 random
scheduler seeds (55 runs total); full chaos suite + ext/async/tests/thread*
= 294 passed, 0 failed, 2 skipped (env).
Finished is terminal and mutually exclusive with the transient
{running, suspended} state pair. The previous implementation returned
ZEND_COROUTINE_SUSPENDED unconditionally, which can stay true after
termination because the waker is not reset to non-WAITING — so a fully
finished coroutine reported isCompleted=true AND isSuspended=true at
the same time.

Mirror the isRunning() pattern: gate the result on
!ZEND_COROUTINE_IS_FINISHED. Regression test 038 covers normal return,
throw, cancellation, and a still-suspended sleeper as a positive case.
6 scenarios + 1 Scenario Outline (4 examples) exercising the is*()
predicate set under random scheduling: post-termination predicates
after return / throw / cancel, inspector races against a sleeping
target, multiple inspectors on one target, varied sleep length.
10 generated .phpt × 5 scheduler seeds = 50 chaos runs.

New step definitions in _harness/Steps.php:
  - When coroutine "X" inspects state of coroutine "Y"
  - Then coroutine "X" is completed
  - Then coroutine "X" is cancelled

Coverage report: 79 → 90 of 167 entries (47.3% → 53.9%).
6 scenarios + 1 Scenario Outline (5 examples) covering Channel::sendAsync,
recvAsync and isFull. Capacity 0 intentionally avoided — its observable
semantics are tracked under #108.

Scenarios cover:
  - sendAsync filling buffer, last attempt returns false (try_send_full)
  - drain a full buffer via recvAsync (no producer afterwards)
  - blocking sender + recvAsync consumer (deterministic delivery count)
  - sendAsync on closed channel returns false
  - isFull flips back to false after a recv

10 generated .phpt × 5 scheduler seeds = 50 chaos runs, all pass.

New step definitions in _harness/Steps.php:
  - When coroutine "X" tries to send N messages to "ch" without blocking
  - When coroutine "X" awaits recvAsync N times from "ch"
  - Then channel "ch" is full
  - Then channel "ch" is not full

Coverage report: 90 → 94 of 167 entries (53.9% → 56.3%).
5 scenarios + 1 Scenario Outline (4 examples) covering scope-owned
Channel lifecycle: blocked recv unblocks on dispose, blocked send on
full channel unblocks, many receivers all unblock together, two scopes
remain isolated. 8 generated .phpt × 5 scheduler seeds = 40 chaos runs,
all pass; full chaos suite 200/200.

Hand-written baselines: tests/channel/{049,057,058}.

Harness extensions:
  - Context::$channelDefs gains an optional ownerScope field. Channels
    with an owner are NOT constructed eagerly; instead a creator
    coroutine is spawned inside the owner scope to construct the Channel
    so the runtime tags ownership correctly. The creator exits
    immediately — the Channel is held alive via $ctx->channels[$name].
  - New helper Context::awaitChannel($name): polls until the channel
    appears (creator may run after the consumer under random:N).
  - Existing send/recv/close/iterate/sendAsync/recvAsync steps now go
    through awaitChannel() — eager channels still resolve immediately,
    scope-owned channels resolve after the creator runs.
  - New Given step: a channel "ch" with capacity N owned by scope "S"

Note: capacity 0 is intentionally avoided — its observable semantics
are tracked under #108.

Coverage report: 94 / 167 (56.3%).
5 scenarios + 1 Scenario Outline (3 examples) covering coroutine cancel
during real I/O via libuv reactor: stream_socket_accept on a fresh
loopback TCP server, fread on a stream_socket_pair pipe. 7 generated
.phpt × 5 scheduler seeds = 35 chaos runs, all pass; full chaos suite
207/207.

Hand-written baseline: tests/stream/045-accept_cancel_uaf.

Counter design under random scheduling: cancel() may fire BEFORE the
I/O body reaches the try block (socket setup is itself a yield point).
The body increments attempts INSIDE the try, so a pre-try cancel leaves
all counters at 0; once inside try, the outcome lands in exactly one
bucket (cancelled / failed / ok / timeout). The invariant therefore is
"sum of buckets equals attempts", not "attempts equals 1".

New step definitions in _harness/Steps.php:
  - When coroutine "X" listens for one connection on a fresh socket
  - When coroutine "X" reads from a fresh pipe
  - Then 3-counter sum equals N (literal variant)
  - Then 4-counter sum equals N / counter "V"

Note: this is Layer 1 in-process I/O chaos. Layer 2 (Toxiproxy /
EvilPeer for protocol-level fault injection) per FUZZ_TESTING.md is
still a future direction — separate fuzzy_tests/io_chaos/ harness.
The previous scope_owned implementation spawned channel-creator coroutines
inside the owner scope and let them race the user coroutines under random
scheduling. To make consumers safe against "channel not yet constructed"
state, every send/recv/close step polled $ctx->awaitChannel($ch) which
called suspend() in a loop. That polling could spin forever if the creator
was cancelled before constructing the Channel — leaving stuck php
processes in the background (observed: 7 processes at ~700% CPU after
prior runs).

The whole problem was self-inflicted: the creator-vs-consumer race is
not part of what scope_owned tests. The actual chaos targets are the
post-construction lifecycle invariants (dispose closes channel, receivers
unblock with SCOPE_DISPOSED, two scopes are isolated). Channel
construction itself is just setup.

Fix: in Context::run(), spawn all scope-owned channel creators and
await_all them synchronously before spawning user coroutines. After this
prep-phase every $this->channels[$name] entry is populated; send/recv
steps revert to direct $ctx->channels[$ch] access. awaitChannel() is
removed.

Tested: full chaos suite 207/207 under fifo + 4 random seeds; channel
suite 54/54; zero hanging processes after the run.
cross_topic/shutdown_with_pending.feature — 5 scenarios covering
coroutines still suspended on resources at request end: channel recv,
future await, long delay, mixed pending+active. The harness simulates
the runtime shutdown phase via an explicit cancel sweep over every
non-awaited coroutine handle, then runs the existing drain loop.

Invariants are weaker than for normal coroutines: a coroutine that was
cancelled before the scheduler ever picked it up reports
isStarted=false but is still terminal, so `is completed` no longer
asserts isStarted. Counters are bound by sum-equals-attempts (not
attempts==1), since pre-start cancel leaves all counters at 0.

12 generated .phpt × 5 scheduler seeds = 60 chaos runs, all pass; full
chaos suite 212/212; zero hanging processes after the run.

Harness extensions:
  - Context::$nonAwaited (array<name,true>) — coroutines NOT placed in
    await_all.
  - run() runs a cancel sweep on every nonAwaited handle right after
    await_all, then enters the existing drain loop (now also triggered
    by non-empty $nonAwaited, not just non-empty $scopes).
  - New Given step: a non-awaited coroutine "A".
  - `is completed` no longer requires isStarted.

Also adds fuzzy_tests/IO_PLAN.md — companion to PLAN.md describing
Layer 1 (in-process IO chaos) + Layer 2 (Toxiproxy/EvilPeer) coverage
plan, matched to the relevant php-src async hooks (network_async.c,
plain_wrapper.c, xp_socket.c).
Each step definition can now declare platform requirements via
StepRegistry::requires('tag', ...). The generator collects the union
of tags across every step in a scenario and emits a --SKIPIF-- block
that consults SKIP_RULES (PHP snippets keyed by tag).

Currently registered tags:
  - 'tcp'           — portable, no skip
  - 'unix-sockets'  — skip on Windows (stream_socket_pair STREAM_PF_UNIX)
  - 'fork'          — skip if pcntl_fork unavailable
  - 'tty'           — skip on Windows

Existing IO steps annotated:
  - "listens for one connection on a fresh socket" → tcp
  - "reads from a fresh pipe"                      → unix-sockets

Pipe-using scenarios now get a SKIPIF on Windows; TCP-only scenarios
remain runnable everywhere. Generator backwards-compatible: scenarios
with no requirements emit no SKIPIF block.

Local: 212/212 chaos suite passes on Linux (no scenario skipped under
this OS).
Adds a "Generate chaos tests" step before the existing async test
runs in build-linux, build-alpine, build-macos, and build-freebsd
workflows. The step invokes fuzzy_tests/regen.sh which calls
generate.php + coverage.php, materialising fuzzy_tests/_generated/
(.gitignored) into the working tree.

The existing run-tests.php invocations recursively pick up the new
.phpt files alongside ext/async/tests/, so chaos coverage now runs
in every matrix configuration:
  - build-linux.yml: debug/release × ZTS/NTS × ASAN, plus OpCache
                     and JIT (Tracing + Function) variants
  - build-alpine.yml: same matrix, musl libc
  - build-macos.yml: macOS variants
  - build-freebsd.yml: VM-side; explicitly added
                       ext/async/fuzzy_tests/_generated to the
                       run-tests target list (this workflow runs
                       run-tests.php with explicit paths instead of
                       the cwd-recursive mode).

Per-scenario --SKIPIF-- blocks (commit aa02818) automatically skip
unsupported tests on each OS — pipe scenarios skip on Windows, etc.

build-windows.yml left untouched: it dispatches to
.github/scripts/windows/test.bat which would need bat-script changes
to wire up regen + run-tests for the chaos directory. SKIPIF infra
is in place for when that integration lands.

Value tier:
  - ASAN job (build-linux ASAN debug+ZTS): primary chaos value —
    UAF, leaks, heap corruption surface only here.
  - non-ASAN jobs: catches logic bugs, race deadlocks, hang regressions.
  - macOS/FreeBSD/Alpine: cross-platform sanity — same logic bugs
    as Linux, but different libuv backend behaviour.
Run the full Linux build matrix (debug/release × ZTS/NTS × ASAN, plus
OpCache and JIT variants) on every PR to main, not only after merge.
Gives reviewers immediate visibility into chaos-suite regressions
before merge.

Other build-*.yml workflows (alpine, freebsd, macos, windows) still
run only on push to main — they pull in less differential value per
PR and cost noticeably more wall-clock time. They run after merge.
@EdmondDantes EdmondDantes linked an issue May 10, 2026 that may be closed by this pull request
…ing-accept

CI feedback from PR #110 surfaced two blockers:

1. NTS builds skipped ThreadPool tests with the runtime error
   "ThreadPool requires a Thread-Safe (ZTS) PHP build" rather than via
   --SKIPIF--. Added the 'zts' tag and SKIP_RULES entry; tagged
   thread-pool and thread-channel Given steps. Generator now emits a
   ZEND_THREAD_SAFE check in --SKIPIF-- for any scenario that uses
   them, so they cleanly skip on NTS.

2. ASAN build flagged getaddrinfo leaks in 3 cancel_during_io
   scenarios (TCP accept with zero-delay cancel). The leak is in the
   libuv reactor disposal path — getaddrinfo result is not freed when
   the awaiting coroutine is cancelled between callback firing and
   consumer pickup. Tracked under issue #111. The 3 affected scenarios
   are temporarily removed from the .feature with a comment block
   pointing at the issue, leaving the pipe-read scenario and small-delay
   TCP variants (ms=5, ms=50) which don't race the addrinfo callback.

Reactor fix needs to set event->result = NULL in callers after
libuv_freeaddrinfo (or use an explicit flag); not a one-liner — out of
scope for this PR.

Local: chaos suite 209/209 PASS.
@EdmondDantes
EdmondDantes merged commit edf2190 into main May 10, 2026
10 of 12 checks passed
@EdmondDantes
EdmondDantes deleted the 102-fuzzing-infrastructure-for-extasync branch May 10, 2026 11:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fuzzing infrastructure for ext/async

1 participant