Skip to content

Async under load: bounded parks, a non-quadratic channel, and a measured fiber stack - #7

Merged
blacktrs merged 24 commits into
mainfrom
async-liveness
Jul 29, 2026
Merged

blacktrs merged 24 commits into
mainfrom
async-liveness

Conversation

@blacktrs

@blacktrs blacktrs commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Everything a cooperative runtime gets wrong only under load: a park with no deadline, a loop that spins instead of waiting, a queue that is quadratic, a crash that will not say what it was. Each item was measured or reproduced before it was fixed.

Both gates green on this head — macOS: AOT 727/727 · difftest 671 MATCH / 0 DIFF · fixpoint IR byte-identical · self-host 727/727 · MIR golden 108 · stability 5×2. Linux (run_tests.sh --gate, arm64): cold seed · 727/727 · 671/0 · fixpoint · self-host · 108 · stability 2×2.

Liveness

  • Every write park has a deadline. Every write site took the unbounded slot, so a peer that stops reading wedged the fiber, its scope and its fd forever. stream_set_timeout now sets both directions (Zend: the timeout belongs to the stream), expiry is a short write rather than an exception, and the TLS WANT_READ/WANT_WRITE loop gets an absolute deadline — it alternates directions, so a per-park budget would just wait forever twice.
  • accept(2) reads errno. Under EMFILE the connection stays queued, so a level-triggered listener stays readable: the old loop re-armed instantly and spun, starving every sibling, and the watchdog could not see it because it suspended each time round. __mc_accept_class splits park / retry-now / back off (1 ms → 50 ms, sleeping rather than re-arming: readiness carries no information there) / fatal.
  • A channel queue that is not quadratic. removeWaiter rebuilt both queues on every removal, so cancelling N waiters on one channel was O(N²) and allocated an N-sized array N times. It showed as a per-task cost that grew with the task count — 71 KiB each at 10k waiters, 111 KiB at 20k — and 40k waiters would not finish cancelling in ten minutes. Cursor queues with tombstones now, a slot on the task for O(1) removal, and no array_shift per delivery: flat 24 KiB/task at 10k, 20k and 40k.
  • fsockopen's timeout means something without a scheduler. It was accepted and documented as ignored, leaving the OS's SYN retries in charge: ~75 s for a 0.3 s request. Same non-blocking connect the async path makes, waited on by poll(2).

Fiber stacks — measured, not assumed

tools/fiber_ceiling.php spawns tasks until allocation fails and reports what ran out. Linux arm64, 40 000 concurrent tasks:

stack RSS virtual
8 MiB 6.55 GiB 313 GiB
1 MiB 0.65 GiB 39.7 GiB
512 KiB 0.65 GiB 20.1 GiB
256 KiB 0.65 GiB 10.4 GiB

Flat below 1 MiB, ten-fold above it — so 1 MiB is the new default, with MANTICORE_FIBER_STACK / Fiber::setStackSize() either way. macOS shows no such step (7410 vs 7251 MiB), so a macOS-only measurement would have shipped a ten-fold memory regression to every Linux deployment.

The ceiling that arrives first is neither column: each fiber costs two mappings (the guard page splits the VMA), so a stock vm.max_map_count of 65530 caps a process near 32 000 concurrent tasks whatever the stack size.

Along the way: mmap failure was never checked — MAP_FAILED flowed back into PHP and -1 + size got a context built on it, so exhausting address space was a SIGSEGV with nothing to read. It raises FiberError now, which is what Zend raises. Same for the context allocator. The stack pool stored bases with no length, an invariant a size knob makes false.

Diagnostics

  • A stack overflow says so. Running off the bottom of a fiber stack faults into the guard page and died as a bare SIGSEGV — SIGBUS on Darwin — pointing at whatever function touched the page. A handler on an alternate stack now prints manticore: fiber stack overflow (raise MANTICORE_FIBER_STACK), then restores the default disposition and re-raises, so the process still dies exactly as it did and any other fault passes through untouched.
  • Async\failure() names the task behind an escaped exception. A child's throwable is rethrown by whoever joined it, so it arrives with the joiner's file and line and the task that actually failed is nowhere in the trace. It cannot be put there — mutating a user's throwable is impossible and wrapping breaks catch — so the provenance rides beside it, first failure only.

Resolution, limits, harness

  • resolv.conf search / ndots. Only nameserver lines were read, so short names (db, redis — the compose and k8s norm) fell through to the blocking getaddrinfo walk in exactly the deployment async is for.
  • posix_getrlimit / posix_setrlimit, with php as the oracle — which is what makes the EMFILE path testable at all (ulimit -n on a dev box is seven figures). POSIX_RLIMIT_* carries host values, and RLIM_INFINITY is PHP_INT_MAX on Darwin but -1 on glibc.
  • A per-case deadline in the harness. A liveness bug used to hang the suite rather than fail it. timeout(1) cannot be assumed — macOS ships no coreutils — so tools/lib/limit.sh resolves once to timeout / gtimeout / a perl fork+alarm / a poll loop, all reporting 124. A hang is its own outcome, never runtime rc=124.
  • file_get_contents read every procfs and sysfs file as the empty string — it sized the buffer from ftell(SEEK_END), and /proc reports 0. Not a visible failure: it reads as "the file is empty".

Docs: docs/async.md gains "How much a task costs"; docs/superset.md and tools/docker/PROBE_RESULTS.md carry the measured numbers and the signal-struct layouts behind the guard handler.

blacktrs added 24 commits July 27, 2026 15:10
Every write site took the unbounded writable slot, so a peer that stops
reading — a zero TCP window, the reverse-slowloris — wedged the writing
fiber forever: the task never settled, its scope never closed, the fd was
never released, and nothing said why.

stream_set_timeout() is the STREAM's timeout in php, not the read's, so it
now sets $wtimeoutMs alongside $rtimeoutMs; __mc_wait_write mirrors
__mc_wait_read (writableFor, 60 s floor, $timedOut on expiry) and bounds
__mc_stream_sendv, fwrite and the raw Async\\read/write parks. Expiry is a
short write, never an exception.

The TLS WANT_READ/WANT_WRITE loop in __mc_stream_fill gets an ABSOLUTE
deadline: both directions parked unbounded and the loop can alternate
between them, so a per-park budget would let a half-record peer live
twice-forever with timed_out false.

Async\\accept stays unbounded on purpose — an idle listener is not a
stalled peer.
The accept loop re-parked on ANY failure. Out of descriptors accept(2)
fails while the pending connection STAYS QUEUED, so a level-triggered
listener stays readable: the park returns at once, accept fails again, and
the loop spins without ever suspending — starving every sibling task. It
does not even trip the watchdog (it suspends each iteration); it shows only
as an exploding wakes counter.

__mc_accept_class splits the failure four ways — park / retry now
(EINTR, ECONNABORTED, EPROTO: no readiness edge is coming for a peer that
already left) / back off (EMFILE, ENFILE, ENOBUFS, ENOMEM) / fatal — and
stream_socket_accept folds its bounded and unbounded branches into one loop
over an absolute deadline. Overload SLEEPS rather than re-arming readiness,
since readiness carries no information there.

Kept separate from __mc_sock_wouldblock and of the opposite polarity: there
an unknown errno parks, here it is fatal. socket_accept gets the immediate
retry only — php reports EMFILE and returns false, and ext/sockets leaves
the serving policy to the caller. No exception at either site: php's
documented contract is a false return, and throwing would break every
while(true){accept();} loop.
Only nameserver lines were read, so a short name had no way to be
qualified: the async resolver could not answer it and the lookup fell
through to the BLOCKING getaddrinfo walk, stalling the loop. Inside compose
and kubernetes short names are the norm — invisible on a laptop,
unavoidable in a container, in exactly the deployment async exists for.

Every parser takes TEXT (__mc_resolv_text is the only reader), so the whole
of resolv.conf handling is offline-testable — the AOT runner injects no env.
__mc_dns_candidates applies the ndots rule; __mc_resolve_async walks the
candidates and caches under the ORIGINAL name, and stops only when nobody
answered (a timeout must not be multiplied by the suffix count). resolv.conf
is parsed once per lookup, down from twice.

Two compiler bugs surfaced doing it:

- a static local inside a NAMESPACED function emitted @ns\fn__sl_x — a
  backslash in an unquoted LLVM identifier, which does not parse. Every
  static local in the tree happened to sit in a global-namespace file, so
  the whole class of function was unbuildable and nobody knew.

- USE-AFTER-FREE: a string ternary's borrowed arm got no retain.
  $out = $out === '' ? $s : ($out . ',' . $s) stored $s's buffer borrowed;
  the next iteration freed it, the allocator handed the same block back, and
  the accumulated value silently became the newest element repeated. A
  string-typed conditional is now an owned producer like a concat — arms
  normalised to +1, consumers uniform (fresh temp / owned local / no
  co-owner retain).
Semaphore and mapConcurrent were documented, but the example a reader copies
spawned per accept with no ceiling — so the first server written from it gets
unbounded concurrency and an OOM under load instead of a queue. The permit is
taken BEFORE the accept, so at the ceiling the queue stays in the kernel
backlog; it is released in the CHILD's finally, since the parent's runs once.

http_transparent stays unbounded on purpose (it exists to produce a wrk
number) and now says so. The doc also records why there is no built-in
per-scope task ceiling: spawn() is the wrong place to fail — the exception
lands in the acceptor, the one task that must survive an overload.
The first cut also taught the consumers that a string-typed conditional is
an owned producer (fresh temp / owned local / no co-owner retain). That
over-released: an arm which is not itself string-TYPED — a cell or unknown
carrier that coerces to the string — gets no retain here, so the release
side freed what nobody owned, and preg_full and socket_sendmsg read the
freed bytes.

Keep only the half that cannot corrupt: arms get their +1, consumers keep
treating the result as borrowed. Retaining without releasing leaks a string
(the concat arm already did); releasing without retaining corrupts one.
The async runtime is the largest thing here that php cannot run, and the
README did not mention it at all. docs/superset.md now catalogues the whole
surface with no oracle — concurrency, compile-time attributes, FFI, modules,
types, memory — together with the rules it lives under: hand-written expected
output, inert under Zend wherever possible, zero cost when unused, no php.ini.

docs/async.md gains what this epic actually changed (bounded writes, the
classified accept loop, search/ndots) and loses the two entries that are now
done. The fiber-stack ceiling moves into 'Not yet' as an unmeasured number
rather than an assumption.

Also fixes the difftest DIFF the new dns case introduced: it echoed a literal
BEFORE its first manticore-only call, so php produced stdout and difftest
reclassified a PHP-SKIP as a real diff.
The status wall opened with numbers that go stale the moment a case lands
(467/467, 458/0, ~228 functions, 5x2) and the install story was three lines
in the middle of it. Requirements and install now come FIRST, with the
toolchain floors, the per-OS packages and the -dev caveat that actually
bites; then a Working-with-it section, then the language surface.

Benchmarks condense from three tables to one representative slice plus the
headline numbers — bench/run.sh is the source of truth for the rest. Gate
counts are gone; the gate COMMANDS stay, which is what a reader can act on.
Limitations lose the resolved multi-object-linking entry and gain the .sig
class-export gap and blocking file I/O, both of which a user meets in
practice.
…l fix

The rcode holder sat in Dns.php, the one namespaced stdlib file, so building
it needed the sanitizeSym fix that shipped in the same commit. A compiler
generation WITHOUT that fix therefore could not build the tree at all:
bin/build died on lib/manticore_stdlib.o and only a cold seed recovered. The
stability gate found it the honest way — five self-front-end rebuilds in a
row, all dead on the same symbol.

The holder moves next to __mc_net_errno, whose idiom it copies anyway, in a
global-namespace file. The compiler fix stays — it is a real bug for user
code, and static_local_namespaced now pins it with php as the oracle (a
namespaced function, a namespaced method, and the once-only initialiser).

A self-hosting compiler must not need itself-plus-one-fix to build.
manticore_self.ll is 954k lines and was neither tracked nor ignored, so the
first git add -A after a gate run committed it.
Gate numbers in a status doc are wrong the moment a case lands — the gate
COMMANDS are what a reader can act on. In their place, the two things that
actually cost time: bin/build green says nothing about tools/selfhost.sh
(library-with-flattened-namespace vs one module), and never ship a compiler
fix together with tree code that needs it.
strcmp / strncmp / strcasecmp / strncasecmp / memcmp were the one family the
#[CType('int')] sweep missed, and they are the family where the SIGN is the
entire answer. Without the sext a negative result reads as ~4.29e9, so every
comparison says "greater" and a sort comes out reordered.

It was invisible on arm64 — Darwin and Linux both implement these in hand-
written assembly that happens to fill the whole return register. glibc on
x86_64 leaves the upper half undefined, so the Linux amd64 gate failed 8 cases
while arm64 and macOS were green:

  closure_string_abi   apple,fig,kiwi,pear -> kiwi,fig,apple,pear
  sort_usort_reduce    apple,fig,kiwi,pear -> fig,kiwi,apple,pear

Confirmed pre-existing: the same cases fail identically at 39b46f5, before any
of the array work. Seven of the eight amd64 failures clear with this.

The other 40 attribute-less binds in the file are deliberately left alone —
strlen/read/write/fread/ftell/readlink/writev return size_t / ssize_t / long
and signal() returns a pointer, so sign-extending them would be a new bug. That
audit is its own task.

With the bind fixed, the SORT_FLAG_CASE comparators go back to calling
strcasecmp directly instead of routing around it through strtolower + strcmp.

amd64 714/715 (generators_exceptions is a separate pre-existing SIGSEGV, also
reproduced at 39b46f5). macOS -k sort 11/11, -k array 106/106.
The size was a bare 8388608 in four places across three call sites, and the
pool stored bases with no length — "all one size" held only because nothing
could change it. It carries the length beside the base now, and a slot whose
length does not match the request is left alone rather than handed out.

mmap's failure was never examined: MAP_FAILED came back as -1, prelude computed
-1 + size and built a context on it, so exhausting address space (or
RLIMIT_AS, or vm.max_map_count) was a SIGSEGV with nothing to read. The
intrinsic returns 0 on failure — never a valid base, so it needs no second
channel — and Fiber::start() raises FiberError, which is what Zend raises when
it cannot allocate a fiber. A failed mprotect on the guard page now fails the
allocation too: a stack without its guard turns an overflow into heap
corruption.
A liveness bug hung the runner instead of failing it — an unbounded write park
never came back, so the suite reported nothing at all rather than one red case.
Both harnesses now bound every compile and every run.

The limit cannot be `timeout 60` : macOS ships no coreutils, so this dev host
has neither timeout nor gtimeout and that spelling would be command-not-found
on all 720 cases — a fake full-suite regression. tools/lib/limit.sh resolves
once to timeout / gtimeout / a perl fork+alarm / a poll loop, and every path
reports GNU timeout's 124 so callers test one number. MC_TIMEOUT_KIND forces a
path, which is the only way to exercise the ones a given host would not pick.

A hang is reported as TIMEOUT, never as `runtime rc=124`: a case that
legitimately exits non-zero already reads that way, and a wrong exit status and
a hang are not the same finding. The summary line is untouched, since
selfhost_fixpoint.sh matches `failed: 0` in it.

In difftest the php side is bounded too, and its timeout is tested BEFORE the
"php produced no stdout" branch — otherwise a hanging reference would be
counted as PHP-SKIP, quietly shrinking the parity denominator.
8 MiB per fiber was never measured, only assumed. tools/fiber_ceiling.php spawns
tasks until allocation fails and reports what ran out; on Linux arm64 at 40 000
concurrent tasks:

  8 MiB   VmRSS 6.55 GiB   VA 313 GiB
  1 MiB   VmRSS 0.65 GiB   VA  39 GiB
  512 KiB VmRSS 0.65 GiB   VA  20 GiB
  256 KiB VmRSS 0.65 GiB   VA  10 GiB

Flat below 1 MiB, 10x worse above it — so 1 MiB is the knee and the new default.
Below it only address space is saved; above it nothing is bought but resident
memory. Darwin shows no such step (7410 vs 7251 MiB at 40 000), so a macOS-only
measurement would have kept 8 MiB and shipped a ten-fold memory regression to
every Linux deployment.

Two mappings per fiber, not one — mprotect splits the VMA for the guard page —
so a stock Linux vm.max_map_count of 65530 caps a process at ~32 000 concurrent
tasks whatever the stack size. That is the real ceiling and it is now written
down.

MANTICORE_FIBER_STACK sets it (Zend's equivalent is the fiber.stack_size ini,
which we have no mechanism for), Fiber::setStackSize() does the same from code —
which is also the only way to test it, since the AOT runner injects no env.
Sizes are clamped to a 16 KiB multiple above the guard page, and mixing sizes in
one process is safe because the pool matches on length.

file_get_contents was reading procfs as the empty string: it sized the buffer
from ftell(SEEK_END), and every /proc and /sys file reports 0. That is not a
visible failure — it reads as "the file is empty" — and it is why the first
Linux measurement could report no VmRSS at all.
The accept-backoff that shipped earlier in this epic had no end-to-end test:
`ulimit -n` on a dev box is seven figures and there was no setrlimit(2) binding,
so async_accept_errno could only exercise the classifier in isolation.

posix_getrlimit/posix_setrlimit are php 8.5 functions, so php is the oracle for
all of it. The resource numbers are host-exposed like FNM_*, not invented like
LOCK_*: MEMLOCK 6/8, NPROC 7/6, NOFILE 8/7, AS 5/9 for Darwin/Linux, verified
against each host's own php. So is RLIM_INFINITY — PHP_INT_MAX on Darwin but -1
on glibc, which is the one value that cannot be guessed, and assuming
PHP_INT_MAX everywhere was wrong on Linux while every macOS test stayed green.
It is also indistinguishable from an error return in an i64, which is why the
mechanism half reports failure as PHP_INT_MIN.

async_accept_emfile drops NOFILE to 24, exhausts the table with a connection
already queued, and asserts that a SIBLING task completes its ten ticks while
the acceptor cannot accept. That is the non-flaky proof: a spinning accept loop
starves the sibling, where a backing-off one does not. Counting wakes would have
been the flaky way to ask the same question.
A child's exception is rethrown by whoever joins it, so it reaches user code
carrying the JOINER's file and line — the task that actually failed appears
nowhere in the trace. The exception cannot be made to say so: mutating a user's
throwable is impossible and wrapping it breaks `catch`. So the provenance rides
beside it.

  task #7 "worker" at jobs.php:31 raised RuntimeException: no such row
    in scope near jobs.php:12

Recorded in settle(), the only point that still knows both the task and the
error, and only for the FIRST real failure — everything after it is the
cancellation wave, and naming a task that was merely swept up is worse than
saying nothing. Read back with Async\failure(); written to STDERR on the same
channel and under the same knob as the watchdog, since a program that catches
and carries on does not need the noise. A static, because run() drops the
singleton before it rethrows, and cleared by every async() so a second run
cannot inherit the first one's blame.
The 5th argument was accepted and documented as ignored, leaving the OS's own
connect timeout in charge: a connect to a black-holed address took ~75 s of SYN
retries where php returns in the 0.3 s it was asked for. One AOT case sat at 76
seconds because of it, which is also how this surfaced — the new per-case
deadline turned "slow" into "reported".

Everything needed already existed: __mc_poll_one waits, __mc_so_error collects
the outcome. The sync path now makes the same non-blocking connect the async one
does and waits with poll(POLLOUT) instead of the reactor, then restores blocking
so nothing downstream meets an unexpected EAGAIN.
docs/async.md gains a "How much a task costs" section (the RSS-vs-stack table,
the two-mappings-per-fiber ceiling) and Async\failure() beside the other
diagnostics; fiber stack sizing leaves "Not yet" — what is left there is naming
a guard-page hit, which needs a sigaltstack handler.

PROBE_RESULTS gains the POSIX_RLIMIT_* table and the ceiling measurements, since
src/ hard-codes both and the file's own rule is that a table contradicting a
measurement means re-measuring first.
Two bugs in one path, both surfaced by bounding the sync connect.

poll(2) reports a refused connect as POLLERR/POLLHUP, which __mc_poll_one folds
into rc<0 — and that was being read as the deadline expiring, so ECONNREFUSED
came out as ETIMEDOUT. SO_ERROR is what carries the cause; only rc==0 is a
timeout.

Then the walk overwrote whatever the wait had recorded with the LIVE errno,
which after a wait is the EINPROGRESS that started it. So fsockopen reported
"Operation now in progress" where php reports "Connection refused". The async
path had the same hole — its ETIMEDOUT was overwritten identically — and nothing
caught it because no test read errno after an async connect failure.

fsockopen now matches php byte for byte again: errno 61, "Connection refused".
enable_crypto.php spends exactly 60 s under php, failing a handshake on a plain
socket through php's own default_socket_timeout. Bounding the reference at the
same 60 s as our binary made the oracle itself the finding.
Chasing per-task memory found it in the channel, not the arena. removeWaiter
rebuilt BOTH queues on every removal, so cancelling N tasks parked on one
channel was O(N^2) and allocated an N-sized array N times. It showed as a
per-task cost that GREW with the task count — 71 KiB each at 10k waiters, 111
KiB at 20k — and a scope of 40k channel waiters did not finish cancelling in ten
minutes. Every delivery also paid an array_shift, which re-indexes the whole
queue.

Both queues are cursor queues with tombstones now. A park records its own slot
on the Task, so a cancel nulls one entry in O(1); a delivery pops at the head
instead of shifting; and the consumed prefix is compacted once it is most of the
array, so a channel that is never idle does not grow for the life of the
process.

  channel-parked, peak RSS per task
  10k   71 KiB -> 25 KiB
  20k  111 KiB -> 24 KiB
  40k  (would not finish) -> 24 KiB

Flat now, and the same as a timer-parked task — the channel costs nothing extra.
A select() waiter still cannot carry one slot, because it sits in several
channels' queues at once; that path scans from the cursor rather than from zero,
and is the one removal left that is not O(1).
Running off the bottom of a fiber stack faults into the PROT_NONE guard page,
and the process died as a bare SIGSEGV — SIGBUS on Darwin — pointing at whatever
function happened to touch the page. It is the one crash whose cause is exactly
knowable, and nothing said it.

A handler on an alternate stack (the thread stack it would otherwise use is the
one that just overflowed) compares the faulting address against the RUNNING
fiber's guard page — the only one an overflow can hit — and writes
`manticore: fiber stack overflow (raise MANTICORE_FIBER_STACK)` before restoring
the default disposition and re-raising. So the process still dies exactly as it
did, with the same status and core, and any fault outside that page passes
through untouched: a genuine bad address still looks like a bad address.

Every layout this needs diverges and was MEASURED on both hosts, not recalled
(tools/docker/PROBE_RESULTS.md). Two of them bite: stack_t's ss_flags and
ss_size are in the OPPOSITE order, so one shared layout would set the alt-stack
size to zero; and the guard hit raises SIGBUS on Darwin against SIGSEGV on
Linux, so a handler on one signal prints nothing on the other host.

⚠ Adds two intrinsics that prelude/fiber.php calls, and the stdlib library build
compiles the prelude — so the FIRST build after this commit must be
`bin/build --seed`. A generation without them cannot build the tree.
The Linux gate caught it: "no limit" is spelled POSIX_RLIMIT_INFINITY, and that
constant carries the HOST's RLIM_INFINITY — PHP_INT_MAX on Darwin but -1 on
glibc. Translating PHP_INT_MAX to infinity on the way in looked portable and was
a divergence: on Linux php sets a finite limit of PHP_INT_MAX and reads back
that number, where we answered 'unlimited'.

Nothing is translated on the way in now. The way OUT still maps the host's
RLIM_INFINITY to 'unlimited', which is php's own shape.

Invisible on macOS, because there the two spellings are the same number — the
AOT case passed on both hosts throughout, since its expected output was captured
from macOS php. Only difftest, against the LOCAL php, could see it.
@blacktrs blacktrs changed the title Async liveness: bounded write parks, a classified accept loop, resolv.conf search/ndots Async under load: bounded parks, a non-quadratic channel, and a measured fiber stack Jul 28, 2026
@blacktrs
blacktrs merged commit cb438bf into main Jul 29, 2026
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.

1 participant